metro/scripts/watch.js

70 lines
2.0 KiB
JavaScript
Raw Permalink Normal View History

2017-01-26 12:56:40 +00:00
/**
* Copyright (c) 2014, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
/**
* Watch files for changes and rebuild (copy from 'src/' to `build/`) if changed
*/
const fs = require('fs');
2017-05-22 10:51:24 +00:00
const {execSync} = require('child_process');
2017-01-26 12:56:40 +00:00
const path = require('path');
2017-05-22 10:51:24 +00:00
const chalk = require('chalk');
const getPackages = require('./_getPackages');
2017-01-26 12:56:40 +00:00
const BUILD_CMD = `node ${path.resolve(__dirname, './build.js')}`;
let filesToBuild = new Map();
const exists = filename => {
try {
return fs.statSync(filename).isFile();
} catch (e) {}
return false;
};
const rebuild = filename => filesToBuild.set(filename, true);
getPackages().forEach(p => {
const srcDir = path.resolve(p, 'src');
try {
fs.accessSync(srcDir, fs.F_OK);
fs.watch(path.resolve(p, 'src'), {recursive: true}, (event, filename) => {
const filePath = path.resolve(srcDir, filename);
2017-05-22 10:51:24 +00:00
if ((event === 'change' || event === 'rename') && exists(filePath)) {
2017-01-26 12:56:40 +00:00
console.log(chalk.green('->'), `${event}: ${filename}`);
rebuild(filePath);
} else {
const buildFile = path.resolve(srcDir, '..', 'build', filename);
try {
fs.unlinkSync(buildFile);
process.stdout.write(
chalk.red(' \u2022 ') +
2017-05-22 10:51:24 +00:00
path.relative(path.resolve(srcDir, '..', '..'), buildFile) +
' (deleted)' +
'\n'
2017-01-26 12:56:40 +00:00
);
} catch (e) {}
}
});
} catch (e) {
// doesn't exist
}
});
setInterval(() => {
const files = Array.from(filesToBuild.keys());
if (files.length) {
filesToBuild = new Map();
try {
execSync(`${BUILD_CMD} ${files.join(' ')}`, {stdio: [0, 1, 2]});
} catch (e) {}
}
}, 100);
console.log(chalk.red('->'), chalk.cyan('Watching for changes...'));