Files
gulp-haxetool/src/common/watch.ts
T
shmyga 428f9d100e
test / test (push) Failing after 6m5s
refactor(types): improve vinyl types
2026-10-27 19:24:54 +03:00

67 lines
1.6 KiB
TypeScript

import { Transform, type TransformCallback } from "stream";
import { Tail } from "tail";
import Vinyl from "vinyl";
export type WatchHandler = (line: string) => string | undefined;
export interface WatchParams {
source: string;
handler?: WatchHandler;
}
class BufferingTransform extends Transform {
_transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void {
this.push(chunk);
callback();
}
}
export class TailVinyl extends Vinyl<BufferingTransform> {
private tail?: Tail;
constructor(params: WatchParams) {
super({ path: "out.log", contents: new BufferingTransform() });
if (params.source) {
this.tail = new Tail(params.source);
this.tail.on("line", (line) => {
if (params.handler) {
line = params.handler(line);
}
if (line) {
this.contents.write(line + "\n");
}
});
this.tail.on("error", (error) => this.contents.write("error: " + error));
}
}
clone() {
return new Vinyl({
cwd: this.cwd,
base: this.base,
history: this.history.slice(),
contents: this.contents,
});
}
dispose() {
this.tail?.unwatch();
this.contents.destroy();
}
}
export class WatchVinylTransform extends Transform {
constructor(private params: WatchParams) {
super({ objectMode: true });
}
_transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void {
const log = new TailVinyl(this.params);
this.on("end", () => log.dispose());
this.push(log);
callback();
}
}
export const watch = (source: string, handler?: WatchHandler) => new WatchVinylTransform({ source, handler });