Creates a watch thread which listens to specified files' modification and reloads
configurations
2879
static void setupWatch(final Map<String, ParseConfigFile> configFileMap) throws IOException {
    Preconditions.checkNotNull(configFileMap);
    Preconditions.checkArgument(configFileMap.size() > 0);

    final WatchService watchService;
    try {
      watchService = FileSystems.getDefault().newWatchService();
    } catch (IOException e) {
      log.warn(" Failed to create WatchService " + e.getMessage());
      throw e;
    }

    // Map to store WatchKey to Dir mapping
    final Map<WatchKey, Path> keys = new HashMap<>();
    // A directory to config files multimap
    final Multimap<Path, String> dirToFilesMap = HashMultimap.create();

    // Iterate over each file.
    for (Map.Entry<String, ParseConfigFile> entry : configFileMap.entrySet()) {
      String fileName = entry.getKey();
      ParseConfigFile parser = entry.getValue();
      Preconditions.checkNotNull(fileName);
      Preconditions.checkNotNull(parser);

      final File file = new File(fileName);
      if (!file.exists()) {
        log.warn("Failed to setup watch service, user provided file " + fileName + " does not "
            + "exist.");
        continue;
      }

      try {
        Path dir = Paths.get(fileName).getParent();
        if (!dirToFilesMap.containsKey(dir)) {
          // There is not entry for this directory, create a watchkey
          WatchKey watchKey = dir.register(watchService,
              new WatchEvent.Kind[]{StandardWatchEventKinds.ENTRY_MODIFY},
              SensitivityWatchEventModifier.HIGH);
          keys.put(watchKey, dir);
        }
        // Add the config file to dir map
        dirToFilesMap.put(dir, fileName);
      } catch (IOException e) {
        // Ignore the IOException
        log.warn("IOException while setting up watch on conf " + fileName + ". "
            + e.getMessage());
      }
    }

    // Return if WatchService is not initialized
    if (keys.size() == 0) {
      log.warn("Watchservice was not setup for any config file(s).");
      try {
        watchService.close();
      } catch (IOException e) {
        log.warn("IOException while closing watchService. " + e.getMessage());
      }
      return;
    }

    Runnable runnable = () -> {
      // Watchservice is established, now listen for the events till eternity!
      for (;; ) {
        WatchKey watchKey;
        try {
          watchKey = watchService.take();
        } catch (InterruptedException ie) {
          log.warn(ie.getMessage());
          Thread.currentThread().interrupt();
          return;
        }

        // Get the directory for which watch service event triggered.
        Path dir = keys.get(watchKey);
        for (WatchEvent<?> event : watchKey.pollEvents()) {
          // Make sure the modification happened to user config file
          @SuppressWarnings("unchecked")
          final Path name = ((WatchEvent<Path>) event).context();
          final String filename = dir.resolve(name).toString();
          // Lookup the file in dirToFilesMap
          if (dirToFilesMap.containsEntry(dir, filename)) {
            // Match!
            // reparse the config file
            log.info("Modification detected, reloading config file " + filename);
            configFileMap.get(filename).parseConfigFile();
            break;
          }
        }
        watchKey.reset();
      }
    };

    final Thread thread = new Thread(runnable);
    log.info("Starting configuration watching thread.");
    thread.start();
  }
661203
function watch() {
  gulp.watch([appSrc + '/app/**/*.ts', '!' + appSrc + '/app/**/*.spec.ts']).on('change', function (e) {
    console.log('TypeScript file ' + e.path + ' has been changed. Compiling.');
  });
  gulp.watch([appSrc + '/app/**/*.less']).on('change', function (e) {
    console.log(e.path + ' has been changed. Updating.');
    transpileLESS(e.path);
    updateWatchDist();
  });
  gulp.watch([appSrc + '/app/**/*.html']).on('change', function (e) {
    console.log(e.path + ' has been changed. Updating.');
    copyToDist(e.path);
    updateWatchDist();
  });
}
1108817
function watch (glob, watchOpt) {
    if (!started) {
      deferredWatch = emitter.watch.bind(null, glob, watchOpt)
    } else {
      // destroy previous
      if (fileWatcher) fileWatcher.close()
      glob = glob && glob.length > 0 ? glob : defaultWatchGlob
      glob = Array.isArray(glob) ? glob : [ glob ]
      watchOpt = xtend({ poll: opts.poll }, watchOpt)

      fileWatcher = createFileWatch(glob, watchOpt)
      fileWatcher.on('watch', emitter.emit.bind(emitter, 'watch'))
    }
    return emitter
  }
