microsoft/typespec

Public

mirrored from https://github.com/microsoft/typespecAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
a6b7827fcd2db3bf604d42e235216c8d5b244f13

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

packages/internal-build-utils/src/watch.ts

56lines · modecode

1import chokidar from "chokidar";
2import { resolve } from "path";
3import { clearScreen, logWithTime } from "./common.js";
4
5export function runWatch(pattern: string, build: any, options?: any) {
6 let lastBuildTime: Date;
7 pattern = resolve(pattern);
8
9 start();
10
11 function start() {
12 // build once up-front
13 runBuild();
14
15 const watcher = chokidar.watch(pattern, { interval: 0.2, ...options });
16
17 // then build again on any change
18 watcher.on("add", (file) => runBuild(`${file} created`));
19 watcher.on("removed", (file) => runBuild(`${file} removed`));
20 watcher.on("change", (file, stats) => runBuild(`${file} changed`, stats?.mtime));
21 }
22
23 function runBuild(changeDescription?: string, changeTime?: Date) {
24 runBuildAsync(changeDescription, changeTime).catch((err) => {
25 // eslint-disable-next-line no-console
26 console.error(err.stack);
27 process.exit(1);
28 });
29 }
30
31 async function runBuildAsync(changeDescription?: string, changeTime?: Date) {
32 if (changeTime && lastBuildTime && changeTime < lastBuildTime) {
33 // Don't rebuild if a change happened before the last build kicked off.
34 // Defends against duplicate events and building more than once when a
35 // bunch of files are changed at the same time.
36 return;
37 }
38
39 lastBuildTime = new Date();
40 if (changeDescription) {
41 clearScreen();
42 logWithTime(`File change detected: ${changeDescription}. Running build.`);
43 } else {
44 logWithTime("Starting build in watch mode.");
45 }
46
47 try {
48 await build();
49 logWithTime("Build succeeded. Waiting for file changes.");
50 } catch (err: any) {
51 // eslint-disable-next-line no-console
52 console.error(err.stack);
53 logWithTime(`Build failed. Waiting for file changes.`);
54 }
55 }
56}
57