Skip to content

Commit

Permalink
fixed double processing issue in the watcher
Browse files Browse the repository at this point in the history
  • Loading branch information
oscarotero committed Aug 27, 2024
1 parent 446c23b commit 3c072e7
Showing 1 changed file with 29 additions and 29 deletions.
58 changes: 29 additions & 29 deletions core/watcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export default class FSWatcher implements Watcher {
async start() {
const { root, ignore, debounce } = this.options;
const watcher = Deno.watchFs(root);
const changeQueue: Set<string>[] = [];
const changes = new Set<string>();
let timer = 0;
let runningCallback = false;

Expand All @@ -86,23 +86,33 @@ export default class FSWatcher implements Watcher {
const callback = async () => {
runningCallback = true;

let changes: Set<string> | undefined;
while ((changes = changeQueue.pop()) !== undefined) {
try {
const result = await this.dispatchEvent({
type: "change",
files: changes,
});
if (false === result) {
runningCallback = false;
return watcher.close();
}
} catch (error) {
await this.dispatchEvent({ type: "error", error });
const files = new Set(changes);
changes.clear();

if (!files.size) {
runningCallback = false;
return;
}

try {
const result = await this.dispatchEvent({
type: "change",
files: files,
});
if (false === result) {
runningCallback = false;
return watcher.close();
}
} catch (error) {
await this.dispatchEvent({ type: "error", error });
}

runningCallback = false;

// New changes detected while processing
if (changes.size) {
callback();
}
};

for await (const event of watcher) {
Expand All @@ -124,23 +134,13 @@ export default class FSWatcher implements Watcher {
continue;
}

const changes = new Set<string>();
paths.forEach((path) => changes.add(normalizePath(relative(root, path))));

// If we're already processing and have a pending
// queue item, we can merge all future changes together
if (runningCallback && changeQueue.length > 0) {
const last = changeQueue[changeQueue.length - 1];
changeQueue[changeQueue.length - 1] = last.union(changes);
} else {
changeQueue.unshift(changes);

// Only start if processing queue is not already running
if (!runningCallback) {
// Debounce
clearTimeout(timer);
timer = setTimeout(callback, debounce ?? 100);
}
// Only start if processing queue is not already running
if (!runningCallback) {
// Debounce
clearTimeout(timer);
timer = setTimeout(callback, debounce ?? 100);
}
}
}
Expand Down

0 comments on commit 3c072e7

Please sign in to comment.