Skip to content

Commit 8b9ddfd

Browse files
authored
Merge pull request #95 from wp-cli/dependencies-update
Add `wp maintenance dependencies update`
2 parents 364be38 + 572825d commit 8b9ddfd

12 files changed

Lines changed: 2188 additions & 140 deletions

‎.maintenance/src/Composer.php‎

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
<?php namespace WP_CLI\Maintenance;
2+
3+
use WP_CLI;
4+
use WP_CLI\Process;
5+
use WP_CLI\Utils;
6+
7+
/**
8+
* Runs Composer against the composer.json and composer.lock of a repository,
9+
* in a throwaway directory and without installing anything.
10+
*/
11+
final class Composer {
12+
13+
/**
14+
* Environment variables that would change what Composer checks, resolves
15+
* or reports, such as COMPOSER_NO_DEV dropping the dev packages, or
16+
* COMPOSER pointing it at another project.
17+
*/
18+
const ENV_OVERRIDES = [
19+
'COMPOSER',
20+
'COMPOSER_AUDIT_ABANDONED',
21+
'COMPOSER_AUTH',
22+
'COMPOSER_IGNORE_PLATFORM_REQ',
23+
'COMPOSER_IGNORE_PLATFORM_REQS',
24+
'COMPOSER_MINIMAL_CHANGES',
25+
'COMPOSER_NO_AUDIT',
26+
'COMPOSER_NO_DEV',
27+
'COMPOSER_NO_SECURITY_BLOCKING',
28+
'COMPOSER_PREFER_LOWEST',
29+
'COMPOSER_PREFER_STABLE',
30+
'COMPOSER_WITH_ALL_DEPENDENCIES',
31+
'COMPOSER_WITH_DEPENDENCIES',
32+
];
33+
34+
/**
35+
* Runs a Composer command in a temporary directory holding the given
36+
* files. Plugins and scripts stay disabled, so the repository's code
37+
* never runs.
38+
*
39+
* @param string[] $arguments Command and its arguments, such
40+
* as [ 'audit', '--locked' ].
41+
* @param array<string, string> $files File name => contents.
42+
* @param string[] $read_back Files to read back afterwards.
43+
* @param array<string, string> $env Extra environment variables.
44+
*
45+
* @return array{return_code: int, stdout: string, stderr: string, files: array<string, string|null>}
46+
*/
47+
public static function run( array $arguments, array $files, array $read_back = [], array $env = [] ) {
48+
$dir = Utils\get_temp_dir() . uniqid( 'wp-cli-maintenance-composer-', true );
49+
50+
$written = mkdir( $dir, 0700 ) && mkdir( "{$dir}/home", 0700 );
51+
foreach ( $files as $name => $contents ) {
52+
$written = $written && false !== file_put_contents( "{$dir}/{$name}", $contents );
53+
}
54+
55+
if ( ! $written ) {
56+
self::remove_directory( $dir );
57+
WP_CLI::error( "Could not write the files for Composer to the temporary directory {$dir}." );
58+
}
59+
60+
$arguments = array_merge(
61+
$arguments,
62+
[ '--no-interaction', '--no-plugins', '--no-scripts', "--working-dir={$dir}" ]
63+
);
64+
65+
$command = 'composer ' . implode( ' ', array_map( 'escapeshellarg', $arguments ) );
66+
$auth = GitHub::get_auth();
67+
$result = Process::create( $command, null, array_merge( self::get_env( (array) getenv(), "{$dir}/home", $auth['token'] ), $env ) )->run();
68+
69+
$contents = [];
70+
foreach ( $read_back as $name ) {
71+
$contents[ $name ] = is_file( "{$dir}/{$name}" ) ? (string) file_get_contents( "{$dir}/{$name}" ) : null;
72+
}
73+
74+
self::remove_directory( $dir );
75+
76+
if ( '' !== trim( $result->stderr ) ) {
77+
WP_CLI::debug( trim( $result->stderr ), 'composer' );
78+
}
79+
80+
return [
81+
'return_code' => (int) $result->return_code,
82+
'stdout' => (string) $result->stdout,
83+
'stderr' => (string) $result->stderr,
84+
'files' => $contents,
85+
];
86+
}
87+
88+
/**
89+
* Builds the environment for Composer: the current one, without the
90+
* variables that change its behavior, and with a Composer home of its
91+
* own, so that no global configuration, such as `audit.ignore` or extra
92+
* repositories, applies.
93+
*
94+
* @param array<string, string> $env Current environment.
95+
* @param string $composer_home Empty directory to use as
96+
* Composer home.
97+
* @param string|null $github_token Token to raise GitHub's API
98+
* rate limit for Composer.
99+
*
100+
* @return array<string, string>
101+
*/
102+
public static function get_env( array $env, $composer_home, $github_token = null ) {
103+
foreach ( self::ENV_OVERRIDES as $variable ) {
104+
unset( $env[ $variable ] );
105+
}
106+
107+
$env['COMPOSER_HOME'] = $composer_home;
108+
109+
if ( $github_token ) {
110+
$env['COMPOSER_AUTH'] = (string) json_encode( [ 'github-oauth' => [ 'github.com' => $github_token ] ] );
111+
}
112+
113+
return $env;
114+
}
115+
116+
private static function remove_directory( $dir ) {
117+
if ( ! is_dir( $dir ) ) {
118+
return;
119+
}
120+
121+
$entries = new \RecursiveIteratorIterator(
122+
new \RecursiveDirectoryIterator( $dir, \FilesystemIterator::SKIP_DOTS ),
123+
\RecursiveIteratorIterator::CHILD_FIRST
124+
);
125+
126+
foreach ( $entries as $entry ) {
127+
if ( $entry->isDir() && ! $entry->isLink() ) {
128+
rmdir( $entry->getPathname() );
129+
} else {
130+
unlink( $entry->getPathname() );
131+
}
132+
}
133+
134+
rmdir( $dir );
135+
}
136+
}

