-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGitAttributesCommand.php
More file actions
284 lines (250 loc) · 10.5 KB
/
GitAttributesCommand.php
File metadata and controls
284 lines (250 loc) · 10.5 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
<?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\Console\Command;
use Composer\Command\BaseCommand;
use FastForward\DevTools\Composer\Json\ComposerJsonInterface;
use FastForward\DevTools\Console\Command\Traits\LogsCommandResults;
use FastForward\DevTools\Console\Input\HasJsonOption;
use FastForward\DevTools\Filesystem\FilesystemInterface;
use FastForward\DevTools\GitAttributes\CandidateProviderInterface;
use FastForward\DevTools\GitAttributes\ExistenceCheckerInterface;
use FastForward\DevTools\GitAttributes\ExportIgnoreFilterInterface;
use FastForward\DevTools\GitAttributes\MergerInterface;
use FastForward\DevTools\GitAttributes\ReaderInterface;
use FastForward\DevTools\GitAttributes\WriterInterface;
use FastForward\DevTools\Resource\FileDiffer;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use function Safe\getcwd;
/**
* Provides functionality to manage .gitattributes export-ignore rules.
*
* This command adds export-ignore entries for repository-only files and directories
* to keep them out of Composer package archives.
*/
#[AsCommand(
name: 'gitattributes',
description: 'Manages .gitattributes export-ignore rules for leaner package archives.'
)]
final class GitAttributesCommand extends BaseCommand implements LoggerAwareCommandInterface
{
use HasJsonOption;
use LogsCommandResults;
private const string FILENAME = '.gitattributes';
private const string EXTRA_NAMESPACE = 'gitattributes';
private const string EXTRA_KEEP_IN_EXPORT = 'keep-in-export';
private const string EXTRA_NO_EXPORT_IGNORE = 'no-export-ignore';
/**
* Creates a new GitAttributesCommand instance.
*
* @param CandidateProviderInterface $candidateProvider the candidate provider
* @param ExistenceCheckerInterface $existenceChecker the repository path existence checker
* @param ExportIgnoreFilterInterface $exportIgnoreFilter the configured candidate filter
* @param MergerInterface $merger the merger component
* @param ReaderInterface $reader the reader component
* @param WriterInterface $writer the writer component
* @param FilesystemInterface $filesystem the filesystem component
* @param ComposerJsonInterface $composer the composer.json accessor
* @param FileDiffer $fileDiffer
* @param LoggerInterface $logger the output-aware logger
*/
public function __construct(
private readonly CandidateProviderInterface $candidateProvider,
private readonly ExistenceCheckerInterface $existenceChecker,
private readonly ExportIgnoreFilterInterface $exportIgnoreFilter,
private readonly MergerInterface $merger,
private readonly ReaderInterface $reader,
private readonly WriterInterface $writer,
private readonly ComposerJsonInterface $composer,
private readonly FilesystemInterface $filesystem,
private readonly FileDiffer $fileDiffer,
private readonly LoggerInterface $logger,
) {
parent::__construct();
}
/**
* Configures verification and interactive update modes.
*/
protected function configure(): void
{
$this->setHelp(
'This command adds export-ignore entries for repository-only files and directories to keep them out of Composer package archives. '
. 'Only paths that exist in the repository are added, existing custom rules are preserved, and '
. '"extra.gitattributes.keep-in-export" paths stay in exported archives.'
);
$this->addJsonOption()
->addOption(
name: 'dry-run',
mode: InputOption::VALUE_NONE,
description: 'Preview .gitattributes synchronization without writing the file.',
)
->addOption(
name: 'check',
mode: InputOption::VALUE_NONE,
description: 'Report .gitattributes drift and exit non-zero when changes are required.',
)
->addOption(
name: 'interactive',
mode: InputOption::VALUE_NONE,
description: 'Prompt before updating .gitattributes.',
);
}
/**
* Configures the current command.
*
* This method MUST define the name, description, and help text for the command.
*
* @param InputInterface $input
* @param OutputInterface $output
*/
protected function execute(InputInterface $input, OutputInterface $output): int
{
$this->logger->info('Synchronizing .gitattributes export-ignore rules...', [
'input' => $input,
]);
$dryRun = (bool) $input->getOption('dry-run');
$check = (bool) $input->getOption('check');
$interactive = (bool) $input->getOption('interactive');
$basePath = getcwd();
$keepInExportPaths = $this->configuredKeepInExportPaths();
$folderCandidates = $this->exportIgnoreFilter->filter($this->candidateProvider->folders(), $keepInExportPaths);
$fileCandidates = $this->exportIgnoreFilter->filter($this->candidateProvider->files(), $keepInExportPaths);
$existingFolders = $this->existenceChecker->filterExisting($basePath, $folderCandidates);
$existingFiles = $this->existenceChecker->filterExisting($basePath, $fileCandidates);
$entries = [...$existingFolders, ...$existingFiles];
if ([] === $entries) {
$this->notice('No candidate paths found in repository. Skipping .gitattributes sync.', $input);
return $this->success(
'No .gitattributes synchronization changes were required.',
$input,
logLevel: 'notice',
);
}
$gitattributesPath = $this->filesystem->getAbsolutePath(self::FILENAME);
$existingContent = $this->reader->read($gitattributesPath);
$content = $this->merger->merge($existingContent, $entries, $keepInExportPaths);
$renderedContent = $this->writer->render($content);
$comparison = $this->fileDiffer->diffContents(
'generated .gitattributes synchronization',
$gitattributesPath,
$renderedContent,
'' === $existingContent ? null : $this->writer->render($existingContent),
\sprintf('Updating managed file %s from generated .gitattributes synchronization.', $gitattributesPath),
);
$this->logger->notice(
$comparison->getSummary(),
[
'input' => $input,
'gitattributes_path' => $gitattributesPath,
],
);
if ($comparison->isChanged()) {
$consoleDiff = $this->fileDiffer->formatForConsole($comparison->getDiff(), $output->isDecorated());
if (null !== $consoleDiff) {
$this->logger->notice(
$consoleDiff,
[
'input' => $input,
'gitattributes_path' => $gitattributesPath,
'diff' => $comparison->getDiff(),
],
);
}
}
if ($comparison->isUnchanged()) {
return $this->success('.gitattributes already matches the generated export-ignore rules.', $input);
}
if ($check) {
return $this->failure(
'.gitattributes requires synchronization updates.',
$input,
[
'gitattributes_path' => $gitattributesPath,
],
$gitattributesPath,
);
}
if ($dryRun) {
return $this->success(
'.gitattributes synchronization preview completed.',
$input,
[
'gitattributes_path' => $gitattributesPath,
],
'notice',
);
}
if ($interactive && $input->isInteractive() && ! $this->shouldWriteGitAttributes($gitattributesPath)) {
$this->notice(
'Skipped updating {gitattributes_path}.',
$input,
[
'gitattributes_path' => $gitattributesPath,
],
);
return $this->success(
'.gitattributes synchronization was skipped.',
$input,
[
'gitattributes_path' => $gitattributesPath,
],
'notice',
);
}
$this->writer->write($gitattributesPath, $content);
return $this->success(
'Added {entries_count} export-ignore entries to .gitattributes.',
$input,
[
'entries_count' => \count($entries),
'gitattributes_path' => $gitattributesPath,
],
);
}
/**
* Prompts whether .gitattributes should be updated.
*
* @param string $targetPath the target path that would be updated
*
* @return bool true when the update SHOULD proceed
*/
private function shouldWriteGitAttributes(string $targetPath): bool
{
return $this->getIO()
->askConfirmation(\sprintf('Update managed file %s? [y/N] ', $targetPath), false);
}
/**
* Resolves the consumer-defined paths that MUST stay in exported archives.
*
* The preferred configuration key is "extra.gitattributes.keep-in-export".
* The alternate "extra.gitattributes.no-export-ignore" key remains
* supported as a compatibility alias.
*
* @return list<string> the configured keep-in-export paths
*/
private function configuredKeepInExportPaths(): array
{
$extra = $this->composer->getExtra(self::EXTRA_NAMESPACE);
return array_unique(array_merge(
$extra[self::EXTRA_KEEP_IN_EXPORT] ?? [],
$extra[self::EXTRA_NO_EXPORT_IGNORE] ?? [],
));
}
}