942867
def watch(ctx):
    
    watcher = Watcher(ctx)
    watcher.watch_directory(
        path='{pkg.source_less}', ext='.less',
        action=lambda e: build(ctx, less=True)
    )
    watcher.watch_directory(
        path='{pkg.source_js}', ext='.jsx',
        action=lambda e: build(ctx, js=True)
    )
    watcher.watch_directory(
        path='{pkg.docs}', ext='.rst',
        action=lambda e: build(ctx, docs=True)
    )
    watcher.start()
1351248
function watch(done) {
  var mainWatcher = gulp.watch([
    'src/**/*.js',
    'modules/**/*.js',
    'test/spec/**/*.js',
    '!test/spec/loaders/**/*.js'
  ]);
  var loaderWatcher = gulp.watch([
    'loaders/**/*.js',
    'test/spec/loaders/**/*.js'
  ]);

  connect.server({
    https: argv.https,
    port: port,
    root: './',
    livereload: true
  });

  mainWatcher.on('all', gulp.series(clean, gulp.parallel(lint, 'build-bundle-dev', test)));
  loaderWatcher.on('all', gulp.series(lint));
  done();
}
234905
def trigger_modified(self, filepath):
        """"""
        mod_time = self._get_modified_time(filepath)
        if mod_time > self._watched_files.get(filepath, 0):
            self._trigger('modified', filepath)
            self._watched_files[filepath] = mod_time
304135
def run_on_modifications(paths)
      changed_files, success = Runner.run(Inspector.clean(paths), watchers, options)

      throw :task_has_failed unless success
    end
238378
function addWatcher(file, handler, callback)
{
  fs.stat(file, function(err, stat)
  {
    if (err) return callback(false);

    fs.watch(file, handler(file));

    callback(true, stat.mtime.getTime());
  });
}
1031678
def watch_dir(path: str) -> None:
    """"""
    _compile_exclude_patterns()
    if config.autoreload or config.debug:
        # Add files to watch for autoreload
        p = pathlib.Path(path)
        p.resolve()
        _add_watch_path(p)
