blob: 12af195d9b6476fd897ceec456eff5dedee5741d [file] [log] [blame]
Paul Lewis64ba20b2020-06-29 16:17:21 +01001// Copyright 2020 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Victor Porof33932362021-07-15 15:05:50 +00005const chokidar = require('chokidar');
Paul Lewis64ba20b2020-06-29 16:17:21 +01006const path = require('path');
7const childProcess = require('child_process');
8const cwd = process.cwd();
9const env = process.env;
Paul Lewisab73c6f2020-11-27 11:30:40 +000010const frontEndDir = path.join(cwd, 'front_end');
11const testsDir = path.join(cwd, 'test');
Paul Lewis64ba20b2020-06-29 16:17:21 +010012
13// Extract the target if it's provided.
14let target = 'Default';
15const targetArg = process.argv.find(value => value.startsWith('--target='));
16if (targetArg) {
17 target = targetArg.slice('--target='.length);
18}
19
Paul Lewisab73c6f2020-11-27 11:30:40 +000020let restartBuild = false;
21let autoninja;
22const changedFiles = new Set();
23const onFileChange = (_, fileName) => {
24 // Some filesystems emit multiple events in quick succession for a
25 // single file change. Here we track the changed files, and reset
26 // after a short timeout.
27 if (changedFiles.has(fileName)) {
28 return;
29 }
30 changedFiles.add(fileName);
31 setTimeout(() => {
32 changedFiles.delete(fileName);
33 }, 250);
34
35 // If the exitCode is null, autoninja is still running so stop it
36 // and try to restart it again.
Tim van der Lippe40755592021-01-07 13:55:08 +000037 const ninjaProcessExists = Boolean(autoninja && autoninja.pid);
Paul Lewisab73c6f2020-11-27 11:30:40 +000038 if (ninjaProcessExists) {
39 const isRunning = ninjaProcessExists && autoninja.exitCode === null;
40 if (isRunning) {
41 autoninja.kill();
42 restartBuild = true;
43 }
Paul Lewis64ba20b2020-06-29 16:17:21 +010044 return;
45 }
46
Paul Lewisab73c6f2020-11-27 11:30:40 +000047 autoninja = childProcess.spawn('autoninja', ['-C', `out/${target}`], {cwd, env, stdio: 'inherit'});
Paul Lewis64ba20b2020-06-29 16:17:21 +010048 autoninja.on('close', () => {
Paul Lewisab73c6f2020-11-27 11:30:40 +000049 autoninja = null;
50 if (restartBuild) {
51 restartBuild = false;
52 console.log(`\n${fileName} changed, restarting ninja\n`);
53 onFileChange();
Paul Lewis64ba20b2020-06-29 16:17:21 +010054 }
Paul Lewis64ba20b2020-06-29 16:17:21 +010055 });
56};
57
Paul Lewisab73c6f2020-11-27 11:30:40 +000058// Watch the front_end and test folder and build on any change.
59console.log(`Watching for changes in ${frontEndDir} and ${testsDir}; building to out/${target}`);
Victor Porof33932362021-07-15 15:05:50 +000060chokidar.watch(frontEndDir).on('all', onFileChange);
61chokidar.watch(testsDir).on('all', onFileChange);