-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMerger.php
More file actions
341 lines (282 loc) · 10.4 KB
/
Merger.php
File metadata and controls
341 lines (282 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
<?php
declare(strict_types=1);
/**
* Fast Forward Development Tools for PHP projects.
*
* This file is part of fast-forward/dev-tools project.
*
* @author Felipe Sayão Lobato Abreu <github@mentordosnerds.com>
* @license https://opensource.org/licenses/MIT MIT License
*
* @see https://github.com/php-fast-forward/
* @see https://github.com/php-fast-forward/dev-tools
* @see https://github.com/php-fast-forward/dev-tools/issues
* @see https://php-fast-forward.github.io/dev-tools/
* @see https://datatracker.ietf.org/doc/html/rfc2119
*/
namespace FastForward\DevTools\GitAttributes;
use function Safe\preg_split;
use function Safe\preg_replace;
use function Safe\preg_match;
/**
* Merges .gitattributes content with generated export-ignore rules.
*
* This class preserves existing custom entries while adding missing
* export-ignore rules for known candidate paths, deduplicates semantically
* equivalent entries, and sorts export-ignore rules with directories before
* files.
*/
final class Merger implements MergerInterface
{
/**
* Merges generated export-ignore entries with existing .gitattributes content.
*
* This method:
* 1. Preserves custom user-defined entries in their original order
* 2. Adds missing generated export-ignore entries for existing paths
* 3. Deduplicates entries using normalized path comparison
* 4. Sorts export-ignore entries with directories before files
*
* @param string $existingContent The raw .gitattributes content currently stored.
* @param list<string> $exportIgnoreEntries the export-ignore entries to manage
* @param list<string> $keepInExportPaths the paths that MUST remain exported
*
* @return string The merged .gitattributes content
*/
public function merge(string $existingContent, array $exportIgnoreEntries, array $keepInExportPaths = []): string
{
$nonExportIgnoreLines = [];
$seenNonExportIgnoreLines = [];
$exportIgnoreLines = [];
$keptExportLookup = $this->keepInExportLookup($keepInExportPaths);
$generatedDirectoryLookup = $this->generatedDirectoryLookup($exportIgnoreEntries);
foreach ($this->parseExistingLines($existingContent) as $line) {
$normalizedLine = $this->normalizeLine($line);
if ('' === $normalizedLine) {
continue;
}
$pathSpec = $this->extractExportIgnorePathSpec($normalizedLine);
if (null === $pathSpec) {
if (isset($seenNonExportIgnoreLines[$normalizedLine])) {
continue;
}
$nonExportIgnoreLines[] = $normalizedLine;
$seenNonExportIgnoreLines[$normalizedLine] = true;
continue;
}
$pathKey = $this->normalizePathKey($pathSpec);
if ($this->isKeptPath($pathKey, $keptExportLookup)) {
continue;
}
if (isset($exportIgnoreLines[$pathKey])) {
continue;
}
$exportIgnoreLines[$pathKey] = [
'line' => $normalizedLine,
'sort_key' => $this->sortKey($pathSpec),
'is_directory' => str_ends_with($pathSpec, '/') || isset($generatedDirectoryLookup[$pathKey]),
];
}
foreach ($exportIgnoreEntries as $entry) {
$trimmedEntry = trim($entry);
$pathKey = $this->normalizePathKey($trimmedEntry);
if ($this->isKeptPath($pathKey, $keptExportLookup)) {
continue;
}
if (! isset($exportIgnoreLines[$pathKey])) {
$exportIgnoreLines[$pathKey] = [
'line' => $trimmedEntry . ' export-ignore',
'sort_key' => $this->sortKey($trimmedEntry),
'is_directory' => str_ends_with($trimmedEntry, '/'),
];
continue;
}
$exportIgnoreLines[$pathKey]['is_directory'] = $exportIgnoreLines[$pathKey]['is_directory']
|| str_ends_with($trimmedEntry, '/');
}
$sortedExportIgnoreLines = array_values($exportIgnoreLines);
usort(
$sortedExportIgnoreLines,
static function (array $left, array $right): int {
if ($left['is_directory'] !== $right['is_directory']) {
return $left['is_directory'] ? -1 : 1;
}
$naturalOrder = strnatcasecmp($left['sort_key'], $right['sort_key']);
if (0 !== $naturalOrder) {
return $naturalOrder;
}
return strcmp($left['sort_key'], $right['sort_key']);
}
);
return implode("\n", [...$nonExportIgnoreLines, ...array_column($sortedExportIgnoreLines, 'line')]);
}
/**
* Parses the raw .gitattributes content into trimmed non-empty lines.
*
* @param string $content The full .gitattributes content.
*
* @return list<string> the non-empty lines from the file
*/
private function parseExistingLines(string $content): array
{
if ('' === $content) {
return [];
}
$lines = [];
foreach (preg_split('/\R/', $content) as $line) {
$trimmedLine = trim((string) $line);
if ('' === $trimmedLine) {
continue;
}
$lines[] = $trimmedLine;
}
return $lines;
}
/**
* Builds a lookup table for paths that MUST stay in the exported archive.
*
* @param list<string> $keepInExportPaths the configured keep-in-export paths
*
* @return array<string, true> the normalized path lookup
*/
private function keepInExportLookup(array $keepInExportPaths): array
{
$lookup = [];
foreach ($keepInExportPaths as $path) {
$normalizedPath = $this->normalizePathKey($path);
if ('' === $normalizedPath) {
continue;
}
$lookup[$normalizedPath] = true;
}
return $lookup;
}
/**
* @param string $pathKey
* @param array<string, true> $keptExportLookup
*/
private function isKeptPath(string $pathKey, array $keptExportLookup): bool
{
foreach (array_keys($keptExportLookup) as $keptPath) {
if ($pathKey === $keptPath || str_starts_with($pathKey . '/', $keptPath . '/')) {
return true;
}
}
return false;
}
/**
* Builds a lookup table of generated directory candidates.
*
* @param list<string> $exportIgnoreEntries the generated export-ignore path list
*
* @return array<string, true> the normalized directory lookup
*/
private function generatedDirectoryLookup(array $exportIgnoreEntries): array
{
$lookup = [];
foreach ($exportIgnoreEntries as $entry) {
$trimmedEntry = trim($entry);
if (! str_ends_with($trimmedEntry, '/')) {
continue;
}
$lookup[$this->normalizePathKey($trimmedEntry)] = true;
}
return $lookup;
}
/**
* Normalizes a .gitattributes line for deterministic comparison and output.
*
* @param string $line the raw line to normalize
*
* @return string the normalized line
*/
private function normalizeLine(string $line): string
{
$trimmedLine = trim($line);
if ('' === $trimmedLine) {
return '';
}
if (str_starts_with($trimmedLine, '#')) {
return $trimmedLine;
}
return preg_replace('/(?<!\\\\)[ \t]+/', ' ', $trimmedLine) ?? $trimmedLine;
}
/**
* Extracts the path spec from a simple export-ignore line.
*
* @param string $line the line to inspect
*
* @return string|null the extracted path spec when the line is a simple export-ignore rule
*/
private function extractExportIgnorePathSpec(string $line): ?string
{
if (1 !== preg_match('/^(\S+)\s+export-ignore$/', $line, $matches)) {
return null;
}
return $matches[1];
}
/**
* Builds the natural sort key for a path spec.
*
* @param string $pathSpec the raw path spec to normalize for sorting
*
* @return string the natural sort key
*/
private function sortKey(string $pathSpec): string
{
return ltrim($this->normalizePathSpec($pathSpec), '/');
}
/**
* Normalizes a gitattributes path spec for sorting.
*
* @param string $pathSpec the raw path spec to normalize
*
* @return string the normalized path spec
*/
private function normalizePathSpec(string $pathSpec): string
{
$trimmedPathSpec = trim($pathSpec);
if ('' === $trimmedPathSpec) {
return '';
}
$isDirectory = str_ends_with($trimmedPathSpec, '/');
$normalizedPathSpec = preg_replace('#/+#', '/', '/' . ltrim($trimmedPathSpec, '/')) ?? $trimmedPathSpec;
$normalizedPathSpec = '/' === $normalizedPathSpec ? $normalizedPathSpec : rtrim($normalizedPathSpec, '/');
if ($isDirectory && '/' !== $normalizedPathSpec) {
$normalizedPathSpec .= '/';
}
return $normalizedPathSpec;
}
/**
* Normalizes a path spec for deduplication and keep-in-export matching.
*
* Literal root paths are compared without leading slash differences, while
* pattern-based specs preserve their original anchoring semantics.
*
* @param string $pathSpec the raw path spec to normalize
*
* @return string the normalized deduplication key
*/
private function normalizePathKey(string $pathSpec): string
{
$normalizedPathSpec = $this->normalizePathSpec($pathSpec);
if ($this->isLiteralPathSpec($normalizedPathSpec)) {
return ltrim(rtrim($normalizedPathSpec, '/'), '/');
}
return $normalizedPathSpec;
}
/**
* Determines whether a path spec is a literal path and not a glob pattern.
*
* @param string $pathSpec the normalized path spec to inspect
*
* @return bool true when the path spec is a literal path
*/
private function isLiteralPathSpec(string $pathSpec): bool
{
return ! str_contains($pathSpec, '*')
&& ! str_contains($pathSpec, '?')
&& ! str_contains($pathSpec, '[')
&& ! str_contains($pathSpec, '{');
}
}