1257847
function watch (specs, handler, options) {
  const err = fileOptions.validate(specs)
  if (err) {
    return Promise.reject(err)
  }
  const normalisedSpecs = fileOptions.normalize(specs)
  const events = new EventEmitter()

  // Option resolving
  const opts = options || {}
  const dir = opts.dir || '.'
  const fileReader = opts.fileReader || readAsFile
  const loader = opts.loader || defaultLoader
  const buildConcurrency = opts.concurrency || 1
  const resolveRoot = path.resolve(opts.resolveRoot || process.cwd())

  // State that is maintained by watching for file changes
  const fileInfos = {}
  const affectedFiles = {}
  const affectedFilesInverse = {}

  function linkingLoader (filename, parentFilename) {
    if (parentFilename) {
      const file = path.relative(dir, filename)
      affectedFiles[file] = affectedFiles[file] || new Set()
      affectedFiles[file].add(parentFilename)

      affectedFilesInverse[parentFilename] = affectedFilesInverse[parentFilename] || new Set()
      affectedFilesInverse[parentFilename].add(file)
      watchFile(file)
    }
    return loader(filename, parentFilename)
  }

  function unlinkFile (filename) {
    delete affectedFiles[filename] // the files affected by changing the file `filename`

    // the files that affect the file `filename`
    if (affectedFilesInverse[filename]) {
      affectedFilesInverse[filename].forEach((affectorFilename) => {
        affectedFiles[affectorFilename].delete(filename)
        if (affectedFiles[affectorFilename].size === 0) {
          delete affectedFiles[affectorFilename]
        }
      })

      delete affectedFilesInverse[filename]
    }
  }

  const inlinedWatcher = chokidar.watch([], {cwd: dir})
  inlinedWatcher.on('change', (filename) => {
    const files = Array.from(getSourceFileObjs(filename))
    Promise.all(files.map((fileInfo) => handleFile(fileInfo, {rootCause: 'change', cause: 'change'})))
      .then(() => events.emit('change', filename))
      .catch(handleFileFailure)
  })

  inlinedWatcher.on('unlink', (filename) => {
    const files = Array.from(getSourceFileObjs(filename))
    unlinkFile(filename)
    Promise.all(files.map((fileInfo) => handleFile(fileInfo, {rootCause: 'delete', cause: 'change'})))
      .then(() => events.emit('delete', filename))
      .catch(handleFileFailure)
  })

  function watchFile (filename) {
    inlinedWatcher.add(filename)
  }

  function getSourceFileObjs (filename, collectorSet) {
    const results = collectorSet || new Set()
    if (affectedFiles[filename]) {
      affectedFiles[filename].forEach((affectedFilename) => {
        if (fileInfos[affectedFilename]) {
          results.add(fileInfos[affectedFilename])
        }
        getSourceFileObjs(affectedFilename, results)
      })
    }
    return results
  }

  function workHandler (work) {
    fileInfos[work.fileInfo.src] = work.fileInfo
    return fileReader(work.fileInfo, { loader: linkingLoader, resolveRoot })
      .then(file => handler(undefined, file, work.cause))
      .catch((err) => {
        if (err instanceof ParseError) {
          return handler(err, new File({info: work.fileInfo, content: undefined}), work.cause)
        } else {
          throw err
        }
      })
      .then((res) => work.resolve(res))
      .catch((err) => work.reject(err))
  }

  const workQueue = new WorkQueue(workHandler, {})

  function handleFile (fileInfo, cause) {
    return new Promise((resolve, reject) => {
      workQueue.add({fileInfo: fileInfo, cause: cause, resolve: resolve, reject: reject})
    })
  }

  function handleFileFailure (err) {
    events.emit('error', err)
  }

  function build () {
    return Promise.all(w.files())
      .map((fileInfo) => {
        return handleFile(fileInfo, {rootCause: 'build', cause: 'build'})
      }, {concurrency: buildConcurrency})
  }

  const w = new Watcher(normalisedSpecs, opts)

  w.on('add', (fileInfo) => {
    return handleFile(fileInfo, {rootCause: 'add', cause: 'add'})
      .then(() => events.emit('add', fileInfo.src))
      .catch(handleFileFailure)
  })

  w.on('change', (fileInfo) => {
    return handleFile(fileInfo, {rootCause: 'change', cause: 'change'})
      .then(() => events.emit('change', fileInfo.src))
      .catch(handleFileFailure)
  })

  w.on('remove', (fileInfo) => {
    unlinkFile(fileInfo.src)
    events.emit('delete', fileInfo.src)
  })

  return w._promise.then(() => ({build: build, events: events}))
}
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);
    }
}
886366
def serve(
    files,
    immutable,
    host,
    port,
    debug,
    reload,
    cors,
    sqlite_extensions,
    inspect_file,
    metadata,
    template_dir,
    plugins_dir,
    static,
    memory,
    config,
    version_note,
    help_config,
):
    """"""
    if help_config:
        formatter = formatting.HelpFormatter()
        with formatter.section("Config options"):
            formatter.write_dl([
                (option.name, '{} (default={})'.format(
                    option.help, option.default
                ))
                for option in CONFIG_OPTIONS
            ])
        click.echo(formatter.getvalue())
        sys.exit(0)
    if reload:
        import hupper

        reloader = hupper.start_reloader("datasette.cli.serve")
        reloader.watch_files(files)
        if metadata:
            reloader.watch_files([metadata.name])

    inspect_data = None
    if inspect_file:
        inspect_data = json.load(open(inspect_file))

    metadata_data = None
    if metadata:
        metadata_data = json.loads(metadata.read())

    click.echo("Serve! files={} (immutables={}) on port {}".format(files, immutable, port))
    ds = Datasette(
        files,
        immutables=immutable,
        cache_headers=not debug and not reload,
        cors=cors,
        inspect_data=inspect_data,
        metadata=metadata_data,
        sqlite_extensions=sqlite_extensions,
        template_dir=template_dir,
        plugins_dir=plugins_dir,
        static_mounts=static,
        config=dict(config),
        memory=memory,
        version_note=version_note,
    )
    # Force initial hashing/table counting
    ds.inspect()
    ds.app().run(host=host, port=port, debug=debug)
