import { FSWatcher, watch } from "chokidar"; import { EventEmitter } from "events"; import { join } from "path"; import { DocumentAccessor } from "../../model/doc"; import { DiffWatcherEvent, IDiffWatcher } from "../watcher"; import { setupHelp, setupRecursive } from "./util"; type RecursiveWatcherOption = { /** @default true */ watchFile?: boolean; /** @default false */ watchDir?: boolean; }; export class RecursiveWatcher extends EventEmitter implements IDiffWatcher { on(event: U, listener: DiffWatcherEvent[U]): this { return super.on(event, listener); } emit(event: U, ...arg: Parameters): boolean { return super.emit(event, ...arg); } readonly path: string; private watcher: FSWatcher; constructor(path: string, option: RecursiveWatcherOption = { watchDir: false, watchFile: true, }) { super(); this.path = path; this.watcher = watch(path, { persistent: true, ignoreInitial: true, depth: 100, }); option.watchFile ??= true; if (option.watchFile) { this.watcher.on("add", path => { const cpath = path; // console.log("add ", cpath); this.emit("create", cpath); }).on("unlink", path => { const cpath = path; // console.log("unlink ", cpath); this.emit("delete", cpath); }); } if (option.watchDir) { this.watcher.on("addDir", path => { const cpath = path; this.emit("create", cpath); }).on("unlinkDir", path => { const cpath = path; this.emit("delete", cpath); }); } } async setup(cntr: DocumentAccessor): Promise { await setupRecursive(this, this.path, cntr); } }