-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
composer-updater
executable file
·330 lines (287 loc) · 12.6 KB
/
composer-updater
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
#!/usr/bin/env php
<?php
declare(strict_types=1);
/**
* This file is part of the guanguans/laravel-soar.
*
* (c) guanguans <[email protected]>
*
* This source file is subject to the MIT license that is bundled.
*/
use Composer\InstalledVersions;
use SebastianBergmann\Diff\Differ;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\SingleCommandApplication;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Process\ExecutableFinder;
use Symfony\Component\Process\PhpExecutableFinder;
use Symfony\Component\Process\Process;
require __DIR__.'/vendor/autoload.php';
/** @noinspection PhpUnhandledExceptionInspection */
$status = (new SingleCommandApplication())
->setName('Composer Updater')
->addOption('composer-json-path', null, InputOption::VALUE_OPTIONAL)
->addOption('highest-php-binary', null, InputOption::VALUE_REQUIRED)
->addOption('composer-binary', null, InputOption::VALUE_OPTIONAL)
->addOption('except-packages', null, InputOption::VALUE_IS_ARRAY | InputOption::VALUE_OPTIONAL)
->addOption('except-dependency-versions', null, InputOption::VALUE_IS_ARRAY | InputOption::VALUE_OPTIONAL)
->addOption('dry-run', null, InputOption::VALUE_NONE)
->setCode(function (InputInterface $input, OutputInterface $output): void {
assert_options(ASSERT_BAIL, 1);
assert($this instanceof SingleCommandApplication);
assert((bool) $input->getOption('highest-php-binary'));
(new class (
$input->getOption('composer-json-path') ?: __DIR__.'/composer.json',
$input->getOption('highest-php-binary'),
$input->getOption('composer-binary'),
$input->getOption('except-packages'),
$input->getOption('except-dependency-versions'),
$input->getOption('dry-run'),
new SymfonyStyle($input, $output),
new Differ(),
) {
private string $composerJsonPath;
private string $composerJsonContents;
private string $highestComposerBinary;
private string $composerBinary;
private array $exceptPackages;
private array $exceptDependencyVersions;
private bool $dryRun;
private SymfonyStyle $symfonyStyle;
private Differ $differ;
/**
* @noinspection ParameterDefaultsNullInspection
*/
public function __construct(
string $composerJsonPath,
?string $highestPhpBinary = null,
?string $composerBinary = null,
array $exceptPackages = [],
array $exceptDependencyVersions = [],
bool $dryRun = false,
?SymfonyStyle $symfonyStyle = null,
?Differ $differ = null
) {
assert_options(ASSERT_BAIL, 1);
assert((bool) $composerJsonPath);
$this->composerJsonPath = $composerJsonPath;
$this->composerJsonContents = file_get_contents($composerJsonPath);
$this->highestComposerBinary = $this->getComposerBinary($composerBinary, $highestPhpBinary);
$this->composerBinary = $this->getComposerBinary($composerBinary);
$this->exceptPackages = array_merge([
'php',
'ext-*',
], $exceptPackages);
$this->exceptDependencyVersions = array_merge([
'\*',
'*-*',
'*@*',
// '*|*',
], $exceptDependencyVersions);
$this->dryRun = $dryRun;
$this->symfonyStyle = $symfonyStyle ?? new SymfonyStyle(new ArgvInput(), new ConsoleOutput());
$this->differ = $differ ?? new Differ();
}
public function __invoke(): void
{
$this
->updateComposerPackages()
->updateOutdatedComposerPackages()
->updateComposerPackages()
->updateOutdatedComposerPackages()
->updateComposerPackages()
->normalizeComposerJson()
->success();
}
private function updateComposerPackages(): self
{
$this->mustRunCommand("$this->composerBinary update -W --ansi");
return $this;
}
/**
* @noinspection JsonEncodingApiUsageInspection
*
* @return $this|never-return
*/
private function updateOutdatedComposerPackages(): self
{
$outdatedComposerJsonContents = json_encode(
$this->getOutdatedDecodedComposerJson(),
JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
).PHP_EOL;
if ($this->dryRun) {
$this->symfonyStyle->writeln($this->formatDiff($this->differ->diff(
$this->composerJsonContents,
$outdatedComposerJsonContents
)));
exit(0);
}
file_put_contents($this->composerJsonPath, $outdatedComposerJsonContents);
return $this;
}
private function normalizeComposerJson(): self
{
$this->mustRunCommand("$this->composerBinary normalize --diff --ansi");
return $this;
}
private function success(): void
{
$this->symfonyStyle->success('Composer packages updated successfully!');
}
/**
* @noinspection JsonEncodingApiUsageInspection
*/
private function getOutdatedDecodedComposerJson(): array
{
$outdatedComposerPackages = $this->getOutdatedComposerPackages();
$decodedComposerJson = json_decode(file_get_contents($this->composerJsonPath), true);
(fn () => self::reload(null))->call(new InstalledVersions());
foreach ($decodedComposerJson as $name => &$value) {
if (! in_array($name, ['require', 'require-dev'], true)) {
continue;
}
foreach ($value as $package => &$dependencyVersion) {
if (
$this->strIs($this->exceptPackages, $package)
|| $this->strIs($this->exceptDependencyVersions, $dependencyVersion)
) {
continue;
}
if ($version = InstalledVersions::getVersion($package)) {
$dependencyVersion = $this->toDependencyVersion($version);
}
if (isset($outdatedComposerPackages[$package])) {
$dependencyVersion = $outdatedComposerPackages[$package]['dependency_version'];
}
}
}
return $decodedComposerJson;
}
/**
* @noinspection JsonEncodingApiUsageInspection
*/
private function getOutdatedComposerPackages(): array
{
return array_reduce(
json_decode(
$this
->mustRunCommand("$this->highestComposerBinary outdated --format=json --direct --ansi")
->getOutput(),
true
)['installed'],
function (array $carry, array $package): array {
$lowestArrayVersion = $this->toArrayVersion($package['version']);
$highestArrayVersion = $this->toArrayVersion($package['latest']);
$dependencyVersions = [$this->toDependencyVersion($package['version'])];
if ($lowestArrayVersion[0] !== $highestArrayVersion[0]) {
$dependencyVersions = array_merge($dependencyVersions, array_map(
static fn (string $major): string => "^$major.0",
range($lowestArrayVersion[0] + 1, $highestArrayVersion[0])
));
}
$package['dependency_version'] = implode(' || ', $dependencyVersions);
$carry[$package['name']] = $package;
return $carry;
},
[]
);
}
private function getComposerBinary(?string $composerBinary = null, ?string $phpBinary = null): string
{
return sprintf(
'%s %s',
$phpBinary ?? (new PhpExecutableFinder())->find(),
$composerBinary ?? (new ExecutableFinder())->find('composer')
);
}
/**
* @param array|string $command
* @param mixed $input The input as stream resource, scalar or \Traversable, or null for no input
*
* @noinspection MissingParameterTypeDeclarationInspection
* @noinspection PhpSameParameterValueInspection
*/
private function mustRunCommand(
$command,
?string $cwd = null,
?array $env = null,
$input = null,
?float $timeout = 300
): Process {
$process = is_string($command)
? Process::fromShellCommandline($command, $cwd, $env, $input, $timeout)
: new Process($command, $cwd, $env, $input, $timeout);
$this->symfonyStyle->warning($process->getCommandLine());
return $process
->setWorkingDirectory(dirname($this->composerJsonPath))
->setEnv(['COMPOSER_MEMORY_LIMIT' => -1])
->mustRun(function (string $type, string $buffer): void {
$this->symfonyStyle->isVerbose() and $this->symfonyStyle->write($buffer);
});
}
private function toDependencyVersion(string $version): string
{
return '^'.implode('.', array_slice($this->toArrayVersion($version), 0, 2));
}
private function toArrayVersion(string $version): array
{
return explode('.', ltrim($version, 'v'));
}
/**
* @param array|string $pattern
*
* @noinspection SuspiciousLoopInspection
* @noinspection ComparisonScalarOrderInspection
* @noinspection MissingParameterTypeDeclarationInspection
*/
private function strIs($pattern, string $value): bool
{
$patterns = (array) $pattern;
if (empty($patterns)) {
return false;
}
foreach ($patterns as $pattern) {
$pattern = (string) $pattern;
if ($pattern === $value) {
return true;
}
$pattern = preg_quote($pattern, '#');
$pattern = str_replace('\*', '.*', $pattern);
if (1 === preg_match('#^'.$pattern.'\z#u', $value)) {
return true;
}
}
return false;
}
private function formatDiff(string $diff): string
{
$lines = explode(
"\n",
$diff,
);
$formatted = array_map(static function (string $line): string {
return preg_replace(
[
'/^(\+.*)$/',
'/^(-.*)$/',
],
[
'<fg=green>$1</>',
'<fg=red>$1</>',
],
$line,
);
}, $lines);
return implode(
"\n",
$formatted,
);
}
})();
})
->run();
exit($status);