/*
records the watched file name
so that i can unwatch it when the process exits

@param {string} process name
@param {string} watched file path
174771
function recordWatchedFiles(processName, filePath, watchedFiles) {
  if (typeof watchedFiles[processName] !== 'undefined' &&
      watchedFiles[processName].length > 0) {
    watchedFiles[processName].push(filePath);
  } else {
    watchedFiles[processName] = [filePath];
  }
}
810166
function specToWatcherObj (watcherInstance, spec, options) {
  const dest = options.dest
  return new Promise((resolve, reject) => {
    const watcher = chokidar.watch(spec.files, {cwd: options.dir})
      .on('ready', () => {
        resolve({
          watcher: watcher,
          spec: spec
        })
      })
      .on('error', (err) => reject(err))
      .on('add', (path) => watcherInstance.emit('add', fileOptions.createFileUsingSpec(path, spec, dest)))
      .on('change', (path) => watcherInstance.emit('change', fileOptions.createFileUsingSpec(path, spec, dest)))
      .on('unlink', (path) => watcherInstance.emit('remove', fileOptions.createFileUsingSpec(path, spec, dest)))
  })
}
1261555
public void onFileChange(File file) {
        mojo.getLog().info(EMPTY_STRING);
        mojo.getLog().info("The watcher has detected a change in " + file.getAbsolutePath());
        mojo.getLog().info(EMPTY_STRING);
        for (Watcher watcher : watchers) {
            if (watcher.accept(file)) {
                cleanupErrorFile(watcher);
                // This flag will be set to false if the processing must be interrupted.
                boolean continueProcessing;
                try {
                    continueProcessing = watcher.fileUpdated(file);
                } catch (WatchingException e) { //NOSONAR
                    mojo.getLog().debug(watcher + " has thrown an exception while handling the " + file.getName() + EMPTY_STRING +
                            " update", e);
                    mojo.getLog().error(String.format(WATCHING_EXCEPTION_MESSAGE, e.getMessage()));
                    createErrorFile(watcher, e);
                    continueProcessing = false;
                }
                if (!continueProcessing) {
                    break;
                }
            }
        }
        mojo.getLog().info(EMPTY_STRING);
        mojo.getLog().info(EMPTY_STRING);
    }
1206646
public void watch(Watcher watcher) throws WatchException{
		if(isClosed){
			throw new WatchException("Watch Monitor is closed !");
		}
		registerPath();
//		log.debug("Start watching path: [{}]", this.path);
		
		while (false == isClosed) {
			WatchKey wk;
			try {
				wk = watchService.take();
			} catch (InterruptedException e) {
//				log.warn(e);
				return;
			}
			
			final Path currentPath = watchKeyPathMap.get(wk);
			WatchEvent.Kind<?> kind;
			for (WatchEvent<?> event : wk.pollEvents()) {
				kind = event.kind();
				if(null != this.filePath && false == this.filePath.endsWith(event.context().toString())){
//					log.debug("[{}] is not fit for [{}], pass it.", event.context(), this.filePath.getFileName());
					continue;
				}
				
				if(kind == StandardWatchEventKinds.ENTRY_CREATE){
					watcher.onCreate(event, currentPath);
				}else if(kind == StandardWatchEventKinds.ENTRY_MODIFY){
					watcher.onModify(event, currentPath);
				}else if(kind == StandardWatchEventKinds.ENTRY_DELETE){
					watcher.onDelete(event, currentPath);
				}else if(kind == StandardWatchEventKinds.OVERFLOW){
					watcher.onOverflow(event, currentPath);
				}
			}
			wk.reset();
		}
	}
1084265
function beginWatch() {
    let watchPaths = []
    let outputs = []

    util.each(cfgArr, function(config) {
      outputs = outputs.concat(config.output)
      watchPaths = watchPaths.concat(config.files)
      watchPaths = watchPaths.concat(config.libPaths)
    })

    chokidar
      .watch(watchPaths, {
        persistent: true,
        ignored: outputs,
        ignoreInitial: true,
        followSymlinks: true,
        usePolling: true,
        alwaysStat: false,
        interval: 100,
        atomic: true,
        ignorePermissionErrors: false
      })
      .on('change', function() {
        i = 0
        build(cfgArr[i], true)
      })
  }
400722
function Watch_file(that,          // @arg this
                    watchFilePath, // @arg String   - watch file path
                    callback) {    // @arg Function - callback(null):void
    var timerID = 0;

    if (this._options.verbose) {
        console.log("  file: " + watchFilePath);
    }

    fs.watchFile(watchFilePath, _watchdogCallback);

    function _watchdogCallback() {
        if (timerID) {
            clearTimeout(timerID); timerID = 0;
        }
        timerID = setTimeout(function() {
            clearTimeout(timerID); timerID = 0;

            callback(null);
        }, that._options.delay);
    }
}
848322
function _recurseFolder(src) {
    // Ignore
    var relativeSrc = path.relative(process.cwd(), src);
    if(_isIgnored(relativeSrc)) return;

    // Process
    fs.readdir(src, function(err, files) {
      files.forEach(function(filename) {
        fs.stat(src+path.sep+filename, function(err, stat) {
          if(stat && stat.isDirectory()) {
            _recurseFolder(src+path.sep+filename);
          }
        });
      });
    });

    // Watch current folder
    _track(src);
  }
503708
function watchFile( file )
        {
            // make sure file is at least something
            if ( !file || '' === file )
            {
                return
            }

            // make sure it's a string
            file = file.toString()

            if ( watchers.hasOwnProperty( file ) )
            {
                return // already exists
            }

            // watch it
            watchers[ file ] = chokidar.watch( file, { ignored:  /[\/\\]\./, persistent: true } )

            var that = this

            // setup event listeners
            watchers[ file ]
                // listener for when the file has been removed
                .on( 'unlink', function ( path )
                    {
                        that.opts.storageMethod.remove( path, function ( err )
                            {
                                if ( err )
                                {
                                    if ( that.opts.logging )
                                    {
                                        console.log( err )
                                    }

                                    return 
                                }

                                // success
                                
                            }
                        )
                    }
                )

                // listener for when the file has been changed
                .on( 'change', function ( path )
                    {
                        // add to main file processing queue
                        mainQueue.add( function ( mainDone )
                            {
                                // attempt to read the file
                                fs.readFile( path, function ( err, fileContents )
                                    {
                                        // notify nbqueue that the async function has finished,
                                        // regardless of success
                                        mainDone()

                                        // check for errors
                                        if ( err )
                                        {
                                            // see if LocalJson instance logging is enabled
                                            if ( that.opts.logging )
                                            {
                                                console.log( err )
                                            }

                                            return 
                                        }

                                        var parsed = LocalJson.TryParse.call( that, JSON.parse, fileContents )

                                        // cache new json
                                        that.opts.storageMethod.set( path, parsed, function ( err )
                                            {
                                                if ( err )
                                                {
                                                    if ( that.opts.logging )
                                                    {
                                                        console.log( err )
                                                    }

                                                    return
                                                }

                                                // success
                                                
                                            }
                                        )
                                    }
                                )
                            }
                        )
                    }
                )
        }
673015
function Watch(paths,      // @arg PathArray
               options,    // @arg Object   - { delay, action, verbose, ... }
               callback) { // @arg Function - callback(err:Error):void
//{@dev
    _if(!Array.isArray(paths),  "invalid Watch(paths)");
    _if(!_isObject(options),    "invalid Watch(,options)");
    _if(!_isFunction(callback), "invalid Watch(,,callback)");
//}@dev

    var that = this;

    this._options = options || {};

    if (this._options.verbose) {
        console.log("  --- watch ---");
    }
    paths.forEach(function(path) {
        if (_isFile(path)) {
            Watch_file(that, path, function(diff) { // { path: { dir, size, mtime }, ... }
                callback(null, diff);
            });
        } else if (_isDir(path)) {
            Watch_dir(that, path, function(diff) { // { path: { dir, size, mtime }, ... }
                callback(null, diff);
            }, options);
        }
    });
}
602846
function addWatcher(dirPath) {
    Debug._l(dirPath);
    /*fs.watchFile(dirPath, function (curr, prev) {
     //        console.log('the current mtime is: ' + curr.mtime);
     //        console.log('the previous mtime was: ' + prev.mtime);

     generateCache(id, dirPath);
     });*/
    var watch = Watcher(dirPath, function (filePath, isModified, isDeleted) {
        if (isModified) {
            Debug._l(generateIdFromFilePath(filePath));
            generateCache(filePath);
        }
        if (isDeleted) {
            removeCache(generateIdFromFilePath(filePath));
        }
    });

    return watch;
}
1144691
function addWatcher(dirPath) {
    Debug._l(dirPath);
    Watcher(dirPath, function (filePath, action) {
        switch (action) {
            case Watcher.ADD_EVENT:
            case Watcher.CHANGE_EVENT:
                Debug._l(generateIdFromFilePath(filePath));
                generateCache(filePath);
                break;

            case Watcher.DELETE_EVENT:
                removeCache(generateIdFromFilePath(filePath));
                break;

        }
    });

}
686411
function() {
      var t = this, path = t.get('path');
      t.watcher = FileProbe.watchLoad(path, {persistent: true}, function(error, content) {
        if (!error) {
          t.set('text', content);
        }
      });
    }
