@voxgig/sdkgen 4.38.0 → 4.39.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,712 @@
1
+ import Path from 'node:path'
2
+ import { realpathSync } from 'node:fs'
3
+ import { execFileSync } from 'node:child_process'
4
+
5
+ import { DiffUtil } from 'jostraca'
6
+
7
+
8
+ // How a toolchain write treats a project file the project changed after the
9
+ // toolchain last wrote it.
10
+ // merge a three-way merge of the incoming copy into the local change
11
+ // overwrite the incoming copy replaces the file
12
+ type CopyMode = 'merge' | 'overwrite'
13
+
14
+ const MERGE: CopyMode = 'merge'
15
+ const OVERWRITE: CopyMode = 'overwrite'
16
+
17
+
18
+ type GuardSpec = {
19
+ fs: any
20
+ folder: string
21
+ log: any
22
+ mode: CopyMode
23
+ what: string
24
+ force?: boolean
25
+ keep?: boolean
26
+ dryrun?: boolean
27
+
28
+ // Relative to `folder`, with forward slashes.
29
+ manage: (rel: string) => boolean
30
+
31
+ // The fingerprint of what the toolchain wrote at `rel` last time, read
32
+ // before the run starts.
33
+ recorded: (rel: string) => string | undefined
34
+ fingerprint: (content: any) => string
35
+
36
+ basedir: string
37
+ conflictdir: string
38
+
39
+ // Earlier versions of a file, newest first, for a base the store lacks.
40
+ versions?: (abs: string) => Iterable<Buffer>
41
+
42
+ error?: (msg: string) => Error
43
+ }
44
+
45
+
46
+ type Conflict = {
47
+ rel: string
48
+ why: 'conflict' | 'nobase' | 'binary'
49
+ preview?: Buffer
50
+ }
51
+
52
+
53
+ type MergeOutcome = {
54
+ merged: string[]
55
+ kept: string[]
56
+ retained: string[]
57
+ spared: string[]
58
+ }
59
+
60
+
61
+ const DELETED = Symbol('deleted')
62
+
63
+ type Pending = Buffer | typeof DELETED
64
+
65
+
66
+ function copyMode(value: any): CopyMode {
67
+ return OVERWRITE === value ? OVERWRITE : MERGE
68
+ }
69
+
70
+
71
+ async function withCopyMerge<T>(
72
+ spec: GuardSpec, run: (fs: any) => Promise<T>,
73
+ ): Promise<T> {
74
+ if (MERGE !== spec.mode || true === spec.force || true === spec.dryrun) {
75
+ const result = await run(spec.fs)
76
+ if (true !== spec.dryrun) {
77
+ clearConflicts(spec)
78
+ }
79
+ return result
80
+ }
81
+
82
+ const guard = new CopyGuard(spec)
83
+
84
+ let result: T
85
+ try {
86
+ result = await run(guard.fs)
87
+ }
88
+ catch (err: any) {
89
+ guard.rollback()
90
+ throw err
91
+ }
92
+
93
+ guard.finish()
94
+ return result
95
+ }
96
+
97
+
98
+ // The previews of a run that stopped are stale once a later run completes.
99
+ function clearConflicts(spec: GuardSpec) {
100
+ const dir = Path.join(Path.resolve(spec.folder), ...spec.conflictdir.split('/'))
101
+ if (spec.fs.existsSync(dir)) {
102
+ spec.fs.rmSync(dir, { recursive: true, force: true })
103
+ }
104
+ }
105
+
106
+
107
+ class CopyGuard {
108
+ spec: GuardSpec
109
+ real: any
110
+ root: string
111
+ fs: any
112
+
113
+ orig = new Map<string, Buffer | null>()
114
+ dirs: string[] = []
115
+ edited = new Map<string, boolean>()
116
+ pending = new Map<string, Pending>()
117
+ touched = new Set<string>()
118
+ spared: string[] = []
119
+
120
+ constructor(spec: GuardSpec) {
121
+ this.spec = spec
122
+ this.real = spec.fs
123
+ this.root = Path.resolve(spec.folder)
124
+ this.fs = this.wrap()
125
+ }
126
+
127
+
128
+ wrap(): any {
129
+ const real = this.real
130
+ const gfs: any = {}
131
+
132
+ for (const key in real) {
133
+ const val = real[key]
134
+ gfs[key] = 'function' === typeof val ? val.bind(real) : val
135
+ }
136
+
137
+ gfs.writeFileSync = (path: any, data: any, opts?: any) => {
138
+ if (this.holds(path, toBuffer(data, opts))) {
139
+ return
140
+ }
141
+ this.before(path)
142
+ return real.writeFileSync(path, data, opts)
143
+ }
144
+
145
+ gfs.appendFileSync = (path: any, data: any, opts?: any) => {
146
+ this.before(path)
147
+ return real.appendFileSync(path, data, opts)
148
+ }
149
+
150
+ gfs.copyFileSync = (from: any, to: any, mode?: any) => {
151
+ if (this.holds(to, Buffer.from(real.readFileSync(from)))) {
152
+ return
153
+ }
154
+ this.before(to)
155
+ return real.copyFileSync(from, to, mode)
156
+ }
157
+
158
+ gfs.renameSync = (from: any, to: any) => {
159
+ const data = this.isFile(from) ? this.read(from) : undefined
160
+ if (null != data && this.holds(to, data)) {
161
+ this.before(from)
162
+ real.unlinkSync(from)
163
+ return
164
+ }
165
+ this.before(from)
166
+ this.before(to)
167
+ return real.renameSync(from, to)
168
+ }
169
+
170
+ gfs.unlinkSync = (path: any) => {
171
+ if (this.spares(path)) {
172
+ return
173
+ }
174
+ this.before(path)
175
+ return real.unlinkSync(path)
176
+ }
177
+
178
+ gfs.mkdirSync = (path: any, opts?: any) => {
179
+ const missing = this.missingDirs(path)
180
+ const res = real.mkdirSync(path, opts)
181
+ this.dirs.push(...missing.filter((dir: string) => real.existsSync(dir)))
182
+ return res
183
+ }
184
+
185
+ gfs.readFileSync = (path: any, opts?: any) => {
186
+ const held = 'string' === typeof path ?
187
+ this.pending.get(Path.resolve(path)) : undefined
188
+ if (held instanceof Buffer) {
189
+ const encoding = 'string' === typeof opts ? opts : opts?.encoding
190
+ return null == encoding ? Buffer.from(held) : held.toString(encoding)
191
+ }
192
+ return real.readFileSync(path, opts)
193
+ }
194
+
195
+ return gfs
196
+ }
197
+
198
+
199
+ rel(path: any): string | undefined {
200
+ if ('string' !== typeof path) {
201
+ return undefined
202
+ }
203
+
204
+ const rel = Path.relative(this.root, Path.resolve(path)).split(Path.sep).join('/')
205
+
206
+ return ('' === rel || '..' === rel || rel.startsWith('../') || Path.isAbsolute(rel)) ?
207
+ undefined : rel
208
+ }
209
+
210
+
211
+ managed(rel: string | undefined): rel is string {
212
+ return null != rel &&
213
+ !within(rel, this.spec.basedir) && !within(rel, this.spec.conflictdir) &&
214
+ this.spec.manage(rel)
215
+ }
216
+
217
+
218
+ isFile(path: any): boolean {
219
+ try {
220
+ return true === this.real.statSync(path)?.isFile()
221
+ }
222
+ catch (err: any) {
223
+ return false
224
+ }
225
+ }
226
+
227
+
228
+ read(path: any): Buffer {
229
+ return Buffer.from(this.real.readFileSync(path))
230
+ }
231
+
232
+
233
+ createdHere(abs: string): boolean {
234
+ return this.orig.has(abs) && null === this.orig.get(abs)
235
+ }
236
+
237
+
238
+ before(path: any) {
239
+ if ('string' !== typeof path) {
240
+ return
241
+ }
242
+
243
+ const abs = Path.resolve(path)
244
+
245
+ if (!this.orig.has(abs)) {
246
+ if (this.isFile(abs)) {
247
+ this.orig.set(abs, this.read(abs))
248
+ }
249
+ else if (!this.real.existsSync(abs)) {
250
+ this.orig.set(abs, null)
251
+ }
252
+ }
253
+
254
+ const rel = this.rel(abs)
255
+ if (this.managed(rel)) {
256
+ this.touched.add(rel)
257
+ }
258
+ }
259
+
260
+
261
+ // Was this file changed after the toolchain wrote it? Asked once, before
262
+ // the run writes it; a file the record does not hold counts as changed.
263
+ isEdited(rel: string, abs: string): boolean {
264
+ let edited = this.edited.get(rel)
265
+
266
+ if (null == edited) {
267
+ const print = this.spec.recorded(rel)
268
+ edited = null == print || print !== this.spec.fingerprint(this.read(abs))
269
+ this.edited.set(rel, edited)
270
+ }
271
+
272
+ return edited
273
+ }
274
+
275
+
276
+ // Defers a write over a locally changed file, leaving it on disk as it is.
277
+ holds(path: any, data: Buffer): boolean {
278
+ if ('string' !== typeof path) {
279
+ return false
280
+ }
281
+
282
+ const abs = Path.resolve(path)
283
+ const rel = this.rel(abs)
284
+
285
+ if (!this.managed(rel)) {
286
+ return false
287
+ }
288
+
289
+ if (this.pending.has(abs)) {
290
+ this.pending.set(abs, data)
291
+ return true
292
+ }
293
+
294
+ if (this.createdHere(abs) || !this.isFile(abs) || !this.isEdited(rel, abs)) {
295
+ return false
296
+ }
297
+
298
+ if (sameText(this.read(abs), data)) {
299
+ return false
300
+ }
301
+
302
+ this.pending.set(abs, data)
303
+ return true
304
+ }
305
+
306
+
307
+ // A delete of a changed file, or of one no add wrote, leaves it in place.
308
+ spares(path: any): boolean {
309
+ if ('string' !== typeof path) {
310
+ return false
311
+ }
312
+
313
+ const abs = Path.resolve(path)
314
+ const rel = this.rel(abs)
315
+
316
+ if (!this.managed(rel) || this.createdHere(abs) || !this.isFile(abs)) {
317
+ return false
318
+ }
319
+
320
+ if (null == this.spec.recorded(rel)) {
321
+ this.spared.push(rel)
322
+ return true
323
+ }
324
+
325
+ if (this.pending.has(abs) || this.isEdited(rel, abs)) {
326
+ this.pending.set(abs, DELETED)
327
+ return true
328
+ }
329
+
330
+ return false
331
+ }
332
+
333
+
334
+ missingDirs(path: any): string[] {
335
+ if ('string' !== typeof path) {
336
+ return []
337
+ }
338
+
339
+ const missing: string[] = []
340
+ let dir = Path.resolve(path)
341
+
342
+ while (!this.real.existsSync(dir) && Path.dirname(dir) !== dir) {
343
+ missing.push(dir)
344
+ dir = Path.dirname(dir)
345
+ }
346
+
347
+ return missing
348
+ }
349
+
350
+
351
+ // An incoming copy the record already holds is its own base: the source
352
+ // did not move since the add that wrote it.
353
+ base(rel: string, incoming: Buffer): Buffer | undefined {
354
+ const print = this.spec.recorded(rel)
355
+
356
+ if (null == print) {
357
+ return undefined
358
+ }
359
+
360
+ if (print === this.spec.fingerprint(incoming)) {
361
+ return incoming
362
+ }
363
+
364
+ const stored = this.storePath(this.spec.basedir, rel)
365
+ if (this.isFile(stored)) {
366
+ const base = this.read(stored)
367
+ if (print === this.spec.fingerprint(base)) {
368
+ return base
369
+ }
370
+ }
371
+
372
+ for (const version of this.spec.versions?.(Path.join(this.root, rel)) ?? []) {
373
+ if (print === this.spec.fingerprint(version)) {
374
+ return version
375
+ }
376
+ }
377
+
378
+ return undefined
379
+ }
380
+
381
+
382
+ storePath(dir: string, rel: string): string {
383
+ return Path.join(this.root, ...dir.split('/'), ...rel.split('/'))
384
+ }
385
+
386
+
387
+ finish(): MergeOutcome {
388
+ const outcome: MergeOutcome = { merged: [], kept: [], retained: [], spared: this.spared }
389
+ const conflicts: Conflict[] = []
390
+ const writes: [string, Buffer][] = []
391
+ const bases = new Map<string, Buffer>()
392
+
393
+ for (const [abs, incoming] of this.pending) {
394
+ const rel = this.rel(abs) as string
395
+
396
+ if (DELETED === incoming) {
397
+ outcome.retained.push(rel)
398
+ continue
399
+ }
400
+
401
+ const local = this.read(abs)
402
+ const base = this.base(rel, incoming)
403
+
404
+ let conflict: Conflict | undefined
405
+ let merged: Buffer | undefined
406
+
407
+ if (null == base) {
408
+ conflict = { rel, why: 'nobase', preview: incoming }
409
+ }
410
+ else if (isBinary(incoming) || isBinary(local) || isBinary(base)) {
411
+ conflict = { rel, why: 'binary', preview: incoming }
412
+ }
413
+ else {
414
+ const res = merge3(incoming, base, local, this.spec.what)
415
+ if (res.conflict) {
416
+ conflict = { rel, why: 'conflict', preview: res.content }
417
+ }
418
+ else {
419
+ merged = res.content
420
+ }
421
+ }
422
+
423
+ if (null != conflict && true === this.spec.keep) {
424
+ outcome.kept.push(rel)
425
+ bases.set(rel, incoming)
426
+ }
427
+ else if (null != conflict) {
428
+ conflicts.push(conflict)
429
+ }
430
+ else {
431
+ writes.push([abs, merged as Buffer])
432
+ outcome.merged.push(rel)
433
+ bases.set(rel, incoming)
434
+ }
435
+ }
436
+
437
+ if (0 < conflicts.length) {
438
+ this.rollback()
439
+ this.previews(conflicts)
440
+ throw this.failure(conflicts)
441
+ }
442
+
443
+ for (const [abs, content] of writes) {
444
+ if (!sameText(this.read(abs), content)) {
445
+ this.writeAtomic(abs, content)
446
+ }
447
+ }
448
+
449
+ this.keepBases(bases)
450
+ clearConflicts(this.spec)
451
+ this.report(outcome)
452
+
453
+ return outcome
454
+ }
455
+
456
+
457
+ // The store holds a base only where the file differs from it: elsewhere
458
+ // the file itself, checked against the record, is the base.
459
+ keepBases(bases: Map<string, Buffer>) {
460
+ for (const rel of new Set([...this.touched, ...bases.keys()])) {
461
+ const at = this.storePath(this.spec.basedir, rel)
462
+ const base = bases.get(rel)
463
+
464
+ if (null != base) {
465
+ this.real.mkdirSync(Path.dirname(at), { recursive: true })
466
+ this.real.writeFileSync(at, base)
467
+ }
468
+ else if (this.isFile(at)) {
469
+ this.real.unlinkSync(at)
470
+ }
471
+ }
472
+ }
473
+
474
+
475
+ rollback() {
476
+ for (const [abs, content] of Array.from(this.orig).reverse()) {
477
+ try {
478
+ if (null != content) {
479
+ this.real.writeFileSync(abs, content)
480
+ }
481
+ else if (this.isFile(abs)) {
482
+ this.real.unlinkSync(abs)
483
+ }
484
+ }
485
+ catch (err: any) {
486
+ this.spec.log.warn({
487
+ point: 'copy-merge-rollback', file: abs, err: err?.message,
488
+ note: 'could not restore ' + abs + ': ' + err?.message,
489
+ })
490
+ }
491
+ }
492
+
493
+ for (const dir of [...this.dirs].reverse()) {
494
+ try {
495
+ if (0 === this.real.readdirSync(dir).length) {
496
+ this.real.rmdirSync(dir)
497
+ }
498
+ }
499
+ catch (err: any) {
500
+ continue
501
+ }
502
+ }
503
+ }
504
+
505
+
506
+ previews(conflicts: Conflict[]) {
507
+ clearConflicts(this.spec)
508
+
509
+ const dir = this.storePath(this.spec.conflictdir, '')
510
+ this.real.mkdirSync(dir, { recursive: true })
511
+ this.real.writeFileSync(Path.join(dir, '.gitignore'), '*\n')
512
+
513
+ for (const conflict of conflicts) {
514
+ const at = this.storePath(this.spec.conflictdir, conflict.rel)
515
+ this.real.mkdirSync(Path.dirname(at), { recursive: true })
516
+ this.real.writeFileSync(at, conflict.preview ?? Buffer.alloc(0))
517
+ }
518
+ }
519
+
520
+
521
+ writeAtomic(abs: string, content: Buffer) {
522
+ const tmp = abs + '.copymerge-' + process.pid + '-' + Date.now()
523
+ this.real.writeFileSync(tmp, content)
524
+ this.real.renameSync(tmp, abs)
525
+ }
526
+
527
+
528
+ failure(conflicts: Conflict[]): Error {
529
+ const why = {
530
+ conflict: 'the incoming copy and the local change touch the same lines',
531
+ nobase: 'no record of what the toolchain wrote here, so nothing to merge ' +
532
+ 'against; a base is found in git once the copies an add writes are committed',
533
+ binary: 'a binary file, which is never merged',
534
+ }
535
+
536
+ const shown = this.spec.conflictdir
537
+
538
+ const msg = this.spec.what + ': ' + conflicts.length +
539
+ ' locally changed file(s) cannot take the incoming copy, so nothing was changed:\n ' +
540
+ conflicts.map((c: Conflict) => c.rel + ' (' + why[c.why] + ')').join('\n ') +
541
+ '\n\n The incoming copies are in ' + shown + '/, with conflict markers where ' +
542
+ 'both sides changed the same lines. Then either:' +
543
+ '\n - fold the incoming change into the local file by hand and re-run with ' +
544
+ '--keep, which keeps the local files and records the incoming copies as ' +
545
+ 'their base;' +
546
+ '\n - or re-run with --force, which takes the incoming copies and discards ' +
547
+ 'the local changes.'
548
+
549
+ return null == this.spec.error ? new Error(msg) : this.spec.error(msg)
550
+ }
551
+
552
+
553
+ report(outcome: MergeOutcome) {
554
+ const log = this.spec.log
555
+
556
+ if (0 < outcome.merged.length) {
557
+ log.info({
558
+ point: 'copy-merge-merged', files: outcome.merged,
559
+ note: this.spec.what + ': merged the incoming copy into ' +
560
+ outcome.merged.length + ' locally changed file(s): ' + outcome.merged.join(', ')
561
+ })
562
+ }
563
+
564
+ if (0 < outcome.kept.length) {
565
+ log.warn({
566
+ point: 'copy-merge-kept', files: outcome.kept,
567
+ note: this.spec.what + ': --keep, kept ' + outcome.kept.length +
568
+ ' local file(s) as they are: ' + outcome.kept.join(', ')
569
+ })
570
+ }
571
+
572
+ if (0 < outcome.retained.length) {
573
+ log.warn({
574
+ point: 'copy-merge-retained', files: outcome.retained,
575
+ note: this.spec.what + ': the source no longer provides ' +
576
+ outcome.retained.length + ' locally changed file(s), left in place: ' +
577
+ outcome.retained.join(', ')
578
+ })
579
+ }
580
+
581
+ if (0 < outcome.spared.length) {
582
+ log.info({
583
+ point: 'copy-merge-spared', files: outcome.spared,
584
+ note: this.spec.what + ': left ' + outcome.spared.length +
585
+ ' file(s) no add wrote in place: ' + outcome.spared.join(', ')
586
+ })
587
+ }
588
+ }
589
+ }
590
+
591
+
592
+ function merge3(
593
+ incoming: Buffer, base: Buffer, local: Buffer, what: string,
594
+ ): { conflict: boolean, content: Buffer } {
595
+ const text = (bytes: Buffer) => bytes.toString('latin1').replace(/\r\n/g, '\n')
596
+
597
+ const res: any = DiffUtil.merge(text(incoming), text(base), text(local), {
598
+ labels: { generated: 'INCOMING (' + what + ')', existing: 'LOCAL' },
599
+ })
600
+
601
+ return {
602
+ conflict: true === res.conflict || 'unresolved' === res.outcome,
603
+ content: Buffer.from(res.content, 'latin1'),
604
+ }
605
+ }
606
+
607
+
608
+ function within(rel: string, dir: string): boolean {
609
+ return rel === dir || rel.startsWith(dir + '/')
610
+ }
611
+
612
+
613
+ function toBuffer(data: any, opts?: any): Buffer {
614
+ if (Buffer.isBuffer(data)) {
615
+ return data
616
+ }
617
+
618
+ if (ArrayBuffer.isView(data)) {
619
+ return Buffer.from(data.buffer, data.byteOffset, data.byteLength)
620
+ }
621
+
622
+ const encoding = ('string' === typeof opts ? opts : opts?.encoding) || 'utf8'
623
+ return Buffer.from(String(data), encoding)
624
+ }
625
+
626
+
627
+ function sameText(a: Buffer, b: Buffer): boolean {
628
+ return a.toString('latin1').replace(/\r\n/g, '\n') ===
629
+ b.toString('latin1').replace(/\r\n/g, '\n')
630
+ }
631
+
632
+
633
+ function isBinary(bytes: Buffer): boolean {
634
+ return 0 <= bytes.subarray(0, 8000).indexOf(0)
635
+ }
636
+
637
+
638
+ // Committed versions of a file, newest first: the index, HEAD, then the
639
+ // commits that touched it. Nothing outside a git checkout.
640
+ function gitVersions(abs: string, limit = 20): Iterable<Buffer> {
641
+ return {
642
+ *[Symbol.iterator]() {
643
+ let top: string
644
+ let rel: string
645
+
646
+ try {
647
+ const dir = Path.dirname(abs)
648
+ top = git(dir, ['rev-parse', '--show-toplevel']).toString().trim()
649
+ const real = Path.join(realpathSync(dir), Path.basename(abs))
650
+ rel = Path.relative(top, real).split(Path.sep).join('/')
651
+ }
652
+ catch (err: any) {
653
+ return
654
+ }
655
+
656
+ const shown = (spec: string) => {
657
+ try {
658
+ return git(top, ['show', spec])
659
+ }
660
+ catch (err: any) {
661
+ return undefined
662
+ }
663
+ }
664
+
665
+ for (const spec of [':' + rel, 'HEAD:' + rel]) {
666
+ const version = shown(spec)
667
+ if (null != version) {
668
+ yield version
669
+ }
670
+ }
671
+
672
+ let shas: string[] = []
673
+ try {
674
+ shas = git(top, ['log', '--format=%H', '-n', String(limit), '--', rel])
675
+ .toString().split('\n').filter(Boolean)
676
+ }
677
+ catch (err: any) {
678
+ return
679
+ }
680
+
681
+ for (const sha of shas) {
682
+ const version = shown(sha + ':' + rel)
683
+ if (null != version) {
684
+ yield version
685
+ }
686
+ }
687
+ }
688
+ }
689
+ }
690
+
691
+
692
+ function git(cwd: string, args: string[]): Buffer {
693
+ return execFileSync('git', args, {
694
+ cwd, stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 256 * 1024 * 1024,
695
+ })
696
+ }
697
+
698
+
699
+ export type {
700
+ CopyMode,
701
+ GuardSpec,
702
+ MergeOutcome,
703
+ }
704
+
705
+ export {
706
+ MERGE,
707
+ OVERWRITE,
708
+ copyMode,
709
+ withCopyMerge,
710
+ gitVersions,
711
+ merge3,
712
+ }
package/src/types.ts CHANGED
@@ -121,6 +121,8 @@ type ActionContext = {
121
121
  flags?: Record<string, any>
122
122
 
123
123
  fetchPackage?: (pkgname: string, actx: ActionContext) => Promise<void>
124
+
125
+ copyGuarded?: boolean
124
126
  }
125
127
 
126
128