jostraca 0.40.0 → 0.41.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.
package/dist/types.d.ts CHANGED
@@ -20,6 +20,7 @@ type JostracaResult = {
20
20
  merged: string[];
21
21
  conflicted: string[];
22
22
  unchanged: string[];
23
+ unmerged: string[];
23
24
  };
24
25
  audit: () => Audit[];
25
26
  vol?: () => any;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jostraca",
3
- "version": "0.40.0",
3
+ "version": "0.41.0",
4
4
  "main": "dist/jostraca.js",
5
5
  "type": "commonjs",
6
6
  "types": "dist/jostraca.d.ts",
@@ -1,5 +1,6 @@
1
1
 
2
2
  import Path from 'node:path'
3
+ import { createHash } from 'node:crypto'
3
4
 
4
5
  import * as DiffUtil from '../diff'
5
6
  // import Os from 'node:os'
@@ -67,6 +68,17 @@ const MERGE_WHY: Record<string, string> = {
67
68
  merged: 'merge-run-0',
68
69
  }
69
70
 
71
+ // How many of a file's generates its meta entry remembers, newest last.
72
+ //
73
+ // MUST match fingerprintHistory in go/filehandler.go.
74
+ const FINGERPRINT_HISTORY = 8
75
+
76
+ // Why a `conflict: 'fail'` merge left a file as it was.
77
+ type MergeFailure = {
78
+ path: string
79
+ reason: 'conflict' | 'unresolved' | 'nobase'
80
+ }
81
+
70
82
  // Suffix for the sibling temp file used by the atomic write-then-rename.
71
83
  const TMP_SUFFIX = '.jostraca-tmp'
72
84
 
@@ -111,6 +123,14 @@ function sameContent(a: string | Buffer, b: string | Buffer): boolean {
111
123
  }
112
124
 
113
125
 
