@@ -6,6 +6,7 @@ const path = require('node:path');
66const chokidar = require ( 'chokidar' ) ;
77const Context = require ( '../context' ) ;
88const collectFiles = require ( './collect-files' ) ;
9+ const glob = require ( 'glob' ) ;
910
1011/**
1112 * Exports the `watchRun` function that runs mocha in "watch" mode.
@@ -136,6 +137,42 @@ exports.watchRun = (mocha, {watchFiles, watchIgnore}, fileCollectParams) => {
136137 } ) ;
137138} ;
138139
140+ class GlobFilesTracker {
141+ constructor ( watchFiles , watchIgnore ) {
142+ this . watchFilesSet = new Set ( ) ;
143+ this . watchFiles = watchFiles ;
144+ this . watchIgnore = watchIgnore ;
145+ }
146+
147+ regenerate ( ) {
148+ const watchIgnoreSet = new Set ( ) ;
149+ for ( const pattern of this . watchIgnore ) {
150+ glob . sync ( pattern , { dot : true } ) . forEach ( filePath => watchIgnoreSet . add ( filePath ) ) ;
151+ }
152+
153+ const globOpts = {
154+ dot : true ,
155+ ignore : {
156+ childrenIgnored : pathToCheck => watchIgnoreSet . has ( pathToCheck . relative ( ) )
157+ }
158+ } ;
159+
160+ this . watchFilesSet . clear ( ) ;
161+ for ( const pattern of this . watchFiles ) {
162+ glob . sync ( pattern , globOpts ) . forEach ( pathToCheck => {
163+ if ( watchIgnoreSet . has ( pathToCheck ) ) {
164+ return ;
165+ }
166+ this . watchFilesSet . add ( pathToCheck ) ;
167+ } ) ;
168+ }
169+ }
170+
171+ has ( filePath ) {
172+ return this . watchFilesSet . has ( filePath )
173+ }
174+ }
175+
139176/**
140177 * Bootstraps a chokidar watcher. Handles keyboard input & signals
141178 * @param {Mocha } mocha - Mocha instance
@@ -167,8 +204,10 @@ const createWatcher = (
167204 // we handle global fixtures manually
168205 mocha . enableGlobalSetup ( false ) . enableGlobalTeardown ( false ) ;
169206
170- const watcher = chokidar . watch ( watchFiles , {
171- ignored : watchIgnore ,
207+ const tracker = new GlobFilesTracker ( watchFiles , watchIgnore ) ;
208+ tracker . regenerate ( ) ;
209+
210+ const watcher = chokidar . watch ( '.' , {
172211 ignoreInitial : true
173212 } ) ;
174213
@@ -184,8 +223,13 @@ const createWatcher = (
184223 rerunner . run ( ) ;
185224 } ) ;
186225
187- watcher . on ( 'all' , ( ) => {
188- rerunner . scheduleRun ( ) ;
226+ watcher . on ( 'all' , ( event , filePath ) => {
227+ if ( event === 'add' ) {
228+ tracker . regenerate ( ) ;
229+ }
230+ if ( tracker . has ( filePath ) ) {
231+ rerunner . scheduleRun ( ) ;
232+ }
189233 } ) ;
190234
191235 hideCursor ( ) ;
0 commit comments