‎.maintenance/src/Dependencies_Command.php‎

Lines changed: 177 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
use WP_CLI\Utils;
66

77
/**
8-
* Checks the locked dependencies of the repositories that commit a
8+
* Checks and updates the locked dependencies of the repositories that commit a
99
* composer.lock, such as wp-cli/wp-cli-bundle.
1010
*/
1111
final class Dependencies_Command {
@@ -114,6 +114,182 @@ public function audit( $args, $assoc_args ) {
114114
}
115115
}
116116

117+
/**
118+
* Updates locked dependencies and proposes the new composer.lock as a pull request.
119+
*
120+
* By default, updates the packages that `wp maintenance dependencies
121+
* audit` reports security advisories for. The update runs within the
122+
* constraints of composer.json, which stays unchanged, and moves the
123+
* dependencies of the updated packages only as far as needed.
124+
*
125+
* The new composer.lock is audited again, then committed on top of the
126+
* default branch, and a pull request is opened from that commit. The branch
127+
* is named after the update: `update-dependencies-security` by default,
128+
* and after the packages with --packages. A later run of the same update
129+
* replaces that commit and refreshes the pull request, but never
130+
* overwrites a branch that someone else pushed to.
131+
*
132+
* Without --packages, exits with an error code when advisories are left
133+
* that the update cannot fix, as fixing them needs a change to
134+
* composer.json. For each of them, it says which version fixes it, and
135+
* what `composer why-not` says holds that version back, both here and in
136+
* the pull request.
137+
*
138+
* Needs Composer 2.7 or later. Works from the files on GitHub, so no clone
139+
* of the repository is needed.
140+
*
141+
* ## OPTIONS
142+
*
143+
* [<repo>...]
144+
* : Name(s) of the repository to update. If no user/org was provided,
145+
* 'wp-cli' org is assumed. Defaults to wp-cli/wp-cli-bundle. Repositories
146+
* without a composer.lock are skipped with a warning.
147+
*
148+
* [--packages=<packages>]
149+
* : Comma-separated list of packages to update instead, with their
150+
* dependencies. `*` matches any characters, so `symfony/*` updates all
151+
* locked Symfony packages and `*` refreshes the whole lock.
152+
*
153+
* [--dry-run]
154+
* : Show what the update changes, without pushing anything.
155+
*
156+
* [--yes]
157+
* : Push and open the pull request without asking for confirmation.
158+
*
159+
* ## EXAMPLES
160+
*
161+
* # Fix what the audit reports.
162+
* $ wp maintenance dependencies update --dry-run
163+
* +--------------------+---------+---------+-----+
164+
* | package | from | to | dev |
165+
* +--------------------+---------+---------+-----+
166+
* | symfony/config | v5.4.46 | v5.4.56 | yes |
167+
* | symfony/filesystem | v5.4.54 | v5.4.56 | yes |
168+
* | symfony/yaml | v5.4.54 | v5.4.56 | yes |
169+
* +--------------------+---------+---------+-----+
170+
* Fixes 3 security advisories.
171+
* Dry run: not pushing the new composer.lock of wp-cli/wp-cli-bundle.
172+
*
173+
* # Move the bundle to the latest commit of the framework.
174+
* $ wp maintenance dependencies update --packages=wp-cli/wp-cli --yes
175+
*
176+
* @when before_wp_load
177+
*/
178+
public function update( $args, $assoc_args ) {
179+
$dry_run = (bool) Utils\get_flag_value( $assoc_args, 'dry-run', false );
180+
$confirmed = (bool) Utils\get_flag_value( $assoc_args, 'yes', false );
181+
$packages = array_values( array_filter( array_map( 'trim', explode( ',', (string) Utils\get_flag_value( $assoc_args, 'packages', '' ) ) ), 'strlen' ) );
182+
$repos = $args ? array_values( array_unique( array_map( [ GitHub::class, 'qualify_repo' ], $args ) ) ) : [ Bundle::REPO ];
183+
184+
foreach ( $packages as $package ) {
185+
if ( '-' === $package[0] ) {
186+
WP_CLI::error( "'{$package}' is not a package name." );
187+
}
188+
}
189+
190+
$updated = false;
191+
$still_found = [];
192+
foreach ( $repos as $repo ) {
193+
$plan = Dependency_Update::prepare( $repo, $packages );
194+
195+
if ( null === $plan ) {
196+
WP_CLI::warning( "{$repo} has no composer.lock, skipping it." );
197+
continue;
198+
}
199+
200+
$updated = true;
201+
202+
if ( $plan['remaining'] ) {
203+
$still_found[] = $repo;
204+
}
205+
206+
foreach ( $plan['unmatched'] as $pattern ) {
207+
WP_CLI::warning( "{$pattern} matches no package locked in {$repo}." );
208+
}
209+
210+
if ( ! $plan['packages'] ) {
211+
if ( ! $plan['requested'] ) {
212+
WP_CLI::success( "No locked package of {$repo} has a security advisory, so there is nothing to update." );
213+
}
214+
continue;
215+
}
216+
217+
if ( ! $plan['changes'] ) {
218+
WP_CLI::warning( 'Updating ' . implode( ', ', $plan['packages'] ) . " changes no locked version of {$repo}." );
219+
$this->report_remaining( $plan );
220+
continue;
221+
}
222+
223+
Utils\format_items(
224+
'table',
225+
array_map(
226+
static function ( $change ) {
227+
return [
228+
'package' => $change['package'],
229+
'from' => null === $change['from'] ? '(new)' : $change['from'],
230+
'to' => null === $change['to'] ? '(removed)' : $change['to'],
231+
'dev' => $change['dev'] ? 'yes' : 'no',
232+
];
233+
},
234+
$plan['changes']
235+
),
236+
[ 'package', 'from', 'to', 'dev' ]
237+
);
238+
239+
if ( $plan['fixed'] ) {
240+
WP_CLI::log( sprintf( 'Fixes %d security %s.', count( $plan['fixed'] ), 1 === count( $plan['fixed'] ) ? 'advisory' : 'advisories' ) );
241+
}
242+
$this->report_remaining( $plan );
243+
244+
if ( $dry_run ) {
245+
WP_CLI::log( "Dry run: not pushing the new composer.lock of {$repo}." );
246+
continue;
247+
}
248+
249+
if ( ! $confirmed && ! Prompt::confirm( "Push the new composer.lock to the {$plan['head']} branch of {$repo} and open a pull request?" ) ) {
250+
WP_CLI::log( "Skipping {$repo}." );
251+
continue;
252+
}
253+
254+
list( $pull_request, $pushed ) = Dependency_Update::publish( $plan );
255+
256+
if ( ! $pushed ) {
257+
WP_CLI::log( "The {$plan['head']} branch already holds this composer.lock, so only the pull request was refreshed." );
258+
}
259+
WP_CLI::success( "Pull request for {$repo}: {$pull_request->html_url}" );
260+
}
261+
262+
if ( ! $updated ) {
263+
WP_CLI::error( 'None of the repositories has a composer.lock to update.' );
264+
}
265+
266+
// An explicit list of packages may leave advisories alone on purpose.
267+
if ( $still_found && ! $packages ) {
268+
WP_CLI::error( 'Locked packages are still affected by security advisories in ' . implode( ', ', $still_found ) . '. Fixing them needs a change to composer.json.' );
269+
}
270+
}
271+
272+
private function report_remaining( array $plan ) {
273+
foreach ( $plan['remaining'] as $advisory ) {
274+
$message = "{$advisory['package']} {$advisory['version']} is still affected by {$advisory['advisory']}: {$advisory['title']}";
275+
276+
if ( ! empty( $advisory['fixed_in'] ) ) {
277+
$message .= "\nIt is fixed in {$advisory['fixed_in']}";
278+
279+
if ( ! empty( $advisory['held_back_by'] ) ) {
280+
$message .= ', which is held back by:';
281+
foreach ( $advisory['held_back_by'] as $reason ) {
282+
$message .= "\n {$reason}";
283+
}
284+
} else {
285+
$message .= '.';
286+
}
287+
}
288+
289+
WP_CLI::warning( $message );
290+
}
291+
}
292+
117293
private function render_table( array $audits ) {
118294
$rows = [];
119295
foreach ( $audits as $audit ) {

0 commit comments

Comments
 (0)