126
+ // A generate's fingerprint: the first 16 hex digits of its SHA-256, which
127
+ // is plenty to tell one file's generates apart. A string is hashed as its
128
+ // UTF-8 bytes, the bytes save writes.
129
+ function fingerprint(content: string | Buffer): string {
130
+ return createHash('sha256').update(content).digest('hex').substring(0, 16)
131
+ }
132
+
133
+
114
134
  class FileHandler {
115
135
 
116
136
  when: number
@@ -129,6 +149,7 @@ class FileHandler {
129
149
  last: () => number
130
150
  addmeta: (file: string, meta: any) => void
131
151
  metafile: () => string
152
+ prevmeta: (rpath: string) => any
132
153
  files: {
133
154
  preserved: string[]
134
155
  written: string[]
@@ -137,7 +158,9 @@ class FileHandler {
137
158
  merged: string[]
138
159
  conflicted: string[]
139
160
  unchanged: string[]
161
+ unmerged: string[]
140
162
  }
163
+ failures: MergeFailure[]
141
164
  createdDirs: Set<string>
142
165
  savedPaths: Set<string>
143
166
  filelogged: Record<string, Set<string>>
@@ -171,7 +194,9 @@ class FileHandler {
171
194
  merged: [],
172
195
  conflicted: [],
173
196
  unchanged: [],
197
+ unmerged: [],
174
198
  }
199
+ this.failures = []
175
200
 
176
201
  this.createdDirs = new Set()
177
202
  this.savedPaths = new Set()
@@ -182,6 +207,10 @@ class FileHandler {
182
207
  this.last = () => bctx.bmeta.prev.last
183
208
  this.addmeta = bctx.addmeta.bind(bctx)
184
209
  this.metafile = () => bctx.bmeta.next.filename
210
+ this.prevmeta = (rpath: string) => {
211
+ const files = bctx.bmeta.prev.files
212
+ return Object.prototype.hasOwnProperty.call(files, rpath) ? files[rpath] : undefined
213
+ }
185
214
 
186
215
  if (!this.fs().existsSync) {
187
216
  throw new Error(CN + ' Invalid file system provider: ' + this.fs())
@@ -339,6 +368,9 @@ class FileHandler {
339
368
  const isTextFile = null == isText ? !isbinext(path) : isText
340
369
  const existing = isTextFile ? this.existing.txt : this.existing.bin
341
370
 
371
+ // `conflict` is a text option: `existing.bin` has no merge.
372
+ const failOnConflict = 'fail' === existing.conflict
373
+
342
374
  const withinFolder = this.withinFolder(path)
343
375
 
344
376
  const rpath = this.relative(path, FN + wstr)
@@ -376,6 +408,15 @@ class FileHandler {
376
408
  // Whether the save ends in a write or skip record.
377
409
  let final = false
378
410
 
411
+ // Whether the file now holds this generate: written, already equal,
412
+ // merged (markers and all) or diffed. Only then does the baseline move
413
+ // on to it. A file that was skipped, protected, presented, left with
414
+ // an earlier merge's markers, or refused by `conflict: 'fail'` still
415
+ // derives from the previous generate, and a baseline moved past it
416
+ // made the next merge read the generator's own older lines as the
417
+ // user's edits and keep them.
418
+ let landed = false
419
+
379
420
  if (exists) {
380
421
  why.push('exists-0')
381
422
  // The existing file is handled as BYTES, text included, as Go does.
@@ -391,6 +432,9 @@ class FileHandler {
391
432
 
392
433
  unchanged = sameContent(currentContent, newContentSource)
393
434
 
435
+ // Equal bytes hold the generate whatever the mode does with them.
436
+ landed = unchanged
437
+
394
438
  if (existing.preserve) {
395
439
  why.push('preserve-0')
396
440
 
@@ -455,6 +499,7 @@ class FileHandler {
455
499
 
456
500
  this.saveFile(path, Buffer.from(diffContent, 'latin1'),
457
501
  modeopts(), whence + meta.action)
502
+ landed = true
458
503
 
459
504
  // this.files.diffed.push(path)
460
505
  this.filelog('diffed', path)
@@ -480,6 +525,7 @@ class FileHandler {
480
525
  }
481
526
  // this.files.unchanged.push(path)
482
527
  this.filelog('unchanged', path)
528
+ landed = true
483
529
  }
484
530
  }
485
531
  else if (existing.merge) {
@@ -488,6 +534,8 @@ class FileHandler {
488
534
  if (!unchanged) {
489
535
  why.push('content-3')
490
536
 
537
+ let baseline: Buffer | undefined
538
+
491
539
  if (this.control.duplicate) {
492
540
  why.push('duplicate-0')
493
541
  const dfolder = this.duplicateFolder()
@@ -496,51 +544,83 @@ class FileHandler {
496
544
 
497
545
  if (this.existsFile(dpath)) {
498
546
  why.push('dupexists-0')
547
+ baseline = this.loadFile(dpath, { encoding: null }) as Buffer
548
+ }
549
+ }
499
550
 
500
- write = false
501
- meta.action = 'merge'
502
-
503
- const prevGenContent = this.loadFile(dpath, { encoding: null }) as Buffer
504
-
505
- const mergeres = this.merge(
506
- latin1(newContentSource), // generated
507
- latin1(prevGenContent), // baseline (last generate)
508
- latin1(currentContent), // existing (on disk)
551
+ // A file that is byte for byte one of its own earlier generates
552
+ // holds nobody's edit, whatever the baseline says. A checkout
553
+ // or a branch switch puts an older generate back while the
554
+ // baseline, which git ignores, stays where the last run left
555
+ // it, and merging against that baseline kept the older lines
556
+ // as if the user had written them.
557
+ const earlier =
558
+ (null == baseline || !sameContent(baseline, currentContent)) &&
559
+ this.priorFingerprints(rpath).includes(fingerprint(currentContent))
560
+
561
+ if (null != baseline || earlier) {
562
+ write = false
563
+ meta.action = 'merge'
564
+
565
+ const mergeres = earlier ?
566
+ this.earlier(newContentSource, why) :
567
+ this.merge(
568
+ latin1(newContentSource), // generated
569
+ latin1(baseline as Buffer), // baseline (last generate)
570
+ latin1(currentContent), // existing (on disk)
509
571
  why
510
572
  )
511
- const diffcontent = mergeres.content
512
-
513
- // A file still holding an earlier merge's markers is left
514
- // byte-for-byte untouched, and reported conflicted: it
515
- // still carries markers, and the documented guard on
516
- // files.conflicted must not pass over it. Rewriting it
517
- // bumped the mtime for nothing.
518
- const unresolved = 'unresolved' === mergeres.outcome
519
- const conflict = mergeres.conflict || unresolved
520
-
521
- if (unresolved) {
522
- if (this.chmodUnchanged(path, mode)) {
523
- why.push('chmod-0')
524
- }
525
- }
526
- else {
527
- this.saveFile(path, Buffer.from(diffcontent, 'latin1'),
528
- modeopts(), whence + meta.action)
573
+ const diffcontent = mergeres.content
574
+
575
+ // A file still holding an earlier merge's markers is left
576
+ // byte-for-byte untouched, and reported conflicted: it
577
+ // still carries markers, and the documented guard on
578
+ // files.conflicted must not pass over it. Rewriting it
579
+ // bumped the mtime for nothing.
580
+ const unresolved = 'unresolved' === mergeres.outcome
581
+ const conflict = mergeres.conflict || unresolved
582
+
583
+ if (conflict && failOnConflict) {
584
+ why.push('conflict-fail-0')
585
+ this.failures.push({ path, reason: unresolved ? 'unresolved' : 'conflict' })
586
+ }
587
+ else if (unresolved) {
588
+ if (this.chmodUnchanged(path, mode)) {
589
+ why.push('chmod-0')
529
590
  }
591
+ }
592
+ else {
593
+ this.saveFile(path, Buffer.from(diffcontent, 'latin1'),
594
+ modeopts(), whence + meta.action)
595
+ landed = true
596
+ }
530
597
 
531
- // this.files.merged.push(path)
532
- this.filelog('merged', path)
598
+ // this.files.merged.push(path)
599
+ this.filelog('merged', path)
533
600
 
534
- if (conflict) {
535
- // this.files.conflicted.push(path)
536
- this.filelog('conflicted', path)
537
- }
601
+ if (conflict) {
602
+ // this.files.conflicted.push(path)
603
+ this.filelog('conflicted', path)
604
+ }
538
605
 
539
- whenify(meta, this.now())
540
- meta.actions.push(meta.action)
541
- meta.conflict = conflict
606
+ whenify(meta, this.now())
607
+ meta.actions.push(meta.action)
608
+ meta.conflict = conflict
542
609
 
543
- this.decision(CN + FN + wstr, meta, why, path)
610
+ this.decision(CN + FN + wstr, meta, why, path)
611
+ }
612
+ else {
613
+ // Nothing to merge against, so the file cannot be told apart
614
+ // from an edit. It is listed rather than passed over: `write`
615
+ // overwrites it and no `write` leaves it, as before, and
616
+ // `conflict: 'fail'` leaves it and fails the run.
617
+ why.push('merge-nobase-0')
618
+ this.filelog('unmerged', path)
619
+
620
+ if (failOnConflict) {
621
+ why.push('conflict-fail-0')
622
+ write = false
623
+ this.failures.push({ path, reason: 'nobase' })
544
624
  }
545
625
  }
546
626
  }
@@ -555,6 +635,7 @@ class FileHandler {
555
635
  }
556
636
  // this.files.unchanged.push(path)
557
637
  this.filelog('unchanged', path)
638
+ landed = true
558
639
  }
559
640
  }
560
641
  }
@@ -594,6 +675,7 @@ class FileHandler {
594
675
  meta.actions.push(meta.action)
595
676
  whenify(meta, this.now())
596
677
  final = true
678
+ landed = true
597
679
  }
598
680
  else if (0 === meta.actions.length) {
599
681
  why.push('skip-0')
@@ -609,12 +691,17 @@ class FileHandler {
609
691
  if (withinFolder && (Path.basename(path) !== this.metafile())) {
610
692
  why.push('within-0')
611
693
 
612
- const dfolder = this.duplicateFolder()
613
- const dpath = fwd(Path.join(dfolder, rpath))
694
+ if (landed) {
695
+ const dfolder = this.duplicateFolder()
696
+ const dpath = fwd(Path.join(dfolder, rpath))
614
697
 
615
- if (!this.control.dryrun) {
616
- this.ensureDir(fwd(Path.dirname(dpath)))
617
- this.writeFileAtomic(dpath, newContentSource, { flush: true })
698
+ if (!this.control.dryrun) {
699
+ this.ensureDir(fwd(Path.dirname(dpath)))
700
+ this.writeFileAtomic(dpath, newContentSource, { flush: true })
701
+ }
702
+ }
703
+ else {
704
+ why.push('hold-0')
618
705
  }
619
706
  }
620
707
  }
@@ -625,10 +712,48 @@ class FileHandler {
625
712
  this.decision(CN + FN + wstr, meta, why, path)
626
713
  }
627
714
 
715
+ // The generates that landed, newest last, so a later merge can tell
716
+ // an earlier one put back from an edit. Recorded after every decision
717
+ // record, so the audit never carries them.
718
+ if (existing.merge) {
719
+ const prior = this.priorFingerprints(rpath)
720
+ if (landed) {
721
+ const fp = fingerprint(newContentSource)
722
+ meta.fingerprints = [...prior.filter((f: string) => f !== fp), fp]
723
+ .slice(-FINGERPRINT_HISTORY)
724
+ }
725
+ else {
726
+ meta.fingerprints = prior
727
+ }
728
+ }
729
+
628
730
  this.addmeta(path, meta)
629
731
  }
630
732
 
631
733
 
734
+ // The fingerprints the previous run recorded for a file. A hand-edited
735
+ // log can hold anything there, and anything but a fingerprint is
736
+ // dropped.
737
+ private priorFingerprints(rpath: string): string[] {
738
+ const prior = this.prevmeta(rpath)?.fingerprints
739
+ return Array.isArray(prior) ?
740
+ prior.filter((f: any) => 'string' === typeof f && /^[0-9a-f]{16}$/.test(f)) :
741
+ []
742
+ }
743
+
744
+
745
+ // The merge result for a file that is one of its own earlier generates:
746
+ // the new generate, taken whole, as for an untouched file.
747
+ private earlier(generated: string | Buffer, why: string[]): {
748
+ content: string,
749
+ conflict: boolean,
750
+ outcome: string,
751
+ } {
752
+ why.push('merge-earlier-0')
753
+ return { content: latin1(generated), conflict: false, outcome: 'clean' }
754
+ }
755
+
756
+
632
757
  // Push a decision record as a SNAPSHOT. The record used to share the live
633
758
  // `why` and `meta.actions` arrays, so an early record (a preserve) later
634
759
  // reported the whole save's actions and breadcrumbs.
package/src/diff.ts CHANGED
@@ -100,45 +100,62 @@ const MARK_END = '>>>>>>> '
100
100
  const LABEL_GENERATED = 'GENERATED'
101
101
  const LABEL_EXISTING = 'EXISTING'
102
102
 
103
- // The end-of-conflict marker for the EXISTING side. A file still holding
104
- // this has an unresolved merge in it.
105
- const UNRESOLVED_MARK = MARK_END + LABEL_EXISTING + ':'
103
+ // The default marker lines, as prefixes, so they match whatever timestamp
104
+ // follows. Both sides open and close a block somewhere: a merge conflict
105
+ // opens on EXISTING and closes on GENERATED, a conflict written before
106
+ // 0.41 the other way round, and a diff block opens and closes on one side.
107
+ const DEFAULT_MARKS = [
108
+ MARK_START + LABEL_EXISTING + ':',
109
+ MARK_END + LABEL_EXISTING + ':',
110
+ MARK_START + LABEL_GENERATED + ':',
111
+ MARK_END + LABEL_GENERATED + ':',
112
+ ]
106
113
 
107
114
  // The largest epoch-ms magnitude a Date holds.
108
115
  const MAX_DATE_MS = 8.64e15
109
116
 
110
117
 
118
+ // Whether `mark` starts a line of `text`. Every marker is written at the
119
+ // start of a line, so a marker-like run in the middle of one is content.
120
+ function hasLine(text: string, mark: string): boolean {
121
+ return text.startsWith(mark) || text.includes('\n' + mark)
122
+ }
123
+
124
+
111
125
  // Whether text still holds an unresolved conflict from an earlier merge.
112
- // Keyed on the closing EXISTING marker alone: a half-resolved file, where
113
- // the opening marker was removed but the closing one was not, must still
114
- // count as unresolved rather than being re-merged.
115
126
  //
116
- // The `existingLabel` argument matters when the caller supplied a custom
117
- // one: `writeConflict` emits `>>>>>>> ` + whatever label was configured, so
118
- // a file conflicted under `labels.existing = 'E'` does not contain the
119
- // default sentinel at all. Without it, merge's unresolved guard did not
120
- // fire and the markers nested one level deeper on every run — exactly what
121
- // the guard exists to prevent.
127
+ // Any one marker line is enough. A half-resolved file, where one marker
128
+ // was removed and another was not, must still count as unresolved rather
129
+ // than being re-merged, whichever marker the user removed.
122
130
  //
123
- // Detection only holds when the SAME existing label is used across runs. A
124
- // caller that changes its labels between generations cannot expect an older
125
- // conflict to be recognised, and the default is unchanged for callers that
126
- // never set one.
127
- function hasConflicts(text: string, existingLabel?: string): boolean {
128
- // The default sentinel is a PREFIX (`>>>>>>> EXISTING:`), so it matches
129
- // whatever timestamp follows. Checking the fully-formatted label instead
130
- // would only match a conflict written in the same millisecond.
131
- if (text.includes(UNRESOLVED_MARK)) {
131
+ // `labels` matters when the caller supplied custom ones: `writeConflict`
132
+ // emits whatever label was configured, so a file conflicted under
133
+ // `labels.existing = 'E'` does not contain the default sentinel at all.
134
+ // Without them, merge's unresolved guard did not fire and the markers
135
+ // nested one level deeper on every run — exactly what the guard exists to
136
+ // prevent. A string is the existing label alone, the form this took when
137
+ // only the existing label closed a conflict.
138
+ //
139
+ // Detection only holds when the SAME labels are used across runs. A caller
140
+ // that changes its labels between generations cannot expect an older
141
+ // conflict to be recognised; the defaults are always recognised.
142
+ function hasConflicts(text: string, labels?: string | DiffLabels): boolean {
143
+ if (DEFAULT_MARKS.some((mark) => hasLine(text, mark))) {
132
144
  return true
133
145
  }
146
+
147
+ const custom = 'string' === typeof labels ? [labels] :
148
+ [labels?.existing, labels?.generated]
149
+
134
150
  // Match the COMPLETE emitted marker, including its newline. A bare
135
151
  // substring check on `MARK_END + label` treats a custom label as a
136
152
  // prefix, so label `E` matched an ordinary line `>>>>>>> Example` and
137
153
  // merge returned `unresolved` — silently suppressing a legitimate
138
154
  // regeneration over a marker the engine never emitted. writeConflict
139
155
  // always appends '\n', so the newline is safe to require.
140
- return null != existingLabel && '' !== existingLabel &&
141
- text.includes(MARK_END + existingLabel + '\n')
156
+ return custom.some((label) => null != label && '' !== label &&
157
+ (hasLine(text, MARK_START + label + '\n') ||
158
+ hasLine(text, MARK_END + label + '\n')))
142
159
  }
143
160
 
144
161
 
@@ -376,25 +393,29 @@ function endsWithNewline(parts: string[]): boolean {
376
393
  }
377
394
 
378
395
 
396
+ // The existing side first, as git writes a conflict: the file on disk is
397
+ // the current change and the generate is the incoming one, so an editor's
398
+ // "accept current" keeps the user's lines (issue #79). The two-way diff
399
+ // already put the existing side first.
379
400
  function writeConflict(
380
401
  out: string[],
381
402
  generated: string[],
382
403
  existing: string[],
383
404
  labels: DiffLabels,
384
405
  ): void {
385
- out.push(MARK_START + labels.generated + '\n')
386
- pushAll(out, generated)
406
+ out.push(MARK_START + labels.existing + '\n')
407
+ pushAll(out, existing)
387
408
  if (!endsWithNewline(out)) {
388
409
  out.push('\n')
389
410
  }
390
411
 
391
412
  out.push(MARK_MID)
392
- pushAll(out, existing)
413
+ pushAll(out, generated)
393
414
  if (!endsWithNewline(out)) {
394
415
  out.push('\n')
395
416
  }
396
417
 
397
- out.push(MARK_END + labels.existing + '\n')
418
+ out.push(MARK_END + labels.generated + '\n')
398
419
  }
399
420
 
400
421
 
@@ -431,9 +452,9 @@ function merge(
431
452
 
432
453
  // Never merge into an unresolved merge — that stacks conflict markers
433
454
  // inside conflict markers and is unreadable. Leave it for the user.
434
- // Pass the EXPLICIT custom label, not the formatted one: the formatted
455
+ // Pass the EXPLICIT custom labels, not the formatted ones: a formatted
435
456
  // default carries a timestamp and would never match an older conflict.
436
- if (hasConflicts(existing, spec?.labels?.existing)) {
457
+ if (hasConflicts(existing, spec?.labels)) {
437
458
  return { content: existing, conflict: false, outcome: 'unresolved' }
438
459
  }
439
460
 
package/src/jostraca.ts CHANGED
@@ -8,7 +8,7 @@ import * as Fs from 'node:fs'
8
8
 
9
9
  import { AsyncLocalStorage } from 'node:async_hooks'
10
10
 
11
- import { Shape, Skip, One, Child, Empty, Nullable, Fault, Check } from 'shape'
11
+ import { Shape, Skip, One, Child, Empty, Nullable, Fault, Check, Default, Exact } from 'shape'
12
12
 
13
13
  import { memfs as MemFs } from './util/memfs'
14
14
 
@@ -214,6 +214,9 @@ const ExistingShape = Shape({
214
214
  present: false, // Present the new file using .new. name annotation.
215
215
  diff: false, // Annotated 2-way diff of new generate and existing file.
216
216
  merge: false, // Annotated 3-way merge of new generate and existing file.
217
+ // What a merge that cannot land does: write the conflict markers into
218
+ // the file, or leave the file as it is and fail the run.
219
+ conflict: Default('markers', Exact('markers', 'fail')),
217
220
  },
218
221
  bin: {
219
222
  write: true, // Overwrite existing files (unless present=true).
@@ -321,6 +324,31 @@ const CONTROL_DEFAULTS = {
321
324
  }
322
325
 
323
326
 
327
+ // The words a merge failure gives each reason.
328
+ const MERGE_FAILURE_REASON: Record<string, string> = {
329
+ conflict: 'conflict',
330
+ unresolved: 'unresolved conflict markers',
331
+ nobase: 'no baseline',
332
+ }
333
+
334
+
335
+ // What `existing.txt.conflict: 'fail'` raises. Every file named was left
336
+ // as it was, with its baseline where it was, so the same run fails the
337
+ // same way until the conflicts are dealt with. `conflicts` lists them and
338
+ // `result` is the run's own result. Go's MergeConflictError carries the
339
+ // same text.
340
+ function mergeConflictError(
341
+ failures: { path: string, reason: string }[],
342
+ result: JostracaResult
343
+ ): Error {
344
+ const err: any = new Error('jostraca: 3-way merge produced conflicts, left unchanged: ' +
345
+ failures.map((f) => f.path + ' (' + MERGE_FAILURE_REASON[f.reason] + ')').join(', '))
346
+ err.conflicts = failures.map((f) => ({ ...f }))
347
+ err.result = result
348
+ return err
349
+ }
350
+
351
+
324
352
  function Jostraca(gopts_in?: JostracaOptions | {}) {
325
353
  // Global options are shared by calls to `generate`.
326
354
  const gOpts = OptionsShape(gopts_in || {})
@@ -487,6 +515,13 @@ function Jostraca(gopts_in?: JostracaOptions | {}) {
487
515
  log.debug({ point: 'jostraca-warning', dlogentry, note: String(dlogentry) })
488
516
  }
489
517
  }
518
+
519
+ // Raised once the build is done, so every other file is already
520
+ // written and the meta log records the run.
521
+ if (0 < buildctx.fh.failures.length) {
522
+ throw mergeConflictError(buildctx.fh.failures, res)
523
+ }
524
+
490
525
  return res
491
526
  })
492
527
  }
package/src/types.ts CHANGED
@@ -76,6 +76,7 @@ type JostracaResult = {
76
76
  merged: string[],
77
77
  conflicted: string[],
78
78
  unchanged: string[],
79
+ unmerged: string[],
79
80
  }
80
81
  audit: () => Audit[]
81
82