-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathwatch.js
208 lines (191 loc) · 5.35 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
/**
* External dependencies
*/
const fs = require( 'fs' );
const watch = require( 'node-watch' );
const { spawn } = require( 'child_process' );
const path = require( 'path' );
const chalk = require( 'chalk' );
/**
* Internal dependencies
*/
const getPackages = require( './get-packages' );
const BUILD_SCRIPT = path.resolve( __dirname, './build.js' );
const PACKAGES_DIR = path.resolve( __dirname, '../../packages' );
const modulePackages = getPackages();
let filesToBuild = new Map();
/**
* Determines whether a file exists.
*
* @param {string} filename
*
* @return {boolean} True if a file exists.
*/
function exists( filename ) {
try {
return fs.statSync( filename ).isFile();
} catch ( e ) {}
return false;
}
/**
* Is the path name a directory?
*
* @param {string} pathname
*
* @return {boolean} True if the given path is a directory.
*/
function isDirectory( pathname ) {
try {
return fs.statSync( pathname ).isDirectory();
} catch ( e ) {}
return false;
}
/**
* Determine if a file is source code.
*
* 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.
*
* @param {string} filename
*
* @return {boolean} True if the file a source file.
*/
function isSourceFile( filename ) {
// Only run this regex on the relative path, otherwise we might run
// into some false positives when eg. the project directory contains `src`
const relativePath = path
.relative( process.cwd(), filename )
.replace( /\\/g, '/' );
return (
/\/src\/.+\.(js|json|scss|ts|tsx)$/.test( relativePath ) &&
! [
/\/(benchmark|__mocks__|__tests__|test|storybook|stories|e2e-test-utils-playwright)\/.+/,
/.\.(spec|test)\.js$/,
].some( ( regex ) => regex.test( relativePath ) )
);
}
/**
* Determine if a file is in a module package.
*
* getPackages only returns packages that have a package.json with the module
* field. Only build these packages.
*
* @param {string} filename
*
* @return {boolean} True if the file is in a module package.
*/
function isModulePackage( filename ) {
return modulePackages.some( ( packagePath ) => {
return filename.indexOf( packagePath ) > -1;
} );
}
/**
* Is the file something the watch task should monitor or skip?
*
* @param {string} filename
* @param {symbol} skip
*
* @return {boolean | symbol} True if the file should be watched.
*/
function isWatchableFile( filename, skip ) {
// Recursive file watching is not available on a Linux-based OS. If this is the case,
// the watcher library falls back to watching changes in the subdirectories
// and passes the directories to this filter callback instead.
if ( isDirectory( filename ) ) {
return true;
}
return isSourceFile( filename ) && isModulePackage( filename )
? true
: skip;
}
/**
* Returns the associated file in the build folder for a given source file.
*
* @param {string} srcFile
*
* @return {string} Path to the build file.
*/
function getBuildFile( srcFile ) {
// Could just use string.replace, but the user might have the project
// checked out and nested under another src folder.
const srcDir = `${ path.sep }src${ path.sep }`;
const packageDir = srcFile.substr( 0, srcFile.lastIndexOf( srcDir ) );
const filePath = srcFile.substr( srcFile.lastIndexOf( srcDir ) + 5 );
return path.resolve( packageDir, 'build', filePath );
}
/**
* Adds a build file to the set of files that should be rebuilt.
*
* @param {'update'} event The event name
* @param {string} filename
*/
function updateBuildFile( event, filename ) {
if ( exists( filename ) ) {
try {
console.log( chalk.green( '->' ), `${ event }: ${ filename }` );
filesToBuild.set( filename, true );
} catch ( e ) {
console.log(
chalk.red( 'Error:' ),
`Unable to update file: ${ filename } - `,
e
);
}
}
}
/**
* Removes a build file from the build folder
* (usually triggered the associated source file was deleted)
*
* @param {'remove'} event The event name
* @param {string} filename
*/
function removeBuildFile( event, filename ) {
const buildFile = getBuildFile( filename );
if ( exists( buildFile ) ) {
try {
fs.unlink( buildFile, () => {
console.log( chalk.red( '<-' ), `${ event }: ${ filename }` );
} );
} catch ( e ) {
console.log(
chalk.red( 'Error:' ),
`Unable to remove build file: ${ filename } - `,
e
);
}
}
}
// Start watching packages.
watch(
PACKAGES_DIR,
{ recursive: true, delay: 500, filter: isWatchableFile },
( event, filename ) => {
// Double check whether we're dealing with a file that needs watching, to accommodate for
// the inability to watch recursively on linux-based operating systems.
if ( ! isSourceFile( filename ) || ! isModulePackage( filename ) ) {
return;
}
switch ( event ) {
case 'update':
updateBuildFile( event, filename );
break;
case 'remove':
removeBuildFile( event, filename );
break;
}
}
);
// Run a separate interval that calls the build script.
// This effectively acts as a throttle for building files.
setInterval( () => {
const files = Array.from( filesToBuild.keys() );
if ( files.length ) {
filesToBuild = new Map();
try {
spawn( 'node', [ BUILD_SCRIPT, ...files ], { stdio: [ 0, 1, 2 ] } );
} catch ( e ) {}
}
}, 100 );
console.log( chalk.red( '->' ), chalk.cyan( 'Watching for changes...' ) );