@osdlc/typed-git 0.8.2 → 0.11.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.
package/dist/verbs.js CHANGED
@@ -12,7 +12,7 @@
12
12
  *
13
13
  * `GitVerb` and `gate` are internal: the package entries do not export them.
14
14
  */
15
- import { CommandFailed } from '@osdlc/command-seam';
15
+ import { CommandFailed, notAnOption, runFailed } from '@osdlc/command-seam';
16
16
  import { gitFailureError } from "./failure.js";
17
17
  /**
18
18
  * Turn one git result into a value or a thrown failure: a `FailureError`
@@ -40,9 +40,7 @@ import { gitFailureError } from "./failure.js";
40
40
  */
41
41
  export function gate(verb, result, argv) {
42
42
  try {
43
- if (result.neverExited ||
44
- result.outputIncomplete ||
45
- (result.exitCode !== 0 && !verb.absent.includes(result.exitCode))) {
43
+ if (runFailed(result, (r) => verb.absent.includes(r.exitCode))) {
46
44
  throw new CommandFailed(argv ?? verb.argv, result);
47
45
  }
48
46
  return verb.parse(result, argv ?? verb.argv);
@@ -164,10 +162,8 @@ const NONE = [];
164
162
  * `-`, and `@{-1}` for the previous branch.
165
163
  */
166
164
  function positional(verb, param, value) {
167
- if (value.startsWith('-')) {
168
- throw new TypeError(`typed-git: ${verb}: ${param} must not start with "-" (got ${JSON.stringify(value)})`);
169
- }
170
- return value;
165
+ const message = (v) => `typed-git: ${verb}: ${param} must not start with "-" (got ${JSON.stringify(v)})`;
166
+ return notAnOption(value, (v) => new TypeError(message(v)));
171
167
  }
172
168
  /**
173
169
  * A config key for the `config` reads: {@link positional}, plus a section and
@@ -217,6 +213,24 @@ export function showAtRev(rev, relPath) {
217
213
  parse: (r) => (r.exitCode === 0 ? r.stdout : null),
218
214
  };
219
215
  }
216
+ /**
217
+ * A file's content at a rev (`git show <rev>:<relPath>`), and a throw when it
218
+ * is not there.
219
+ *
220
+ * The same argv as {@link showAtRev}, with `absent: []`. Use it when a missing
221
+ * file is an error: a path that is not in that tree throws the classified
222
+ * failure, as does a rev that does not resolve or a broken repository, rather
223
+ * than all three reading as `null`. It has no `soft` form, because it has no
224
+ * absence value.
225
+ */
226
+ export function showAtRevChecked(rev, relPath) {
227
+ return {
228
+ argv: ['show', `${positional('showAtRevChecked', 'rev', rev)}:${relPath}`],
229
+ absent: NONE,
230
+ // Verbatim, as for showAtRev.
231
+ parse: (r) => r.stdout,
232
+ };
233
+ }
220
234
  /**
221
235
  * Trimmed `git rev-parse <args>` output, for a query no other verb covers.
222
236
  *
@@ -374,69 +388,91 @@ export function statusEntries() {
374
388
  if (f.length < 4)
375
389
  continue;
376
390
  const x = f[0];
377
- out.push({ x, y: f[1], path: f.slice(3) });
378
- if (x === 'R' || x === 'C')
391
+ const y = f[1];
392
+ out.push({ x, y, path: f.slice(3) });
393
+ // A rename or copy in either column (a worktree rename of an
394
+ // intent-to-add file sets Y) is followed by its source field.
395
+ if (x === 'R' || x === 'C' || y === 'R' || y === 'C')
379
396
  i++;
380
397
  }
381
398
  return out;
382
399
  },
383
400
  };
384
401
  }
385
- /** Local branch shortnames matching `pattern` (all when omitted). */
402
+ /**
403
+ * Local branch names matching `pattern` (all when omitted). The name is
404
+ * `refs/heads/` stripped, never `%(refname:short)`, which answers
405
+ * `heads/<name>` when a tag shares the name.
406
+ */
386
407
  export function branches(pattern) {
387
- const argv = ['branch', '--list', '--format=%(refname:short)'];
408
+ const argv = ['branch', '--list', '--format=%(refname:lstrip=2)'];
388
409
  if (pattern !== undefined)
389
410
  argv.push(positional('branches', 'pattern', pattern));
390
411
  return { argv, absent: NONE, parse: trimmedLines };
391
412
  }
392
- /** `git worktree list --porcelain`, parsed. Throws outside a repository. */
413
+ /**
414
+ * `git worktree list --porcelain -z`, parsed. Throws outside a repository.
415
+ *
416
+ * `-z` (git 2.36) ends each line with NUL, so a path or lock reason holding
417
+ * a newline reads as written. On an older git the client runs the
418
+ * newline-split form instead (the `worktree list -z` row in `./features.ts`),
419
+ * which breaks on such a path and C-quotes such a reason.
420
+ */
393
421
  export function worktrees() {
394
422
  return {
395
- argv: ['worktree', 'list', '--porcelain'],
423
+ argv: ['worktree', 'list', '--porcelain', '-z'],
396
424
  absent: NONE,
397
- parse(r) {
398
- const out = [];
399
- let cur = null;
400
- const flush = () => {
401
- if (cur?.path !== undefined) {
402
- out.push({
403
- path: cur.path,
404
- head: cur.head ?? null,
405
- branch: cur.branch ?? null,
406
- detached: cur.detached ?? false,
407
- bare: cur.bare ?? false,
408
- locked: cur.locked ?? false,
409
- lockReason: cur.lockReason ?? null,
410
- });
411
- }
412
- };
413
- for (const line of r.stdout.split('\n')) {
414
- if (line.startsWith('worktree ')) {
415
- flush();
416
- cur = { path: line.slice('worktree '.length) };
417
- }
418
- else if (cur !== null && line.startsWith('HEAD ')) {
419
- cur.head = line.slice('HEAD '.length);
420
- }
421
- else if (cur !== null && line.startsWith('branch ')) {
422
- cur.branch = line.slice('branch '.length).replace(/^refs\/heads\//, '');
423
- }
424
- else if (cur !== null && line === 'detached') {
425
- cur.detached = true;
426
- }
427
- else if (cur !== null && line === 'bare') {
428
- cur.bare = true;
429
- }
430
- else if (cur !== null && (line === 'locked' || line.startsWith('locked '))) {
431
- cur.locked = true;
432
- cur.lockReason = line.slice('locked '.length) || null;
433
- }
434
- }
435
- flush();
436
- return out;
425
+ parse: (r) => worktreeRecords(r.stdout.split('\x00')),
426
+ needs: 'worktree list -z',
427
+ fallback: {
428
+ argv: ['worktree', 'list', '--porcelain'],
429
+ absent: NONE,
430
+ parse: (r) => worktreeRecords(r.stdout.split('\n')),
437
431
  },
438
432
  };
439
433
  }
434
+ /** `worktree list --porcelain` lines, however they were split, into rows. */
435
+ function worktreeRecords(lines) {
436
+ const out = [];
437
+ let cur = null;
438
+ const flush = () => {
439
+ if (cur?.path !== undefined) {
440
+ out.push({
441
+ path: cur.path,
442
+ head: cur.head ?? null,
443
+ branch: cur.branch ?? null,
444
+ detached: cur.detached ?? false,
445
+ bare: cur.bare ?? false,
446
+ locked: cur.locked ?? false,
447
+ lockReason: cur.lockReason ?? null,
448
+ });
449
+ }
450
+ };
451
+ for (const line of lines) {
452
+ if (line.startsWith('worktree ')) {
453
+ flush();
454
+ cur = { path: line.slice('worktree '.length) };
455
+ }
456
+ else if (cur !== null && line.startsWith('HEAD ')) {
457
+ cur.head = line.slice('HEAD '.length);
458
+ }
459
+ else if (cur !== null && line.startsWith('branch ')) {
460
+ cur.branch = line.slice('branch '.length).replace(/^refs\/heads\//, '');
461
+ }
462
+ else if (cur !== null && line === 'detached') {
463
+ cur.detached = true;
464
+ }
465
+ else if (cur !== null && line === 'bare') {
466
+ cur.bare = true;
467
+ }
468
+ else if (cur !== null && (line === 'locked' || line.startsWith('locked '))) {
469
+ cur.locked = true;
470
+ cur.lockReason = line.slice('locked '.length) || null;
471
+ }
472
+ }
473
+ flush();
474
+ return out;
475
+ }
440
476
  /**
441
477
  * Merge base of two revs, or null when the two histories are unrelated
442
478
  * (exit 1). A rev that does not resolve exits 128 and throws.
@@ -754,6 +790,26 @@ export function diffCheck(opts = {}) {
754
790
  parse: (r) => ({ ok: r.exitCode === 0, output: r.stdout }),
755
791
  };
756
792
  }
793
+ /**
794
+ * True iff the index differs from HEAD (`git diff --cached --quiet`): is there
795
+ * anything staged to commit?
796
+ *
797
+ * A boolean carried by the exit code. `absent: [1]` — measured: nothing staged
798
+ * → 0 (`false`); something staged → 1 (`true`). Anything else throws. Outside
799
+ * a repository `git diff` exits 129, so a non-repository is a failure, not
800
+ * "nothing staged".
801
+ *
802
+ * On an unborn HEAD (no commits yet) git compares the index against the empty
803
+ * tree: an empty index is `false`, and any staged file is `true`. It does not
804
+ * throw.
805
+ */
806
+ export function hasStagedChanges() {
807
+ return {
808
+ argv: ['diff', '--cached', '--quiet'],
809
+ absent: [1],
810
+ parse: (r) => r.exitCode === 1,
811
+ };
812
+ }
757
813
  /**
758
814
  * Changed paths with their status (`git diff --name-status -z`).
759
815
  *
@@ -1033,6 +1089,61 @@ export function isAncestor(a, b) {
1033
1089
  parse: (r) => r.exitCode === 0,
1034
1090
  };
1035
1091
  }
1092
+ /**
1093
+ * Which commits `head` has that `upstream` lacks, and for each one whether
1094
+ * `upstream` carries a commit with the same patch id (`git cherry`). Oldest
1095
+ * first. Merge commits are not listed.
1096
+ *
1097
+ * `absent: []`: an unresolvable rev exits 128 and throws. Empty output is a
1098
+ * real answer (`head` has nothing `upstream` lacks), so a caller that needs at
1099
+ * least one commit checks the length. A line that is not `+ <sha>` or
1100
+ * `- <sha>` throws rather than reading as an entry or being skipped.
1101
+ */
1102
+ export function cherry(upstream, head) {
1103
+ const argv = ['cherry', positional('cherry', 'upstream', upstream)];
1104
+ if (head !== undefined)
1105
+ argv.push(positional('cherry', 'head', head));
1106
+ return {
1107
+ argv,
1108
+ absent: NONE,
1109
+ parse(r, ranArgv) {
1110
+ const out = [];
1111
+ for (const line of r.stdout.split('\n')) {
1112
+ if (line === '')
1113
+ continue;
1114
+ const m = /^([+-]) ([0-9a-f]{40}|[0-9a-f]{64})$/.exec(line);
1115
+ if (m === null)
1116
+ throw new CommandFailed(ranArgv, r);
1117
+ out.push({ sha: m[2], equivalent: m[1] === '-' });
1118
+ }
1119
+ return out;
1120
+ },
1121
+ };
1122
+ }
1123
+ /**
1124
+ * Write a commit object for `tree` and print its sha (`git commit-tree`).
1125
+ *
1126
+ * It writes an object and no ref, and leaves the index and working tree alone.
1127
+ * git needs an author and committer identity; without one it exits 128 and
1128
+ * this throws. `absent: []`, and a reply that is not a sha throws.
1129
+ */
1130
+ export function commitTree(tree, opts) {
1131
+ const argv = ['commit-tree', positional('commitTree', 'tree', tree)];
1132
+ for (const parent of opts.parents ?? []) {
1133
+ argv.push('-p', positional('commitTree', 'parent', parent));
1134
+ }
1135
+ argv.push('-m', opts.message);
1136
+ return {
1137
+ argv,
1138
+ absent: NONE,
1139
+ parse(r, ranArgv) {
1140
+ const sha = r.stdout.trim();
1141
+ if (!/^([0-9a-f]{40}|[0-9a-f]{64})$/.test(sha))
1142
+ throw new CommandFailed(ranArgv, r);
1143
+ return sha;
1144
+ },
1145
+ };
1146
+ }
1036
1147
  /**
1037
1148
  * How far `tip` has diverged from `base`
1038
1149
  * (`git rev-list --left-right --count base...tip`).
@@ -1180,6 +1291,10 @@ export function add(paths, opts = {}) {
1180
1291
  * which holds both streams, not stderr alone.
1181
1292
  */
1182
1293
  export function commit(opts) {
1294
+ if (opts.paths !== undefined && opts.paths.length === 0) {
1295
+ throw new TypeError('typed-git: commit: paths is empty; omit it to commit everything staged');
1296
+ }
1297
+ const pathArgs = opts.paths === undefined ? [] : ['--', ...opts.paths];
1183
1298
  const argv = ['commit'];
1184
1299
  if (opts.allowEmpty)
1185
1300
  argv.push('--allow-empty');
@@ -1190,7 +1305,7 @@ export function commit(opts) {
1190
1305
  if (opts.signoff)
1191
1306
  argv.push('--signoff');
1192
1307
  if (opts.messageStdin !== undefined) {
1193
- argv.push('-F', '-');
1308
+ argv.push('-F', '-', ...pathArgs);
1194
1309
  return { argv, input: opts.messageStdin, absent: NONE, parse: nothing };
1195
1310
  }
1196
1311
  if (opts.messageFile !== undefined)
@@ -1200,6 +1315,7 @@ export function commit(opts) {
1200
1315
  if (opts.body !== undefined)
1201
1316
  argv.push('-m', opts.body);
1202
1317
  }
1318
+ argv.push(...pathArgs);
1203
1319
  return { argv, absent: NONE, parse: nothing };
1204
1320
  }
1205
1321
  /** `git config <key> <value>` — the write twin of {@link configGet}. */
@@ -1288,7 +1404,7 @@ export function forceWithLeaseArg(lease) {
1288
1404
  return `--force-with-lease=${lease.ref}:${lease.expect ?? ''}`;
1289
1405
  }
1290
1406
  /**
1291
- * Push a refspec.
1407
+ * Push a refspec, or delete it on the remote with `{ delete: true }`.
1292
1408
  *
1293
1409
  * `forceWithLease` takes a {@link ForceLease} for the pinned form, or `true`
1294
1410
  * for the bare `--force-with-lease`. `true` is the unsafe form. It trusts
@@ -1297,7 +1413,10 @@ export function forceWithLeaseArg(lease) {
1297
1413
  * is overwritten. Pin the lease whenever the expected remote sha is known.
1298
1414
  */
1299
1415
  export function push(remote, refspec, opts = {}) {
1300
- const argv = ['push', ...forceWithLeaseArgs('push', opts.forceWithLease)];
1416
+ const argv = ['push'];
1417
+ if (opts.delete)
1418
+ argv.push('--delete');
1419
+ argv.push(...forceWithLeaseArgs('push', opts.forceWithLease));
1301
1420
  argv.push(positional('push', 'remote', remote), positional('push', 'refspec', refspec));
1302
1421
  return { argv, absent: NONE, parse: nothing };
1303
1422
  }
@@ -1489,13 +1608,19 @@ export function deleteRef(ref, opts) {
1489
1608
  parse: nothing,
1490
1609
  };
1491
1610
  }
1492
- /** `git worktree add [--detach] [-b branch] <path> [startPoint]`. */
1611
+ /** `git worktree add [--detach] [-b|-B branch] <path> [startPoint]`. */
1493
1612
  export function worktreeAdd(path, opts = {}) {
1613
+ if (opts.resetBranch && opts.branch === undefined) {
1614
+ throw new TypeError('typed-git: worktreeAdd: resetBranch needs a branch');
1615
+ }
1494
1616
  const argv = ['worktree', 'add'];
1495
1617
  if (opts.detach)
1496
1618
  argv.push('--detach');
1497
- if (opts.branch !== undefined)
1498
- argv.push('-b', opts.branch);
1619
+ // Guarded: worktree add hands the name to a child `git branch`, which would
1620
+ // read a leading-dash value such as `-M` as an option.
1621
+ if (opts.branch !== undefined) {
1622
+ argv.push(opts.resetBranch ? '-B' : '-b', positional('worktreeAdd', 'branch', opts.branch));
1623
+ }
1499
1624
  argv.push(positional('worktreeAdd', 'path', path));
1500
1625
  const start = optionalPositional('worktreeAdd', 'startPoint', opts.startPoint);
1501
1626
  if (start !== undefined)
@@ -1543,6 +1668,68 @@ export function remoteAdd(name, url) {
1543
1668
  parse: nothing,
1544
1669
  };
1545
1670
  }
1671
+ /**
1672
+ * `git remote set-head <remote> <branch> | --auto | --delete`: set or remove
1673
+ * the local `refs/remotes/<remote>/HEAD`, which {@link symbolicRef} reads.
1674
+ *
1675
+ * `absent: []`. A `branch` with no remote-tracking ref `<remote>/<branch>`
1676
+ * exits 1 and throws, and so does an unknown remote with `branch`. `auto` asks
1677
+ * the remote, so an unknown or unreachable one exits 128, and a remote whose
1678
+ * HEAD cannot be determined exits 1; both throw. `delete`
1679
+ * when the ref is not set exits 0 (measured on git 2.34).
1680
+ */
1681
+ export function remoteSetHead(remote, opts) {
1682
+ const given = [opts.branch !== undefined, opts.auto === true, opts.delete === true];
1683
+ if (given.filter(Boolean).length !== 1) {
1684
+ throw new TypeError('typed-git: remoteSetHead: pass exactly one of branch, auto, delete');
1685
+ }
1686
+ const argv = ['remote', 'set-head', positional('remoteSetHead', 'remote', remote)];
1687
+ if (opts.branch !== undefined)
1688
+ argv.push(positional('remoteSetHead', 'branch', opts.branch));
1689
+ else if (opts.auto)
1690
+ argv.push('--auto');
1691
+ else
1692
+ argv.push('--delete');
1693
+ return { argv, absent: NONE, parse: nothing };
1694
+ }
1695
+ /**
1696
+ * `git remote set-branches [--add] <remote> <branch…>`: the branches a fetch
1697
+ * of `remote` tracks, written as its `remote.<remote>.fetch` refspecs. A
1698
+ * branch may be a glob.
1699
+ *
1700
+ * An empty `branches` throws a `TypeError`: git would exit 0 and clear every
1701
+ * fetch refspec of the remote. `absent: []` — an unknown remote exits 2 and throws.
1702
+ */
1703
+ export function remoteSetBranches(remote, branches, opts = {}) {
1704
+ if (branches.length === 0) {
1705
+ throw new TypeError('typed-git: remoteSetBranches: branches is empty');
1706
+ }
1707
+ const argv = ['remote', 'set-branches'];
1708
+ if (opts.add)
1709
+ argv.push('--add');
1710
+ argv.push(positional('remoteSetBranches', 'remote', remote));
1711
+ for (const b of branches)
1712
+ argv.push(positional('remoteSetBranches', 'branch', b));
1713
+ return { argv, absent: NONE, parse: nothing };
1714
+ }
1715
+ /** `git gc [--auto] [--aggressive] [--prune=<date> | --no-prune] [--quiet]`. */
1716
+ export function gc(opts = {}) {
1717
+ const argv = ['gc'];
1718
+ if (opts.auto)
1719
+ argv.push('--auto');
1720
+ if (opts.aggressive)
1721
+ argv.push('--aggressive');
1722
+ if (opts.prune === false)
1723
+ argv.push('--no-prune');
1724
+ else if (opts.prune !== undefined) {
1725
+ if (opts.prune === '')
1726
+ throw new TypeError('typed-git: gc: prune is empty');
1727
+ argv.push(`--prune=${opts.prune}`);
1728
+ }
1729
+ if (opts.quiet)
1730
+ argv.push('--quiet');
1731
+ return { argv, absent: NONE, parse: nothing };
1732
+ }
1546
1733
  /** `CONFLICT (content|add/add|…): Merge conflict in <path>` */
1547
1734
  const CONFLICT_MERGE_IN = /^CONFLICT \([^)]*\): Merge conflict in (.+)$/;
1548
1735
  /** `CONFLICT (modify/delete): <path> deleted in <x> and modified in <y>…` */
@@ -1694,6 +1881,10 @@ export function rebaseContinue() {
1694
1881
  *
1695
1882
  * A name git cannot merge exits 1 exactly like a conflict, so again only
1696
1883
  * stdout separates an answer from a refusal.
1884
+ *
1885
+ * Needs git 2.38, or 2.40 with `mergeBase` (the `merge-tree` rows in
1886
+ * `./features.ts`). There is no fallback: on an older git it throws the
1887
+ * `unsupported-git` failure without running git.
1697
1888
  */
1698
1889
  export function mergeTree(ours, theirs, opts = {}) {
1699
1890
  const argv = ['merge-tree', '--write-tree', '--name-only', '-z'];
@@ -1702,6 +1893,7 @@ export function mergeTree(ours, theirs, opts = {}) {
1702
1893
  argv.push(positional('mergeTree', 'ours', ours), positional('mergeTree', 'theirs', theirs));
1703
1894
  return {
1704
1895
  argv,
1896
+ needs: opts.mergeBase === undefined ? 'merge-tree --write-tree' : 'merge-tree --merge-base',
1705
1897
  absent: [1],
1706
1898
  parse(r, ranArgv) {
1707
1899
  const fields = r.stdout.split('\x00');
@@ -1788,8 +1980,9 @@ export function checkout(ref, opts = {}) {
1788
1980
  const argv = ['checkout'];
1789
1981
  if (opts.force)
1790
1982
  argv.push('--force');
1791
- if (opts.branch !== undefined)
1792
- argv.push(opts.resetBranch ? '-B' : '-b', opts.branch);
1983
+ if (opts.branch !== undefined) {
1984
+ argv.push(opts.resetBranch ? '-B' : '-b', positional('checkout', 'branch', opts.branch));
1985
+ }
1793
1986
  argv.push(positional('checkout', 'ref', ref));
1794
1987
  return { argv, absent: NONE, parse: nothing };
1795
1988
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@osdlc/typed-git",
3
- "version": "0.8.2",
3
+ "version": "0.11.1",
4
4
  "description": "A typed git client for TypeScript, sync and awaitable. Each verb declares what absence means for it; every other failure throws. git.try.* inspects, raw() bypasses — over an injectable backend that drives the git CLI or any other implementation.",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "author": "sksizer",
@@ -52,7 +52,7 @@
52
52
  ],
53
53
  "dependencies": {
54
54
  "hosted-git-info": "^10.1.1",
55
- "@osdlc/command-seam": "^0.12.1",
55
+ "@osdlc/command-seam": "^0.14.0",
56
56
  "@osdlc/result": "^0.1.0"
57
57
  },
58
58
  "devDependencies": {