24273
def run_process(path: Union[Path, str], target: Callable, *,
                args: Tuple=(),
                kwargs: Dict[str, Any]=None,
                callback: Callable[[Set[Tuple[Change, str]]], None]=None,
                watcher_cls: Type[AllWatcher]=PythonWatcher,
                debounce=400,
                min_sleep=100):
    

    process = _start_process(target=target, args=args, kwargs=kwargs)
    reloads = 0

    for changes in watch(path, watcher_cls=watcher_cls, debounce=debounce, min_sleep=min_sleep):
        callback and callback(changes)
        _stop_process(process)
        process = _start_process(target=target, args=args, kwargs=kwargs)
        reloads += 1
    return reloads
1308900
function fileChanged(status, filepath) {
			// If file was deleted and then re-added, consider it changed.
			if (changedFiles[filepath] === 'deleted' && status === 'added') {
				status = 'changed';
			}
			// Keep track of changed status for later.
			changedFiles[filepath] = status;
			// Emit watch events if anyone is listening
			if (grunt.event.listeners('watch').length > 0) {
				var matchingTargets = [];
				targets.forEach(function(target) {
					if (grunt.file.match(target.files, filepath).length > 0) {
						matchingTargets.push(target.name);
					}
				});
				matchingTargets.forEach(function(matchingTarget) {
					grunt.event.emit('watch', status, filepath, matchingTarget);
				});
			}
			// Keep track of changed status for later.
			changedFiles[filepath] = status;
			// Execute debounced done function.
			done();
		}
608938
def watch_and_run(monitor, times, recursively, directory, *flags)
      result = OpenStruct.new(directory: directory, changes: [])
      i = 0
      result.changes[i] = OpenStruct.new(called: false)
      can_return = false
      callback = Proc.new do |change|
        next if can_return

        result.changes[i].called = true;
        result.changes[i].change = change

        i += 1

        if i < times
          result.changes[i] = OpenStruct.new(called: false)
        else
          can_return = true
        end
      end

      if recursively
        monitor.watch_recursively(directory, *flags, &callback)
      else
        monitor.watch(directory, *flags, &callback)
      end

      thread = Thread.new(monitor) { |m| m.run! }
      sleep(0.2) # give time for the monitor to bootup

      yield # So much boilerplate code to get here :S

      sleep(0.2) # allow the monitor to run the callbacks

      # Nothing can change after the callback if there is only one of them,
      # so never wait for one callback
      if times > 1
        until can_return
          sleep(0.1)
        end
      end

      return result
    ensure
      monitor.stop
      thread.join if thread
    end
1157239
function(file, event) {
    var fn = function(file) {};
    for(var i = 0; i < watchList.length; i++) {
        if(watchList[i].file === file) {
            watchers[i].on(event, fn);
            watchList[i].callback[event] = fn;
            return;
        }
    }
    throw new Error(file + " was not being watched previously");
}
517968
def watch(directory=None, auto_clear=False, extensions=[]):
    """"""
    if directory and not os.path.isdir(directory):
        raise ValueError('Directory not found: ' + directory)
    directory = os.path.abspath(directory)

    # Initial run
    event_handler = ChangeHandler(directory, auto_clear, extensions)
    event_handler.run()

    # Setup watchdog
    observer = Observer()
    observer.schedule(event_handler, path=directory, recursive=True)
    observer.start()

    # Watch and run tests until interrupted by user
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()