4in1_ws_web/deploy/gen_static_config.php

89 lines
2.2 KiB
PHP
Executable File

#!/usr/bin/env php
<?php
require __DIR__.'/../init.php';
require 'engine/skin.php';
if ($argc <= 1) {
usage();
exit(1);
}
$input_dir = null;
array_shift($argv);
while (count($argv) > 0) {
switch ($argv[0]) {
case '-i':
array_shift($argv);
$input_dir = array_shift($argv);
break;
default:
cli::die('unsupported argument: '.$argv[0]);
}
}
if (is_null($input_dir))
cli::die("input directory has not been specified");
$hashes = [];
foreach (['css', 'js'] as $type) {
$entries = glob_recursive($input_dir.'/dist-'.$type.'/*.'.$type);
if (empty($entries)) {
cli::error("warning: no files found in $input_dir/dist-$type");
continue;
}
foreach ($entries as $file) {
$hashes[$type.'/'.basename($file)] = [
'version' => get_hash($file),
'integrity' => []
];
foreach (RESOURCE_INTEGRITY_HASHES as $hash_type)
$hashes[$type.'/'.basename($file)]['integrity'][$hash_type] = base64_encode(hash_file($hash_type, $file, true));
}
}
echo "<?php\n\n";
echo "return ".var_export($hashes, true).";\n";
function usage(): void {
global $argv;
echo <<<EOF
usage: {$argv[0]} [OPTIONS]
Options:
-i input htdocs directory
EOF;
}
function get_hash(string $path): string {
return substr(sha1(file_get_contents($path)), 0, 8);
}
function glob_escape(string $pattern): string {
if (str_contains($pattern, '[') || str_contains($pattern, ']')) {
$placeholder = uniqid();
$replaces = array( $placeholder.'[', $placeholder.']', );
$pattern = str_replace( array('[', ']', ), $replaces, $pattern);
$pattern = str_replace( $replaces, array('[[]', '[]]', ), $pattern);
}
return $pattern;
}
/**
* Does not support flag GLOB_BRACE
*
* @param string $pattern
* @param int $flags
* @return array
*/
function glob_recursive(string $pattern, int $flags = 0): array {
$files = glob(glob_escape($pattern), $flags);
foreach (glob(glob_escape(dirname($pattern)).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) {
$files = array_merge($files, glob_recursive($dir.'/'.basename($pattern), $flags));
}
return $files;
}