-
Notifications
You must be signed in to change notification settings - Fork 19
/
parser.js
398 lines (339 loc) · 9.91 KB
/
parser.js
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
const fs = require('fs/promises')
const { dirname } = require('path')
const yaml = require('yaml')
const NpmPackageJson = require('@npmcli/package-json')
const jsonParse = require('json-parse-even-better-errors')
const Diff = require('diff')
const { unset } = require('lodash')
const ini = require('ini')
const { minimatch } = require('minimatch')
const template = require('./template.js')
const jsonDiff = require('./json-diff')
const { merge } = require('./merge.js')
const setFirst = (first, rest) => ({ ...first, ...rest })
const traverse = (value, visit, keys = []) => {
if (keys.length) {
const res = visit(keys, value)
if (res != null) {
return
}
}
if (typeof value === 'object' && value !== null) {
for (const [k, v] of Object.entries(value)) {
traverse(v, visit, keys.concat(k))
}
}
}
const fsOk = code => error => {
if (error.code === 'ENOENT') {
return null
}
return Object.assign(error, { code })
}
class Base {
static types = []
static header = 'This file is automatically added by {{ __NAME__ }}. Do not edit.'
comment = v => v
merge = false // supply a merge function which runs on prepare for certain types
DELETE = template.DELETE
constructor(target, source, options, fileOptions) {
this.target = target
this.source = source
this.options = options
this.fileOptions = fileOptions
}
header() {
if (typeof this.comment === 'function') {
return this.comment(this.template(this.constructor.header || ''))
}
}
clean() {
if (this.fileOptions.clean) {
return fs.rm(this.target).catch(fsOk())
}
return null
}
read(s) {
if (Array.isArray(s)) {
return Promise.all(s.map(f => this.read(f)))
}
return fs.readFile(s, { encoding: 'utf-8' })
}
template(s) {
if (Array.isArray(s)) {
return Promise.all(s.map(f => this.template(f)))
}
return template(s, this.options)
}
parse(s) {
return s
}
prepare(s) {
const header = this.header()
return header ? `${header}\n\n${s}` : s
}
prepareTarget(s) {
return s
}
toString(s) {
return s.toString()
}
async write(s) {
// XXX: find more efficient way to do this. we can build all possible dirs before get here
await fs.mkdir(dirname(this.target), { owner: 'inherit', recursive: true, force: true })
return fs.writeFile(this.target, this.toString(s), { owner: 'inherit' })
}
diffPatch(t, s) {
// create a patch and strip out the filename. if it ends up an empty string
// then return true since the files are equal
return Diff.createPatch('', t.replace(/\r\n/g, '\n'), s.replace(/\r\n/g, '\n')).split('\n').slice(4).join('\n')
}
diff(t, s) {
return this.diffPatch(t, s)
}
// the apply methods are the only ones that should be called publically
// XXX: everything is allowed to be overridden in base classes but we could
// find a different solution than making everything public
applyWrite() {
return (
Promise.resolve(this.clean())
.then(() => this.read(this.source))
// replace template vars first, this will throw for nonexistant vars
// because it must be parseable after this step
.then(s => this.template(s))
// parse into whatever data structure is necessary for maniuplating
// diffing, merging, etc. by default its a string
.then(s => {
this.sourcePreParse = s
return this.parse(s)
})
// prepare the source for writing and diffing, pass in current
// target for merging. errors parsing or preparing targets are ok here
.then(s =>
this.applyTarget()
.catch(() => null)
.then(t => this.prepare(s, t)),
)
.then(s => this.write(s))
)
}
applyTarget() {
return (
Promise.resolve(this.read(this.target))
.then(s => this.parse(s))
// for only preparing the target for diffing
.then(s => this.prepareTarget(s))
)
}
async applyDiff() {
// handle if old does not exist
const targetError = 'ETARGETERROR'
const target = await this.applyTarget().catch(fsOk(targetError))
// no need to diff if current file does not exist
if (target === null) {
return null
}
const source = await Promise.resolve(this.read(this.source))
.then(s => this.template(s))
.then(s => this.parse(s))
// gets the target to diff against in case it needs to merge, etc
.then(s => this.prepare(s, target))
// if there was a target error then there is no need to diff
// so we just show the source with an error message
if (target.code === targetError) {
const msg = `[${this.options.config.__NAME__} ERROR]`
return [
`${msg} There was an erroring getting the target file`,
`${msg} ${target}`,
`${msg} It will be overwritten with the following source:`,
'-'.repeat(40),
this.toString(source),
].join('\n')
}
// individual diff methods are responsible for returning a string
// representing the diff. an empty trimmed string means no diff
const diffRes = this.diff(target, source).trim()
return diffRes || true
}
}
class Gitignore extends Base {
static types = ['codeowners', '.gitignore', '.prettierignore']
comment = c => `# ${c}`
}
class Js extends Base {
static types = ['*.js', '*.cjs']
comment = c => `/* ${c} */`
}
class Ini extends Base {
static types = ['*.ini']
comment = c => `; ${c}`
toString(s) {
return typeof s === 'string' ? s : ini.stringify(s)
}
parse(s) {
return typeof s === 'string' ? ini.parse(s) : s
}
prepare(s, t) {
let source = s
if (typeof this.merge === 'function' && t) {
source = this.merge(t, s)
}
return super.prepare(this.toString(source))
}
diff(t, s) {
return jsonDiff(this.parse(t), this.parse(s), this.DELETE)
}
}
class IniMerge extends Ini {
static types = ['.npmrc']
merge = (t, s) => merge(t, s)
}
class Markdown extends Base {
static types = ['*.md']
comment = c => `<!-- ${c} -->`
}
class Yml extends Base {
static types = ['*.yml']
comment = c => ` ${c}`
toString(s) {
try {
return s.toString({ lineWidth: 0, indent: 2 })
} catch (err) {
err.message = [this.target, this.sourcePreParse, ...s.errors, err.message].join('\n')
throw err
}
}
parse(s) {
return yaml.parseDocument(s)
}
prepare(s) {
s.commentBefore = this.header()
return this.toString(s)
}
prepareTarget(s) {
return this.toString(s)
}
}
class YmlMerge extends Yml {
prepare(source, t) {
if (t === null) {
// If target does not exist or is in an
// error state, we cant do anything but write
// the whole document
return super.prepare(source)
}
const key = [].concat(this.key)
const getId = node => {
const index = node.items.findIndex(p => p.key?.value === this.id)
return index !== -1 ? node.items[index].value?.value : node.toJSON()
}
const target = this.parse(t)
const targetNodes = target.getIn(key).items.reduce((acc, node, index) => {
acc[getId(node)] = { node, index }
return acc
}, {})
for (const node of source.getIn(key).items) {
const index = targetNodes[getId(node)]?.index
if (typeof index === 'number' && index !== -1) {
target.setIn([...key, index], node)
} else {
target.addIn(key, node)
}
}
return super.prepare(target)
}
}
class Json extends Base {
static types = ['*.json']
// its a json comment! not really but we do add a special key
// to json objects
comment = c => ({ [`//${this.options.config.__NAME__}`]: c })
toString(s) {
return JSON.stringify(s, (_, v) => (v === this.DELETE ? undefined : v), 2).trim() + '\n'
}
parse(s) {
if (Array.isArray(s)) {
return s.map(f => this.parse(f)).reduce((a, f) => this.merge(a, f), {})
}
return jsonParse(s)
}
prepare(s, t) {
let source = s
if (typeof this.merge === 'function' && t) {
source = this.merge(t, s)
}
return setFirst(this.header(), source)
}
diff(t, s) {
return jsonDiff(t, s, this.DELETE)
}
}
class JsonMerge extends Json {
static header = 'This file is partially managed by {{ __NAME__ }}. Edits may be overwritten.'
merge = (t, s) => merge(t, s)
}
class JsonMergeNoComment extends JsonMerge {
comment = null
}
class PackageJson extends JsonMerge {
static types = ['package.json']
async prepare(s, t) {
// merge new source with current pkg content
const update = super.prepare(s, t)
// move comment to config field
const configKey = this.options.config.__CONFIG_KEY__
const header = this.header()
const headerKey = Object.keys(header)[0]
update[configKey] = setFirst(header, update[configKey])
delete update[headerKey]
return update
}
async write(s) {
const pkg = await NpmPackageJson.load(dirname(this.target))
pkg.update(s)
traverse(pkg.content, (keys, value) => {
if (value === this.DELETE) {
return unset(pkg.content, keys)
}
})
await pkg.save()
}
}
const Parsers = {
Base,
Gitignore,
Js,
Ini,
IniMerge,
Markdown,
Yml,
YmlMerge,
Json,
JsonMerge,
JsonMergeNoComment,
PackageJson,
}
// Create an order to lookup parsers based on filename the only important part
// of ordering is that we want to match types by exact match first, then globs,
// so we always sort globs to the bottom
const parserLookup = []
for (const parser of Object.values(Parsers)) {
for (const type of parser.types) {
const parserEntry = [type, parser]
if (type.includes('*')) {
parserLookup.push(parserEntry)
} else {
parserLookup.unshift(parserEntry)
}
}
}
const getParser = file => {
for (const [type, parser] of parserLookup) {
if (minimatch(file, type, { nocase: true, dot: true, matchBase: true })) {
return parser
}
}
return Parsers.Base
}
module.exports = getParser
module.exports.Parsers = Parsers