1152323
def watch(filenames, callback, use_sudo=False):
    """"""
    filenames = [filenames] if isinstance(filenames, basestring) else filenames
    old_md5 = {fn: md5sum(fn, use_sudo) for fn in filenames}
    yield
    for filename in filenames:
        if md5sum(filename, use_sudo) != old_md5[filename]:
            callback()
            return
683200
def _watch_folder(folder, destination, compiler_args):
    """"""
    for dirpath, dirnames, filenames in os.walk(folder):
        for filename in filenames:
            # Ignore filenames starting with ".#" for Emacs compatibility
            if watched_extension(filename) and not filename.startswith('.#'):
                fullpath = os.path.join(dirpath, filename)
                subfolder = os.path.relpath(dirpath, folder)
                mtime = os.stat(fullpath).st_mtime
                
                # Create subfolders in target directory if they don't exist
                compiled_folder = os.path.join(destination, subfolder)
                if not os.path.exists(compiled_folder):
                    os.makedirs(compiled_folder)
                
                compiled_path = _compiled_path(compiled_folder, filename)
                if (not fullpath in compiled or
                    compiled[fullpath] < mtime or
                    not os.path.isfile(compiled_path)):
                    compile_file(fullpath, compiled_path, compiler_args)
                    compiled[fullpath] = mtime
