-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
watch.js
78 lines (68 loc) · 2.21 KB
/
watch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* External dependencies
*/
const fs = require( 'fs' );
const watch = require( 'node-watch' );
const { execSync } = require( 'child_process' );
const path = require( 'path' );
const chalk = require( 'chalk' );
/**
* Internal dependencies
*/
const getPackages = require( './get-packages' );
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;
};
// Exclude test files including .js files inside of __tests__ or test folders
// and files with a suffix of .test or .spec (e.g. blocks.test.js),
// and deceitful source-like files, such as editor swap files.
const isSourceFile = ( filename ) => {
return ! [ /\/(__tests__|test)\/.+.js$/, /.\.(spec|test)\.js$/ ].some( ( regex ) => regex.test( filename ) ) && /.\.(js|scss)$/.test( filename );
};
const rebuild = ( filename ) => filesToBuild.set( filename, true );
getPackages().forEach( ( p ) => {
const srcDir = path.resolve( p, 'src' );
try {
fs.accessSync( srcDir, fs.F_OK );
watch( path.resolve( p, 'src' ), { recursive: true }, ( event, filename ) => {
if ( ! isSourceFile( filename ) ) {
return;
}
const filePath = path.resolve( srcDir, filename );
if ( ( event === 'update' ) && exists( filePath ) ) {
// eslint-disable-next-line no-console
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 ' ) +
path.relative( path.resolve( srcDir, '..', '..' ), buildFile ) +
' (deleted)' +
'\n'
);
} 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 );
// eslint-disable-next-line no-console
console.log( chalk.red( '->' ), chalk.cyan( 'Watching for changes...' ) );