@voxgig/sdkgen 4.37.0 → 4.39.0

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