This repository has been archived by the owner on Sep 24, 2020. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
State.ts
301 lines (243 loc) · 9.07 KB
/
State.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
import { alg, Graph } from 'graphlib'
import { EventEmitter } from 'events'
import * as os from 'os'
import * as path from 'path'
import { Command, OptionDefinition, OptionsInterface } from '@dicy/types'
import File from './File'
import Rule from './Rule'
import {
FileCache, DependencyType, KillToken, OptionInterfaceMap, Phase
} from './types'
function getLabel (x: File | Rule): string {
return (x instanceof File) ? x.filePath : x.id
}
type GraphProperties = {
components?: Rule[][]
}
function getConfigHome (): string {
// Even though Windows and MacOS do not follow the XDG Base Directory spec we
// allow the environment variable XDG_CONFIG_HOME to override the platform's
// default in case users want to maintain a consistent configuration setup
// across multiple platforms.
switch (process.platform) {
case 'win32':
return process.env.XDG_CONFIG_HOME || process.env.APPDATA ||
path.join(os.homedir(), 'AppData', 'Roaming')
case 'darwin':
return process.env.XDG_CONFIG_HOME ||
path.join(os.homedir(), 'Library', 'Application Support')
default:
return process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config')
}
}
export default class State extends EventEmitter {
readonly filePath: string
readonly rootPath: string
files: Map<string, File> = new Map()
rules: Map<string, Rule> = new Map()
options: {[name: string]: any} = {}
defaultOptions: OptionsInterface
optionSchema: Map<string, OptionDefinition> = new Map()
ruleClasses: typeof Rule[] = []
cacheTimeStamp: Date
processes: Set<number> = new Set<number>()
env: {[name: string]: string}
killToken: KillToken | null
private graph: Graph = new Graph()
private graphProperties: GraphProperties = {}
private optionProxies: Map<string | null, OptionsInterface> = new Map<string | null, OptionsInterface>()
constructor (filePath: string, schema: OptionDefinition[] = []) {
super()
const resolveFilePath: string = path.resolve(filePath)
const { dir, base, name, ext } = path.parse(resolveFilePath)
this.filePath = base
this.rootPath = dir,
this.graph.setDefaultEdgeLabel('default')
this.defaultOptions = {} as OptionsInterface
for (const option of schema) {
this.optionSchema.set(option.name, option)
for (const alias of option.aliases || []) {
this.optionSchema.set(alias, option)
}
if (option.defaultValue) this.defaultOptions[option.name] = option.defaultValue
}
this.resetOptions()
this.env = Object.assign({}, process.env, {
FILEPATH: base,
ROOTDIR: dir,
DIR: '.',
BASE: base,
NAME: name,
EXT: ext,
CONFIG_HOME: getConfigHome()
})
if (process.platform === 'win32') {
Object.assign(this.env, {
HOME: process.env.USERPROFILE,
PATH: process.env.Path
})
}
}
normalizePath (filePath: string): string {
filePath = path.normalize(filePath)
if (path.isAbsolute(filePath)) {
const dirPaths: string[] = [
this.rootPath
]
for (const dir of dirPaths) {
const candidateFilePath = path.relative(dir, filePath)
if (!candidateFilePath.startsWith('..')) {
return candidateFilePath
}
}
}
return filePath
}
async addRule (rule: Rule): Promise<void> {
this.rules.set(rule.id, rule)
this.addNode(rule.id)
rule.addActions()
}
removeRule (rule: Rule): void {
this.rules.delete(rule.id)
this.removeNode(rule.id)
}
removeFile (file: File): void {
this.files.delete(file.filePath)
this.removeNode(file.filePath)
}
getRuleId (name: string, command: Command, phase: Phase, jobName: string | null = null, parameters: string[] = []): string {
const items: string[] = [command, phase, jobName || ''].concat(parameters)
return `${name}(${items.join(';')})`
}
getRule (name: string, command: Command, phase: Phase, jobName: string | null = null, parameters: string[] = []): Rule | undefined {
const id: string = this.getRuleId(name, command, phase, jobName, parameters)
return this.rules.get(id)
}
addNode (x: string): void {
this.graph.setNode(x)
this.graphProperties = {}
}
removeNode (x: string): void {
this.graph.removeNode(x)
this.graphProperties = {}
}
hasInEdge (x: string, type?: DependencyType): boolean {
const edges = this.graph.inEdges(x)
return !!edges && edges.some(edge => !type || this.graph.edge(edge) === type)
}
hasOutEdge (x: string, type?: DependencyType): boolean {
const edges = this.graph.outEdges(x)
return !!edges && edges.some(edge => !type || this.graph.edge(edge) === type)
}
hasEdge (x: string, y: string): boolean {
return this.graph.hasEdge(x, y)
}
edge (x: string, y: string): DependencyType {
return this.graph.edge(x,y)
}
addEdge (x: string, y: string, type: DependencyType = 'default'): void {
this.graph.setEdge(x, y, type)
this.graphProperties = {}
}
removeEdge (x: string, y: string): void {
this.graph.removeEdge(x, y)
this.graphProperties = {}
}
async getFile (filePath: string, fileCache?: FileCache): Promise<File | undefined> {
filePath = this.normalizePath(filePath)
let file: File | undefined = this.files.get(filePath)
if (!file) {
file = await File.create(path.resolve(this.rootPath, filePath), filePath, fileCache)
if (!file) {
this.graph.removeNode(filePath)
return undefined
}
this.addNode(filePath)
this.files.set(filePath, file)
}
return file
}
resetOptions (): void {
for (const name of Object.getOwnPropertyNames(this.options)) {
delete this.options[name]
}
Object.assign(this.options, this.defaultOptions)
}
getJobOptions (jobName: string | null = null): OptionsInterface {
let optionProxy: OptionsInterface | undefined = this.optionProxies.get(jobName)
if (!optionProxy) {
optionProxy = new Proxy(this.options, {
get: (target, name) => {
if (name === 'jobNames') {
if ('jobName' in target) return [target.jobName]
if ('jobNames' in target) return target.jobNames
if ('jobs' in target) return Object.keys(target.jobs)
return [null]
}
if (jobName) {
if (name === 'jobName') return jobName
if ('jobs' in target) {
const jobOptions: OptionInterfaceMap = target.jobs[jobName]
if (jobOptions && name in jobOptions) return jobOptions[name.toString()]
}
}
const schema: OptionDefinition | void = this.optionSchema.get(name.toString())
if (schema && schema.type === 'boolean') {
return !!target[name.toString()]
}
return (name === 'filePath') ? this.filePath : target[name.toString()]
},
ownKeys: target => {
const keys: Set<string> = new Set<string>(['filePath', 'jobNames'])
if (jobName && 'jobs' in target) {
const jobOptions: OptionInterfaceMap = target.jobs[jobName]
if (jobOptions) Object.keys(jobOptions).forEach(key => keys.add(key))
}
this.optionSchema.forEach(option => {
if (option.type === 'boolean') keys.add(option.name)
})
Object.keys(target).forEach(key => keys.add(key))
keys.delete('jobs')
return Array.from(keys.values())
}
}) as OptionsInterface
this.optionProxies.set(jobName, optionProxy)
}
return optionProxy
}
get components (): Rule[][] {
if (!this.graphProperties.components) {
this.graphProperties.components = alg.components(this.graph)
.map(component => component.map(id => this.rules.get(id)).filter(rule => rule) as Rule[])
.filter(component => component.length > 0)
}
return this.graphProperties.components
}
isGrandparentOf (x: File | Rule, y: File | Rule): boolean {
const xLabel: string = getLabel(x)
const yLabel: string = getLabel(y)
const predecessors: string[] = this.graph.predecessors(yLabel) || []
return predecessors.some(file => (this.graph.predecessors(file) || []).some(r => r === xLabel))
}
getInputRules (file: File): Rule[] {
const successors = this.graph.successors(file.filePath) || []
return successors.map(id => this.rules.get(id)).filter(rule => rule) as Rule[]
}
getOutputRules (file: File): Rule[] {
const predecessors = this.graph.predecessors(file.filePath) || []
return predecessors.map(id => this.rules.get(id)).filter(rule => rule) as Rule[]
}
isOutputOf (file: File, ruleId: string): boolean {
const inEdges = this.graph.inEdges(file.filePath) || []
return inEdges.some(edge => edge.v.startsWith(ruleId))
}
getInputFiles (rule: Rule): File[] {
const predecessors = this.graph.predecessors(rule.id) || []
return predecessors.map(filePath => this.files.get(filePath)).filter(file => file) as File[]
}
getOutputFiles (rule: Rule): File[] {
const successors = this.graph.successors(rule.id) || []
return successors.map(filePath => this.files.get(filePath)).filter(file => file) as File[]
}
}