995302
function _watchProjectRoot(rootPath) {
        FileSystem.on("change", _fileSystemChange);
        FileSystem.on("rename", _fileSystemRename);

        FileSystem.watch(FileSystem.getDirectoryForPath(rootPath), ProjectModel._shouldShowName, ProjectModel.defaultIgnoreGlobs, function (err) {
            if (err === FileSystemError.TOO_MANY_ENTRIES) {
                if (!_projectWarnedForTooManyFiles) {
                    _showErrorDialog(ERR_TYPE_MAX_FILES);
                    _projectWarnedForTooManyFiles = true;
                }
            } else if (err) {
                console.error("Error watching project root: ", rootPath, err);
            }
        });

        // Reset allFiles cache
        model._resetCache();
    }
221171
function Gaze (patterns, opts, done) {
  EE.call(this);

  // If second arg is the callback
  if (typeof opts === 'function') {
    done = opts;
    opts = {};
  }

  // Default options
  opts = opts || {};
  opts.mark = true;
  opts.interval = opts.interval || 100;
  opts.debounceDelay = opts.debounceDelay || 500;
  opts.cwd = opts.cwd || process.cwd();
  this.options = opts;

  // Default done callback
  done = done || emptyFunction;

  // Remember our watched dir:files
  this._watched = Object.create(null);

  // Store watchers
  this._watchers = Object.create(null);

  // Store watchFile listeners
  this._pollers = Object.create(null);

  // Store patterns
  this._patterns = [];

  // Cached events for debouncing
  this._cached = Object.create(null);

  // Set maxListeners
  if (this.options.maxListeners != null) {
    this.setMaxListeners(this.options.maxListeners);
    delete this.options.maxListeners;
  }

  // Initialize the watch on files
  if (patterns) {
    this.add(patterns, done);
  }

  // keep the process alive
  this._keepalive = setInterval(emptyFunction, 200);

  return this;
}
200795
function(file) {
    for(var i = 0; i < watchList.length; i++) {
        if(watchList[i].file === file) {
            watchers[i].close();
            watchList.splice(i, 1);
            watchers.splice(i, 1);
            return;
        }
    }
    throw new Error(file + " was not being watched previously");
}