/
FilesRegister.ts
76 lines (60 loc) · 1.71 KB
/
FilesRegister.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
import * as ts from 'typescript'; // import for types alone
import { LintReport } from './types/eslint';
export interface DataShape {
source?: ts.SourceFile;
linted: boolean;
eslints: LintReport[];
}
export class FilesRegister {
private files: { [filePath: string]: { mtime?: number; data: DataShape } };
constructor(private dataFactory: (_data?: DataShape) => DataShape) {
this.files = {};
this.dataFactory = dataFactory;
}
public keys() {
return Object.keys(this.files);
}
public add(filePath: string) {
this.files[filePath] = {
mtime: undefined,
data: this.dataFactory(undefined)
};
}
public remove(filePath: string) {
if (this.has(filePath)) {
delete this.files[filePath];
}
}
public has(filePath: string) {
return this.files.hasOwnProperty(filePath);
}
public get(filePath: string) {
if (!this.has(filePath)) {
throw new Error('File "' + filePath + '" not found in register.');
}
return this.files[filePath];
}
public ensure(filePath: string) {
if (!this.has(filePath)) {
this.add(filePath);
}
}
public getData(filePath: string) {
return this.get(filePath).data;
}
public mutateData(filePath: string, mutator: (data: DataShape) => void) {
this.ensure(filePath);
mutator(this.files[filePath].data);
}
public getMtime(filePath: string) {
return this.get(filePath).mtime;
}
public setMtime(filePath: string, mtime: number) {
this.ensure(filePath);
if (this.files[filePath].mtime !== mtime) {
this.files[filePath].mtime = mtime;
// file has been changed - we have to reset data
this.files[filePath].data = this.dataFactory(this.files[filePath].data);
}
}
}