ionian/packages/server/src/diff/watcher/recursive_watcher.ts
2024-03-29 00:19:36 +09:00

67 lines
1.7 KiB
TypeScript

import { type FSWatcher, watch } from "chokidar";
import { EventEmitter } from "node:events";
import type { DocumentAccessor } from "../../model/doc";
import type { DiffWatcherEvent, IDiffWatcher } from "../watcher";
import { setupRecursive } from "./util";
type RecursiveWatcherOption = {
/** @default true */
watchFile?: boolean;
/** @default false */
watchDir?: boolean;
};
export class RecursiveWatcher extends EventEmitter implements IDiffWatcher {
on<U extends keyof DiffWatcherEvent>(event: U, listener: DiffWatcherEvent[U]): this {
return super.on(event, listener);
}
emit<U extends keyof DiffWatcherEvent>(event: U, ...arg: Parameters<DiffWatcherEvent[U]>): 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<void> {
await setupRecursive(this, this.path, cntr);
}
}