pokemon-showdown-client/build-tools/update
Guangcong Luo 15c73c922f Refactor build system
We no longer have the relevant Githook for automatic building, so
putting it in `githooks/` no longer makes much sense. It's now manually
called with a build script `./build`, like other PS websites (most
notably PSDex and the damagecalc).
2017-12-04 17:37:01 -05:00

75 lines
2.5 KiB
JavaScript
Executable File

#!/usr/bin/env node
/**
* This script parses index.html and sets the version query string of each
* resource to be the MD5 hash of that resource.
* It also updates news and the learnsets-g6.js file.
*
* On the live web server, this script is set as the following git hooks:
* post-commit, post-checkout, post-merge, post-rewrite
*/
"use strict";
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
const exec = require('child_process').exec;
const thisDir = __dirname;
const rootDir = path.resolve(thisDir, '..');
// update version
process.stdout.write("Updating version... ");
let version = require('../package.json').version;
let configBuf = fs.readFileSync(path.resolve(rootDir, 'config/config.js'), {encoding: 'utf8'});
configBuf = configBuf.replace(/\/\* version \*\/[^;\n]*;/, `/* version */ Config.version = ${JSON.stringify(version)};`);
fs.writeFileSync(path.resolve(rootDir, 'config/config.js'), configBuf);
console.log("DONE");
function updateIndex() {
let indexContents = fs.readFileSync(path.resolve(rootDir, 'index.template.html'), {encoding: 'utf8'});
// add hashes to js and css files
process.stdout.write("Updating hashes... ");
indexContents = indexContents.replace(/(src|href)="\/(.*?)\?[a-z0-9]*?"/g, function (a, b, c) {
let hash = Math.random(); // just in case creating the hash fails
try {
const filename = c.replace('/play.pokemonshowdown.com/', '');
const fstr = fs.readFileSync(path.resolve(rootDir, filename), {encoding: 'utf8'});
hash = crypto.createHash('md5').update(fstr).digest('hex').substr(0, 8);
} catch (e) {}
return b + '="/' + c + '?' + hash + '"';
});
console.log("DONE");
// add news
process.stdout.write("Updating news... ");
exec('php ' + path.resolve(thisDir, 'news-data.php'), function (error, stdout, stderr) {
let newsData = [0, '[failed to retrieve news]'];
if (!error && !stderr) {
try {
newsData = JSON.parse(stdout);
} catch (e) {
console.log("git hook failed to retrieve news (parsing JSON failed):\n" + e.stack);
}
} else {
console.log("git hook failed to retrieve news (exec command failed):\n" + (error || stderr));
}
indexContents = indexContents.replace(/<!-- newsid -->/g, newsData[0]);
indexContents = indexContents.replace(/<!-- news -->/g, newsData[1]);
console.log("DONE");
process.stdout.write("Writing new `index.html` file... ");
fs.writeFileSync(path.resolve(rootDir, 'index.html'), indexContents);
console.log("DONE");
});
}
updateIndex();