-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGitHooksCommand.php
More file actions
305 lines (271 loc) · 10.4 KB
/
GitHooksCommand.php
File metadata and controls
305 lines (271 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
<?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\Console\Command\Traits\LogsCommandResults;
use FastForward\DevTools\Console\Input\HasJsonOption;
use FastForward\DevTools\Filesystem\FinderFactoryInterface;
use FastForward\DevTools\Filesystem\FilesystemInterface;
use FastForward\DevTools\Resource\FileDiffer;
use Psr\Log\LoggerInterface;
use Symfony\Component\Config\FileLocatorInterface;
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 Symfony\Component\Filesystem\Exception\IOExceptionInterface;
use Symfony\Component\Filesystem\Path;
/**
* Installs packaged Git hooks for the consumer repository.
*/
#[AsCommand(
name: 'git-hooks',
description: 'Installs Fast Forward Git hooks.',
help: 'This command copies packaged Git hooks into the current repository.'
)]
final class GitHooksCommand extends BaseCommand implements LoggerAwareCommandInterface
{
use HasJsonOption;
use LogsCommandResults;
/**
* Creates a new GitHooksCommand instance.
*
* @param FilesystemInterface $filesystem the filesystem used to copy hooks
* @param FileLocatorInterface $fileLocator the locator used to find packaged hooks
* @param FinderFactoryInterface $finderFactory the factory used to create finders for hook files
* @param FileDiffer $fileDiffer
* @param LoggerInterface $logger the output-aware logger
*/
public function __construct(
private readonly FilesystemInterface $filesystem,
private readonly FileLocatorInterface $fileLocator,
private readonly FinderFactoryInterface $finderFactory,
private readonly FileDiffer $fileDiffer,
private readonly LoggerInterface $logger,
) {
parent::__construct();
}
/**
* Configures hook source, target, and initialization options.
*/
protected function configure(): void
{
$this->addJsonOption()
->addOption(
name: 'source',
shortcut: 's',
mode: InputOption::VALUE_OPTIONAL,
description: 'Path to the packaged Git hooks directory.',
default: 'resources/git-hooks',
)
->addOption(
name: 'target',
shortcut: 't',
mode: InputOption::VALUE_OPTIONAL,
description: 'Path to the target Git hooks directory.',
default: '.git/hooks',
)
->addOption(
name: 'no-overwrite',
mode: InputOption::VALUE_NONE,
description: 'Do not overwrite existing hook files.',
)
->addOption(
name: 'dry-run',
mode: InputOption::VALUE_NONE,
description: 'Preview Git hook synchronization without copying files.',
)
->addOption(
name: 'check',
mode: InputOption::VALUE_NONE,
description: 'Report Git hook drift and exit non-zero when replacements are required.',
)
->addOption(
name: 'interactive',
mode: InputOption::VALUE_NONE,
description: 'Prompt before replacing drifted Git hooks.',
);
}
/**
* Copies packaged Git hooks.
*
* @param InputInterface $input the command input
* @param OutputInterface $output the command output
*
* @return int the command status code
*/
protected function execute(InputInterface $input, OutputInterface $output): int
{
$sourcePath = $this->fileLocator->locate((string) $input->getOption('source'));
$targetPath = (string) $this->filesystem->getAbsolutePath((string) $input->getOption('target'));
$overwrite = ! $input->getOption('no-overwrite');
$dryRun = (bool) $input->getOption('dry-run');
$check = (bool) $input->getOption('check');
$interactive = (bool) $input->getOption('interactive');
$files = $this->finderFactory
->create()
->files()
->in($sourcePath);
$checkFailure = false;
$installFailure = false;
foreach ($files as $file) {
$hookPath = Path::join($targetPath, $file->getRelativePathname());
if (! $overwrite && ! $dryRun && ! $check && ! $interactive && $this->filesystem->exists($hookPath)) {
$this->notice(
'Skipped existing {hook_name} hook.',
$input,
[
'hook_name' => $file->getFilename(),
'hook_path' => $hookPath,
],
);
continue;
}
if (($overwrite || $dryRun || $check || $interactive) && $this->filesystem->exists($hookPath)) {
$comparison = $this->fileDiffer->diff($file->getRealPath(), $hookPath);
$this->logger->notice(
$comparison->getSummary(),
[
'input' => $input,
'hook_name' => $file->getFilename(),
'hook_path' => $hookPath,
],
);
if ($comparison->isChanged()) {
$consoleDiff = $this->fileDiffer->formatForConsole($comparison->getDiff(), $output->isDecorated());
if (null !== $consoleDiff) {
$this->logger->notice(
$consoleDiff,
[
'input' => $input,
'hook_name' => $file->getFilename(),
'hook_path' => $hookPath,
'diff' => $comparison->getDiff(),
],
);
}
}
if ($comparison->isUnchanged()) {
continue;
}
if ($check) {
$checkFailure = true;
continue;
}
if ($dryRun) {
continue;
}
if ($interactive && $input->isInteractive() && ! $this->shouldReplaceHook($hookPath)) {
$this->notice(
'Skipped replacing {hook_path}.',
$input,
[
'hook_name' => $file->getFilename(),
'hook_path' => $hookPath,
],
);
continue;
}
}
if (! $this->installHook($file->getRealPath(), $hookPath, $overwrite || $interactive, $input)) {
$installFailure = true;
continue;
}
$this->success(
'Installed {hook_name} hook.',
$input,
[
'hook_name' => $file->getFilename(),
'hook_path' => $hookPath,
],
);
}
if ($checkFailure) {
return $this->failure(
'One or more Git hooks require synchronization updates.',
$input,
[
'target' => $targetPath,
],
$targetPath,
);
}
if ($installFailure) {
return $this->failure(
'One or more Git hooks could not be installed automatically.',
$input,
[
'target' => $targetPath,
],
$targetPath,
);
}
return $this->success(
'Git hook synchronization completed successfully.',
$input,
[
'target' => $targetPath,
],
);
}
/**
* Prompts whether a drifted hook should be replaced.
*
* @param string $hookPath the hook path that would be replaced
*
* @return bool true when the replacement SHOULD proceed
*/
private function shouldReplaceHook(string $hookPath): bool
{
return $this->getIO()
->askConfirmation(\sprintf('Replace drifted Git hook %s? [y/N] ', $hookPath), false);
}
/**
* Installs a single hook and rewrites drifted targets defensively.
*
* @param string $sourcePath the packaged hook path
* @param string $hookPath the target repository hook path
* @param bool $replaceExisting whether an existing hook SHOULD be removed first
* @param InputInterface $input the originating command input
*
* @return bool true when the hook was installed successfully
*/
private function installHook(string $sourcePath, string $hookPath, bool $replaceExisting, InputInterface $input): bool
{
try {
if ($replaceExisting && $this->filesystem->exists($hookPath)) {
$this->filesystem->remove($hookPath);
}
$this->filesystem->copy($sourcePath, $hookPath, false);
$this->filesystem->chmod(files: $hookPath, mode: 0o755);
return true;
} catch (IOExceptionInterface $exception) {
$this->logger->error(
'Failed to install {hook_name} hook automatically. Remove or unlock {hook_path} and rerun git-hooks.',
[
'input' => $input,
'hook_name' => $this->filesystem->basename($hookPath),
'hook_path' => $hookPath,
'error' => $exception->getMessage(),
'file' => $exception->getPath() ?? $hookPath,
'line' => null,
],
);
return false;
}
}
}