3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
19 * @ingroup Maintenance
22 require_once __DIR__
. '/../Maintenance.php';
25 * Manage foreign resources registered with ResourceLoader.
27 * @ingroup Maintenance
30 class ManageForeignResources
extends Maintenance
{
31 private $defaultAlgo = 'sha384';
32 private $tmpParentDir;
34 private $failAfterOutput = false;
36 public function __construct() {
38 parent
::__construct();
39 $this->addDescription( <<<TEXT
40 Manage foreign resources registered with ResourceLoader.
42 This helps developers to download, verify and update local copies of upstream
43 libraries registered as ResourceLoader modules. See also foreign-resources.yaml.
45 For sources that don't publish an integrity hash, omit "integrity" (or leave empty)
46 and run the "make-sri" action to compute the missing hashes.
48 This script runs in dry mode by default. Use --update to actually change, remove,
49 or add files to /resources/lib/.
52 $this->addArg( 'action', 'One of "update", "verify" or "make-sri"', true );
53 $this->addArg( 'module', 'Name of a single module (Default: all)', false );
54 $this->addOption( 'verbose', 'Be verbose', false, false, 'v' );
56 // Use a directory in $IP instead of wfTempDir() because
57 // PHP's rename() does not work across file systems.
58 $this->tmpParentDir
= "{$IP}/resources/tmp";
61 public function execute() {
63 $this->action
= $this->getArg( 0 );
64 if ( !in_array( $this->action
, [ 'update', 'verify', 'make-sri' ] ) ) {
65 $this->fatalError( "Invalid action argument." );
68 $registry = $this->parseBasicYaml(
69 file_get_contents( __DIR__
. '/foreign-resources.yaml' )
71 $module = $this->getArg( 1, 'all' );
72 foreach ( $registry as $moduleName => $info ) {
73 if ( $module !== 'all' && $moduleName !== $module ) {
76 $this->verbose( "\n### {$moduleName}\n\n" );
77 $destDir = "{$IP}/resources/lib/$moduleName";
79 if ( $this->action
=== 'update' ) {
80 $this->output( "... updating '{$moduleName}'\n" );
81 $this->verbose( "... emptying /resources/lib/$moduleName\n" );
82 wfRecursiveRemoveDir( $destDir );
83 } elseif ( $this->action
=== 'verify' ) {
84 $this->output( "... verifying '{$moduleName}'\n" );
86 $this->output( "... checking '{$moduleName}'\n" );
89 $this->verbose( "... preparing {$this->tmpParentDir}\n" );
90 wfRecursiveRemoveDir( $this->tmpParentDir
);
91 if ( !wfMkdirParents( $this->tmpParentDir
) ) {
92 $this->fatalError( "Unable to create {$this->tmpParentDir}" );
95 if ( !isset( $info['type'] ) ) {
96 $this->fatalError( "Module '$moduleName' must have a 'type' key." );
98 switch ( $info['type'] ) {
100 $this->handleTypeTar( $moduleName, $destDir, $info );
103 $this->handleTypeFile( $moduleName, $destDir, $info );
106 $this->handleTypeMultiFile( $moduleName, $destDir, $info );
109 $this->fatalError( "Unknown type '{$info['type']}' for '$moduleName'" );
114 $this->output( "\nDone!\n" );
115 if ( $this->failAfterOutput
) {
116 // The verify mode should check all modules/files and fail after, not during.
121 private function fetch( $src, $integrity ) {
122 $data = Http
::get( $src, [ 'followRedirects' => false ] );
123 if ( $data === false ) {
124 $this->fatalError( "Failed to download resource at {$src}" );
126 $algo = $integrity === null ?
$this->defaultAlgo
: explode( '-', $integrity )[0];
127 $actualIntegrity = $algo . '-' . base64_encode( hash( $algo, $data, true ) );
128 if ( $integrity === $actualIntegrity ) {
129 $this->verbose( "... passed integrity check for {$src}\n" );
131 if ( $this->action
=== 'make-sri' ) {
132 $this->output( "Integrity for {$src}\n\tintegrity: ${actualIntegrity}\n" );
134 $this->fatalError( "Integrity check failed for {$src}\n" .
135 "\tExpected: {$integrity}\n" .
136 "\tActual: {$actualIntegrity}"
143 private function handleTypeFile( $moduleName, $destDir, array $info ) {
144 if ( !isset( $info['src'] ) ) {
145 $this->fatalError( "Module '$moduleName' must have a 'src' key." );
147 $data = $this->fetch( $info['src'], $info['integrity'] ??
null );
148 $dest = $info['dest'] ??
basename( $info['src'] );
149 $path = "$destDir/$dest";
150 if ( $this->action
=== 'verify' && sha1_file( $path ) !== sha1( $data ) ) {
151 $this->fatalError( "File for '$moduleName' is different." );
152 } elseif ( $this->action
=== 'update' ) {
153 wfMkdirParents( $destDir );
154 file_put_contents( "$destDir/$dest", $data );
158 private function handleTypeMultiFile( $moduleName, $destDir, array $info ) {
159 if ( !isset( $info['files'] ) ) {
160 $this->fatalError( "Module '$moduleName' must have a 'files' key." );
162 foreach ( $info['files'] as $dest => $file ) {
163 if ( !isset( $file['src'] ) ) {
164 $this->fatalError( "Module '$moduleName' file '$dest' must have a 'src' key." );
166 $data = $this->fetch( $file['src'], $file['integrity'] ??
null );
167 $path = "$destDir/$dest";
168 if ( $this->action
=== 'verify' && sha1_file( $path ) !== sha1( $data ) ) {
169 $this->fatalError( "File '$dest' for '$moduleName' is different." );
170 } elseif ( $this->action
=== 'update' ) {
171 wfMkdirParents( $destDir );
172 file_put_contents( "$destDir/$dest", $data );
177 private function handleTypeTar( $moduleName, $destDir, array $info ) {
178 $info +
= [ 'src' => null, 'integrity' => null, 'dest' => null ];
179 if ( $info['src'] === null ) {
180 $this->fatalError( "Module '$moduleName' must have a 'src' key." );
182 // Download the resource to a temporary file and open it
183 $data = $this->fetch( $info['src'], $info['integrity' ] );
184 $tmpFile = "{$this->tmpParentDir}/$moduleName.tar";
185 $this->verbose( "... writing '$moduleName' src to $tmpFile\n" );
186 file_put_contents( $tmpFile, $data );
187 $p = new PharData( $tmpFile );
188 $tmpDir = "{$this->tmpParentDir}/$moduleName";
189 $p->extractTo( $tmpDir );
192 if ( $info['dest'] === null ) {
193 // Default: Replace the entire directory
194 $toCopy = [ $tmpDir => $destDir ];
196 // Expand and normalise the 'dest' entries
198 foreach ( $info['dest'] as $fromSubPath => $toSubPath ) {
199 // Use glob() to expand wildcards and check existence
200 $fromPaths = glob( "{$tmpDir}/{$fromSubPath}", GLOB_BRACE
);
202 $this->fatalError( "Path '$fromSubPath' of '$moduleName' not found." );
204 foreach ( $fromPaths as $fromPath ) {
205 $toCopy[$fromPath] = $toSubPath === null
206 ?
"$destDir/" . basename( $fromPath )
207 : "$destDir/$toSubPath/" . basename( $fromPath );
211 foreach ( $toCopy as $from => $to ) {
212 if ( $this->action
=== 'verify' ) {
213 $this->verbose( "... verifying $to\n" );
214 if ( is_dir( $from ) ) {
215 $rii = new RecursiveIteratorIterator( new RecursiveDirectoryIterator(
217 RecursiveDirectoryIterator
::SKIP_DOTS
219 foreach ( $rii as $file ) {
220 $remote = $file->getPathname();
221 $local = strtr( $remote, [ $from => $to ] );
222 if ( sha1_file( $remote ) !== sha1_file( $local ) ) {
223 $this->error( "File '$local' is different." );
224 $this->failAfterOutput
= true;
227 } elseif ( sha1_file( $from ) !== sha1_file( $to ) ) {
228 $this->error( "File '$to' is different." );
229 $this->failAfterOutput
= true;
231 } elseif ( $this->action
=== 'update' ) {
232 $this->verbose( "... moving $from to $to\n" );
233 wfMkdirParents( dirname( $to ) );
234 if ( !rename( $from, $to ) ) {
235 $this->fatalError( "Could not move $from to $to." );
241 private function verbose( $text ) {
242 if ( $this->hasOption( 'verbose' ) ) {
243 $this->output( $text );
247 private function cleanUp() {
248 wfRecursiveRemoveDir( $this->tmpParentDir
);
251 protected function fatalError( $msg, $exitCode = 1 ) {
253 parent
::fatalError( $msg, $exitCode );
259 * Supports only string or object values, and 2 spaces indentation.
261 * @todo Just ship symfony/yaml.
262 * @param string $input
265 private function parseBasicYaml( $input ) {
266 $lines = explode( "\n", $input );
270 foreach ( $lines as $i => $text ) {
272 $trimmed = ltrim( $text, ' ' );
273 if ( $trimmed === '' ||
$trimmed[0] === '#' ) {
276 $indent = strlen( $text ) - strlen( $trimmed );
277 if ( $indent %
2 !== 0 ) {
278 throw new Exception( __METHOD__
. ": Odd indentation on line $line." );
280 $depth = $indent === 0 ?
0 : ( $indent / 2 );
281 if ( $depth < $prev ) {
282 // Close previous branches we can't re-enter
283 array_splice( $stack, $depth +
1 );
285 if ( !array_key_exists( $depth, $stack ) ) {
286 throw new Exception( __METHOD__
. ": Too much indentation on line $line." );
288 if ( strpos( $trimmed, ':' ) === false ) {
289 throw new Exception( __METHOD__
. ": Missing colon on line $line." );
291 $dest =& $stack[ $depth ];
292 if ( $dest === null ) {
293 // Promote from null to object
296 list( $key, $val ) = explode( ':', $trimmed, 2 );
297 $val = ltrim( $val, ' ' );
300 $dest[ $key ] = $val;
302 // Add null (may become an object later)
305 $dest[ $key ] = &$val;
308 unset( $dest, $val );
314 $maintClass = ManageForeignResources
::class;
315 require_once RUN_MAINTENANCE_IF_MAIN
;