59 lines
1.9 KiB
TypeScript
59 lines
1.9 KiB
TypeScript
import {watch, FSWatcher} 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<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 = join(this.path,path);
|
|
this.emit("create",cpath);
|
|
}).on("unlink",path=>{
|
|
const cpath = join(this.path,path);
|
|
this.emit("delete",cpath);
|
|
});
|
|
}
|
|
if(option.watchDir){
|
|
this.watcher.on("addDir",path=>{
|
|
const cpath = join(this.path,path);
|
|
this.emit("create",cpath);
|
|
}).on("unlinkDir",path=>{
|
|
const cpath = join(this.path,path);
|
|
this.emit("delete",cpath);
|
|
})
|
|
}
|
|
}
|
|
async setup(cntr: DocumentAccessor): Promise<void> {
|
|
await setupRecursive(this,this.path,cntr);
|
|
}
|
|
}
|