-
-
Notifications
You must be signed in to change notification settings - Fork 197
/
Copy pathcancellation.ts
83 lines (70 loc) · 2.05 KB
/
cancellation.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import * as choki from "chokidar";
import * as path from "path";
import * as os from "os";
import * as _ from "lodash";
import {
IHostInfo,
IFileSystem,
IDictionary,
ICancellationService,
ErrorCodes,
} from "../declarations";
import { injector } from "../yok";
class CancellationService implements ICancellationService {
private watches: IDictionary<choki.FSWatcher> = {};
constructor(
private $fs: IFileSystem,
private $logger: ILogger,
private $hostInfo: IHostInfo
) {
if (this.$hostInfo.isWindows) {
this.$fs.createDirectory(CancellationService.killSwitchDir);
}
}
public async begin(name: string): Promise<void> {
if (!this.$hostInfo.isWindows) {
return;
}
const triggerFile = CancellationService.makeKillSwitchFileName(name);
if (!this.$fs.exists(triggerFile)) {
this.$fs.writeFile(triggerFile, "");
}
this.$logger.trace("Starting watch on killswitch %s", triggerFile);
const watcher = choki
.watch(triggerFile, { ignoreInitial: true })
.on("unlink", (filePath: string) => {
this.$logger.info(
`Exiting process as the file ${filePath} has been deleted. Probably reinstalling CLI while there's a working instance.`
);
process.exit(ErrorCodes.DELETED_KILL_FILE);
});
if (watcher) {
this.watches[name] = watcher;
}
}
public end(name: string): void {
const watcher = this.watches[name];
if (watcher) {
delete this.watches[name];
watcher.close().then().catch();
}
}
public dispose(): void {
_(this.watches)
.keys()
.each((name) => this.end(name));
}
private static get killSwitchDir(): string {
try {
const { username } = os.userInfo();
return path.join(os.tmpdir(), username, "KillSwitches");
} catch (err) {
// os.userInfo throws when there's no username of home directory - we'll default to a generic folder
return path.join(os.tmpdir(), ".nativescript-cli", "KillSwitches");
}
}
private static makeKillSwitchFileName(name: string): string {
return path.join(CancellationService.killSwitchDir, name);
}
}
injector.register("cancellation", CancellationService);