@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/backend.d.ts CHANGED
@@ -18,7 +18,8 @@
18
18
  * `cliBackend` and `AsyncGit` are stable.
19
19
  */
20
20
  import { type AsyncCommandRunner, type CommandResult } from '@osdlc/command-seam';
21
- import { type AddOptions, type AheadBehind, type CheckoutOptions, type CloneOptions, type CommitOptions, type ConfigGetOptions, type ConfigSetOptions, type ConflictSide, type DiffEntry, type DiffNameOnlyOptions, type DiffStatOptions, type DiffNameStatusOptions, type DiffTextOptions, type DiffTreeOptions, type FetchOptions, type ForEachRefOptions, type ForceLease, type GrepOptions, type InitOptions, type LogOptions, type IgnoreMatch, type LsFilesOptions, type LsRemoteOptions, type LsTreeOptions, type MergeOptions, type MergeOutcome, type MergeTreeOptions, type MergeTreeOutcome, type NumstatEntry, type PushPorcelainOptions, type PushReport, type RebaseOptions, type RebaseOutcome, type RemoteGetUrlOptions, type RemoteRef, type CleanOptions, type DiffCheckOptions, type DiffCheckResult, type StatusEntry, type StatusPorcelainOptions, type TreeEntry, type TaggedFile, type UnmergedEntry, type Worktree, type WorktreeMoveOptions } from './verbs.ts';
21
+ import { type GitVersion } from './git-version.ts';
22
+ import { type AddOptions, type AheadBehind, type CherryEntry, type CommitTreeOptions, type CheckoutOptions, type CloneOptions, type CommitOptions, type ConfigGetOptions, type ConfigSetOptions, type ConflictSide, type DiffEntry, type DiffNameOnlyOptions, type DiffStatOptions, type DiffNameStatusOptions, type DiffTextOptions, type DiffTreeOptions, type FetchOptions, type ForEachRefOptions, type GcOptions, type GrepOptions, type InitOptions, type LogOptions, type IgnoreMatch, type LsFilesOptions, type LsRemoteOptions, type LsTreeOptions, type MergeOptions, type MergeOutcome, type MergeTreeOptions, type MergeTreeOutcome, type NumstatEntry, type PushOptions, type PushPorcelainOptions, type PushReport, type RemoteSetBranchesOptions, type RemoteSetHeadOptions, type WorktreeAddOptions, type RebaseOptions, type RebaseOutcome, type RemoteGetUrlOptions, type RemoteRef, type CleanOptions, type DiffCheckOptions, type DiffCheckResult, type StatusEntry, type StatusPorcelainOptions, type TreeEntry, type TaggedFile, type UnmergedEntry, type Worktree, type WorktreeMoveOptions } from './verbs.ts';
22
23
  /** Per-call concerns that are not part of the operation itself. */
23
24
  export interface GitCallOptions {
24
25
  /**
@@ -57,9 +58,15 @@ export interface GitCallOptions {
57
58
  * @experimental Each new verb adds a kind, in a minor release.
58
59
  */
59
60
  export type GitRequest = {
61
+ kind: 'version';
62
+ } | {
60
63
  kind: 'showAtRev';
61
64
  rev: string;
62
65
  relPath: string;
66
+ } | {
67
+ kind: 'showAtRevChecked';
68
+ rev: string;
69
+ relPath: string;
63
70
  } | {
64
71
  kind: 'revParse';
65
72
  args: string[];
@@ -125,7 +132,14 @@ export type GitRequest = {
125
132
  kind: 'aheadBehind';
126
133
  base: string;
127
134
  tip: string;
135
+ } | {
136
+ kind: 'cherry';
137
+ upstream: string;
138
+ head?: string | undefined;
128
139
  } | ({
140
+ kind: 'commitTree';
141
+ tree: string;
142
+ } & CommitTreeOptions) | ({
129
143
  kind: 'lsFiles';
130
144
  } & LsFilesOptions) | {
131
145
  kind: 'lsFilesTagged';
@@ -138,7 +152,9 @@ export type GitRequest = {
138
152
  kind: 'diffStat';
139
153
  } & DiffStatOptions) | ({
140
154
  kind: 'diffCheck';
141
- } & DiffCheckOptions) | ({
155
+ } & DiffCheckOptions) | {
156
+ kind: 'hasStagedChanges';
157
+ } | ({
142
158
  kind: 'diffNameStatus';
143
159
  } & DiffNameStatusOptions) | ({
144
160
  kind: 'log';
@@ -183,12 +199,11 @@ export type GitRequest = {
183
199
  kind: 'clone';
184
200
  url: string;
185
201
  dest?: string | undefined;
186
- } & CloneOptions) | {
202
+ } & CloneOptions) | ({
187
203
  kind: 'push';
188
204
  remote: string;
189
205
  refspec: string;
190
- forceWithLease?: boolean | ForceLease | undefined;
191
- } | ({
206
+ } & PushOptions) | ({
192
207
  kind: 'pushPorcelain';
193
208
  remote: string;
194
209
  refspec: string | string[];
@@ -205,13 +220,10 @@ export type GitRequest = {
205
220
  kind: 'deleteRef';
206
221
  ref: string;
207
222
  expected: string;
208
- } | {
223
+ } | ({
209
224
  kind: 'worktreeAdd';
210
225
  path: string;
211
- branch?: string | undefined;
212
- startPoint?: string | undefined;
213
- detach?: boolean | undefined;
214
- } | {
226
+ } & WorktreeAddOptions) | {
215
227
  kind: 'worktreeRemove';
216
228
  path: string;
217
229
  force?: boolean | undefined;
@@ -264,7 +276,16 @@ export type GitRequest = {
264
276
  kind: 'remoteAdd';
265
277
  name: string;
266
278
  url: string;
267
- } | {
279
+ } | ({
280
+ kind: 'remoteSetHead';
281
+ remote: string;
282
+ } & RemoteSetHeadOptions) | ({
283
+ kind: 'remoteSetBranches';
284
+ remote: string;
285
+ branches: string[];
286
+ } & RemoteSetBranchesOptions) | ({
287
+ kind: 'gc';
288
+ } & GcOptions) | {
268
289
  kind: 'raw';
269
290
  argv: string[];
270
291
  input?: string | undefined;
@@ -276,7 +297,9 @@ export type GitRequest = {
276
297
  * @experimental It grows with {@link GitRequest}.
277
298
  */
278
299
  export interface GitResults {
300
+ version: GitVersion;
279
301
  showAtRev: string | null;
302
+ showAtRevChecked: string;
280
303
  revParse: string | null;
281
304
  resolveRef: string | null;
282
305
  headRef: string | null;
@@ -300,12 +323,15 @@ export interface GitResults {
300
323
  checkIgnoreVerbose: IgnoreMatch[];
301
324
  isAncestor: boolean;
302
325
  aheadBehind: AheadBehind;
326
+ cherry: CherryEntry[];
327
+ commitTree: string;
303
328
  lsFiles: string[];
304
329
  lsFilesTagged: TaggedFile[];
305
330
  forEachRef: string[];
306
331
  diffNameOnly: string[];
307
332
  diffStat: string;
308
333
  diffCheck: DiffCheckResult;
334
+ hasStagedChanges: boolean;
309
335
  diffNameStatus: DiffEntry[];
310
336
  log: string;
311
337
  lsTree: TreeEntry[];
@@ -346,6 +372,9 @@ export interface GitResults {
346
372
  remoteGetUrls: string[];
347
373
  remoteHead: string | null;
348
374
  remoteAdd: void;
375
+ remoteSetHead: void;
376
+ remoteSetBranches: void;
377
+ gc: void;
349
378
  raw: CommandResult;
350
379
  }
351
380
  /** Every request kind, as a union of string literals. */
@@ -359,6 +388,12 @@ export type GitRequestKind = GitRequest['kind'];
359
388
  * config key. It rejects with the classified failure — or whatever error the backend
360
389
  * considers equivalent — when git failed rather than answered.
361
390
  *
391
+ * The git version check is `cliBackend`'s: it probes `git --version` before
392
+ * a request whose verb needs a newer git (see `features.ts`) and rejects with
393
+ * the `unsupported-git` failure when the git is too old. Another backend has
394
+ * no git version to check, so it gets every request and decides itself. It
395
+ * may reject one with that same failure, or with {@link UnsupportedRequest}.
396
+ *
362
397
  * @experimental New request kinds land in minor releases. Use
363
398
  * {@link partialBackend} rather than an exhaustive switch.
364
399
  */
@@ -393,6 +428,13 @@ export declare function cliBackend(opts?: {
393
428
  * `GIT_SSH_COMMAND` once, instead of passing it on every call.
394
429
  */
395
430
  env?: Record<string, string> | undefined;
431
+ /**
432
+ * Pins the git version: `'2.55.0'`, or a whole `git version …` line.
433
+ * Version-gated requests then use it and never run `git --version`, and
434
+ * the `version` request returns it. Set it with a fake runner. An
435
+ * unparsable value throws a `RangeError` here.
436
+ */
437
+ gitVersion?: string | undefined;
396
438
  }): GitBackend;
397
439
  /**
398
440
  * Wrap a partial implementation: any request kind the object does not handle
package/dist/backend.js CHANGED
@@ -18,6 +18,8 @@
18
18
  * `cliBackend` and `AsyncGit` are stable.
19
19
  */
20
20
  import { spawnRunnerAsync, } from '@osdlc/command-seam';
21
+ import { versionedVerb } from "./features.js";
22
+ import { pinnedGitVersion, probeGitVersionAsync, versionVerb, } from "./git-version.js";
21
23
  import * as v from "./verbs.js";
22
24
  import { gate, mergeEnv, repoPrefix, } from "./verbs.js";
23
25
  /** Thrown by a backend asked for an operation it cannot perform. */
@@ -32,8 +34,12 @@ export class UnsupportedRequest extends Error {
32
34
  /** Translate a request into the CLI verb that performs it. */
33
35
  function toVerb(request) {
34
36
  switch (request.kind) {
37
+ case 'version':
38
+ return versionVerb();
35
39
  case 'showAtRev':
36
40
  return v.showAtRev(request.rev, request.relPath);
41
+ case 'showAtRevChecked':
42
+ return v.showAtRevChecked(request.rev, request.relPath);
37
43
  case 'revParse':
38
44
  return v.revParse(...request.args);
39
45
  case 'resolveRef':
@@ -76,6 +82,10 @@ function toVerb(request) {
76
82
  return v.isAncestor(request.a, request.b);
77
83
  case 'aheadBehind':
78
84
  return v.aheadBehind(request.base, request.tip);
85
+ case 'cherry':
86
+ return v.cherry(request.upstream, request.head);
87
+ case 'commitTree':
88
+ return v.commitTree(request.tree, request);
79
89
  case 'checkIgnore':
80
90
  return v.checkIgnore(request.relPaths);
81
91
  case 'checkIgnoreVerbose':
@@ -92,6 +102,8 @@ function toVerb(request) {
92
102
  return v.diffStat(request);
93
103
  case 'diffCheck':
94
104
  return v.diffCheck(request);
105
+ case 'hasStagedChanges':
106
+ return v.hasStagedChanges();
95
107
  case 'diffNameStatus':
96
108
  return v.diffNameStatus(request);
97
109
  case 'log':
@@ -123,9 +135,7 @@ function toVerb(request) {
123
135
  case 'clone':
124
136
  return v.clone(request.url, request.dest, request);
125
137
  case 'push':
126
- return v.push(request.remote, request.refspec, {
127
- forceWithLease: request.forceWithLease,
128
- });
138
+ return v.push(request.remote, request.refspec, request);
129
139
  case 'pushPorcelain':
130
140
  return v.pushPorcelain(request.remote, request.refspec, request);
131
141
  case 'resetHard':
@@ -174,6 +184,12 @@ function toVerb(request) {
174
184
  return v.remoteHead(request.remote);
175
185
  case 'remoteAdd':
176
186
  return v.remoteAdd(request.name, request.url);
187
+ case 'remoteSetHead':
188
+ return v.remoteSetHead(request.remote, request);
189
+ case 'remoteSetBranches':
190
+ return v.remoteSetBranches(request.remote, request.branches, request);
191
+ case 'gc':
192
+ return v.gc(request);
177
193
  case 'raw': {
178
194
  const verb = {
179
195
  argv: request.argv,
@@ -197,10 +213,21 @@ function toVerb(request) {
197
213
  */
198
214
  export function cliBackend(opts = {}) {
199
215
  const runner = opts.runner ?? spawnRunnerAsync('git', { absolutePathOnly: true });
216
+ const pinned = pinnedGitVersion(opts.gitVersion);
217
+ // A failed probe names `report`: the gated verb's argv, so a missing git
218
+ // reads `git worktree: …` rather than `git --version: …`.
219
+ const versionOf = (run, report) => pinned === undefined
220
+ ? probeGitVersionAsync(runner, {
221
+ env: run.env,
222
+ timeoutMs: run.timeoutMs,
223
+ signal: run.signal,
224
+ report,
225
+ })
226
+ : Promise.resolve(pinned);
200
227
  const prefix = repoPrefix(opts.gitDir, opts.workTree);
201
228
  return {
202
229
  async execute(cwd, request, callOpts = {}) {
203
- const verb = toVerb(request);
230
+ const gated = toVerb(request);
204
231
  const runOpts = { cwd };
205
232
  if (callOpts.timeoutMs !== undefined)
206
233
  runOpts.timeoutMs = callOpts.timeoutMs;
@@ -212,6 +239,17 @@ export function cliBackend(opts = {}) {
212
239
  const env = mergeEnv(opts.env, callOpts.env);
213
240
  if (env !== undefined)
214
241
  runOpts.env = env;
242
+ const req = request;
243
+ // `version` is answered from the per-runner cache, like the probe a
244
+ // version-gated verb makes.
245
+ if (req.kind === 'version') {
246
+ return (await versionOf(runOpts, ['--version']));
247
+ }
248
+ // A verb that needs a git feature runs in the form this git supports,
249
+ // or rejects as `unsupported-git`. Others never probe.
250
+ const verb = gated.needs === undefined
251
+ ? gated
252
+ : versionedVerb(gated, await versionOf(runOpts, [...prefix, ...gated.argv]), prefix);
215
253
  if (verb.input !== undefined)
216
254
  runOpts.input = verb.input;
217
255
  // The verb's own entries (the C locale) win over the backend's and the call's.
@@ -222,10 +260,9 @@ export function cliBackend(opts = {}) {
222
260
  // Unchecked `raw` is the only request that skips `gate`: it returns the
223
261
  // result at any exit code. Everything else goes through the same `gate`
224
262
  // the sync client uses.
225
- const req = request;
226
- const gated = req.kind !== 'raw' || req.checked === true;
263
+ const checked = req.kind !== 'raw' || req.checked === true;
227
264
  // The prefixed argv is what ran, so it is what a `CommandFailed` reports.
228
- const value = gated ? gate(verb, result, argv) : verb.parse(result, argv);
265
+ const value = checked ? gate(verb, result, argv) : verb.parse(result, argv);
229
266
  // `GitResults` restates the verb table's return types for callers. The
230
267
  // two are kept in step by hand, and this cast is where they meet.
231
268
  return value;
@@ -61,7 +61,8 @@ export interface CheckoutScan {
61
61
  * an owner directory per GitHub org, or a folder per client, and the
62
62
  * checkouts sit a level or two inside. Stopping at a checkout keeps this
63
63
  * fast: a repository's own `node_modules`, `vendor` and nested worktrees are
64
- * below it, so they are never entered.
64
+ * below it, so they are never entered. A search root that is a checkout
65
+ * answers itself alone.
65
66
  *
66
67
  * Two limits keep a bad search root from turning into a walk of the whole
67
68
  * disk: children whose names start with a dot are skipped, and nothing
@@ -54,7 +54,8 @@ export const DEFAULT_WARN_AFTER = 10_000;
54
54
  * an owner directory per GitHub org, or a folder per client, and the
55
55
  * checkouts sit a level or two inside. Stopping at a checkout keeps this
56
56
  * fast: a repository's own `node_modules`, `vendor` and nested worktrees are
57
- * below it, so they are never entered.
57
+ * below it, so they are never entered. A search root that is a checkout
58
+ * answers itself alone.
58
59
  *
59
60
  * Two limits keep a bad search root from turning into a walk of the whole
60
61
  * disk: children whose names start with a dot are skipped, and nothing
@@ -116,6 +117,11 @@ export function scanForCheckouts(dir, opts = {}) {
116
117
  visit(candidate, depth + 1);
117
118
  }
118
119
  };
120
+ // A search root that is itself a checkout is the answer, and the same rule
121
+ // holds: nothing inside it is entered.
122
+ if (existsSync(resolve(root, '.git'))) {
123
+ return { checkouts: [root], directoriesScanned: 0, depthLimited: 0 };
124
+ }
119
125
  visit(root, 1);
120
126
  return { checkouts: checkouts.sort(), directoriesScanned, depthLimited };
121
127
  }
package/dist/client.d.ts CHANGED
@@ -20,5 +20,7 @@ export { parseRemoteUrl, type RemoteCoordinate } from './remote-url.ts';
20
20
  export { cliBackend, partialBackend, UnsupportedRequest, type GitBackend, type GitCallOptions, type GitRequest, type GitRequestKind, type GitResults, } from './backend.ts';
21
21
  export { classifyGitFailure, describeGitFailure, type GitFailure, type GitFailureKind, } from './failure.ts';
22
22
  export { type Soft, type TriedAsync, type TriedSync } from './outcome.ts';
23
- export { forceWithLeaseArg, parseRefRows, REF_FORMAT, type AddOptions, type AheadBehind, type CheckoutOptions, type CleanOptions, type CloneOptions, type CommitFlags, type CommitOptions, type ConfigGetOptions, type ConfigScope, type ConfigSetOptions, type ConflictSide, type DiffCheckOptions, type DiffCheckResult, type DiffEntry, type DiffNameOnlyOptions, type DiffNameStatusOptions, type DiffStatOptions, type DiffTextOptions, type DiffTreeOptions, type FetchOptions, type ForEachRefOptions, type ForceLease, type GrepOptions, type InitOptions, type IntegrationOutcome, type LogOptions, type IgnoreMatch, type LsFilesOptions, type LsRemoteOptions, type LsTreeOptions, type MergeOptions, type MergeOutcome, type MergeTreeOptions, type MergeTreeOutcome, type NumstatEntry, type PushFlag, type PushPorcelainOptions, type PushRefResult, type PushRejection, type PushReport, type RebaseOptions, type RebaseOutcome, type RemoteGetUrlOptions, type RemoteRef, type StatusEntry, type StatusPorcelainOptions, type TaggedFile, type TreeEntry, type UnmergedEntry, type Worktree, type WorktreeMoveOptions, } from './verbs.ts';
23
+ export { GIT_FEATURES, GIT_FLOOR, gitSupports, type GitFeature, type GitFeatureSpec, type GitRelease, type UnsupportedGit, } from './features.ts';
24
+ export { compareGitVersions, parseGitVersion, type GitVersion } from './git-version.ts';
25
+ export { forceWithLeaseArg, parseRefRows, REF_FORMAT, type AddOptions, type AheadBehind, type CherryEntry, type CommitTreeOptions, type CheckoutOptions, type CleanOptions, type CloneOptions, type CommitFlags, type CommitOptions, type ConfigGetOptions, type ConfigScope, type ConfigSetOptions, type ConflictSide, type DiffCheckOptions, type DiffCheckResult, type DiffEntry, type DiffNameOnlyOptions, type DiffNameStatusOptions, type DiffStatOptions, type DiffTextOptions, type DiffTreeOptions, type FetchOptions, type ForEachRefOptions, type ForceLease, type GcOptions, type GrepOptions, type InitOptions, type IntegrationOutcome, type LogOptions, type IgnoreMatch, type LsFilesOptions, type LsRemoteOptions, type LsTreeOptions, type MergeOptions, type MergeOutcome, type MergeTreeOptions, type MergeTreeOutcome, type NumstatEntry, type PushFlag, type PushOptions, type PushPorcelainOptions, type PushRefResult, type PushRejection, type PushReport, type RebaseOptions, type RebaseOutcome, type RemoteGetUrlOptions, type RemoteRef, type RemoteSetBranchesOptions, type RemoteSetHeadOptions, type StatusEntry, type StatusPorcelainOptions, type TaggedFile, type TreeEntry, type UnmergedEntry, type Worktree, type WorktreeAddOptions, type WorktreeMoveOptions, } from './verbs.ts';
24
26
  export { asAsync, CommandFailed, runChecked, runCheckedAsync, spawnRunner, spawnRunnerAsync, type AsyncCommandRunner, type AsyncCommandRunOptions, type CommandResult, type CommandRunner, type CommandRunOptions, } from '@osdlc/command-seam';
package/dist/client.js CHANGED
@@ -20,6 +20,8 @@ export { parseRemoteUrl } from "./remote-url.js";
20
20
  export { cliBackend, partialBackend, UnsupportedRequest, } from "./backend.js";
21
21
  export { classifyGitFailure, describeGitFailure, } from "./failure.js";
22
22
  export {} from "./outcome.js";
23
+ export { GIT_FEATURES, GIT_FLOOR, gitSupports, } from "./features.js";
24
+ export { compareGitVersions, parseGitVersion } from "./git-version.js";
23
25
  export { forceWithLeaseArg, parseRefRows, REF_FORMAT, } from "./verbs.js";
24
26
  // The command-seam exports are re-exported so a caller wiring a runner or catching
25
27
  // a failure needs one import, not two. `@osdlc/command-seam` is the package
package/dist/failure.d.ts CHANGED
@@ -7,9 +7,14 @@
7
7
  * non-English locale git translates its messages. Those keep command-seam's
8
8
  * kind, so an unrecognised failure is still an `exit` with git's first stderr
9
9
  * line as its message, never a wrong git kind.
10
+ *
11
+ * One kind is not read from git's output: `unsupported-git`, which a client
12
+ * reports before it runs a verb the local git is too old for (see
13
+ * `./features.ts`).
10
14
  */
11
15
  import { type CommandFailed, type CommandFailureKind } from '@osdlc/command-seam';
12
16
  import { type Failure } from '@osdlc/result';
17
+ import type { UnsupportedGit } from './features.ts';
13
18
  /**
14
19
  * Why a git call failed:
15
20
  *
@@ -29,9 +34,13 @@ import { type Failure } from '@osdlc/result';
29
34
  * - `tls`: the TLS handshake failed ("unable to access … SSL certificate
30
35
  * problem"). The host was reached, so this is not `remote-unreachable`, and
31
36
  * retrying will not help until the clock, the CA certificates or the remote's
32
- * certificate is fixed.
37
+ * certificate is fixed;
38
+ * - `unsupported-git`: the local git is older than the verb needs ("merge-tree
39
+ * --write-tree needs git 2.38 or later; found 2.34.1"), or older than the
40
+ * 2.34 floor. The verb did not run. `unsupported` says which feature, and
41
+ * which git it needs and found.
33
42
  */
34
- export type GitFailureKind = CommandFailureKind | 'not-a-repo' | 'no-remote' | 'remote-unreachable' | 'not-authenticated' | 'not-found' | 'tls';
43
+ export type GitFailureKind = CommandFailureKind | 'not-a-repo' | 'no-remote' | 'remote-unreachable' | 'not-authenticated' | 'not-found' | 'tls' | 'unsupported-git';
35
44
  /** A failed git call. `message` is one line for a person; `detail` is git's own output. */
36
45
  export interface GitFailure extends Failure<GitFailureKind> {
37
46
  /** The binary that ran (`git`), when the runner reports one. */
@@ -42,8 +51,13 @@ export interface GitFailure extends Failure<GitFailureKind> {
42
51
  exitCode: number | null;
43
52
  /** The signal that ended git, when the runner knows it. */
44
53
  signal?: NodeJS.Signals | null | undefined;
45
- /** The `CommandFailed` this was classified from. */
46
- cause: CommandFailed;
54
+ /**
55
+ * The `CommandFailed` this was classified from. Absent for
56
+ * `unsupported-git`, where the verb never ran.
57
+ */
58
+ cause?: CommandFailed | undefined;
59
+ /** For `unsupported-git`: the feature, the git it needs, and the git found. */
60
+ unsupported?: UnsupportedGit | undefined;
47
61
  }
48
62
  /** The git failure for a failed `git` run. */
49
63
  export declare function classifyGitFailure(failed: CommandFailed): GitFailure;
package/dist/failure.js CHANGED
@@ -7,21 +7,20 @@
7
7
  * non-English locale git translates its messages. Those keep command-seam's
8
8
  * kind, so an unrecognised failure is still an `exit` with git's first stderr
9
9
  * line as its message, never a wrong git kind.
10
+ *
11
+ * One kind is not read from git's output: `unsupported-git`, which a client
12
+ * reports before it runs a verb the local git is too old for (see
13
+ * `./features.ts`).
10
14
  */
11
- import { classifyFailure, isCommandFailed, } from '@osdlc/command-seam';
15
+ import { classifyFailed, isCommandFailed, } from '@osdlc/command-seam';
12
16
  import { describe, FailureError, isFailure } from '@osdlc/result';
13
17
  const INSTALL_HINT = 'Install git from https://git-scm.com.';
14
18
  /** The git failure for a failed `git` run. */
15
19
  export function classifyGitFailure(failed) {
16
20
  // The client's runner may not name its binary; this is git either way, so
17
21
  // the messages say `git` rather than "The command".
18
- const f = failed.binary === undefined
19
- ? (classifyFailure(failed.result, { binary: 'git', argv: failed.argv }) ?? failed.failure)
20
- : failed.failure;
21
- const base = { ...f, cause: failed };
22
- if (f.kind === 'not-installed')
23
- return { ...base, hint: INSTALL_HINT };
24
- if (f.kind !== 'exit')
22
+ const base = classifyFailed(failed, { binary: 'git', installHint: INSTALL_HINT });
23
+ if (base.kind !== 'exit')
25
24
  return base;
26
25
  // git's own words: stderr, then the stdout some commands explain with.
27
26
  const text = `${failed.result.stderr}\n${failed.result.stdout}`;
@@ -45,18 +44,12 @@ export function classifyGitFailure(failed) {
45
44
  hint: 'List the remotes with `git remote -v`.',
46
45
  };
47
46
  }
48
- if (/Authentication failed|Permission denied \(publickey\)|could not read (Username|Password)/i.test(text)) {
49
- return {
50
- ...base,
51
- kind: 'not-authenticated',
52
- message: 'The remote refused the credentials.',
53
- hint: 'Check that you are signed in to the host, or that your SSH key is added.',
54
- };
55
- }
56
47
  // "unable to access" with a status means the host answered. A refusal or a
57
48
  // wrong URL will not clear up by retrying, so it must not read as unreachable.
58
49
  const status = /unable to access[^\n]*returned error: (\d{3})/.exec(text)?.[1];
59
- if (status === '401' || status === '403') {
50
+ if (/Authentication failed|Permission denied \(publickey\)|could not read (Username|Password)/i.test(text) ||
51
+ status === '401' ||
52
+ status === '403') {
60
53
  return {
61
54
  ...base,
62
55
  kind: 'not-authenticated',
@@ -0,0 +1,91 @@
1
+ /**
2
+ * The git feature table: the one place that says which git release each
3
+ * version-dependent feature needs, and which of them have a fallback.
4
+ *
5
+ * A verb that uses one of these features names it in `needs` (see `GitVerb`
6
+ * in `./verbs.ts`). Before such a verb runs, the client probes the git version
7
+ * once per runner (`./git-version.ts`) and calls {@link versionedVerb}, which
8
+ * picks the verb's own form, its `fallback` form, or throws the
9
+ * `unsupported-git` failure. No other module compares versions.
10
+ *
11
+ * Every feature at or below {@link GIT_FLOOR} is used without a check. Below
12
+ * the floor itself, every version-gated verb fails as `unsupported-git` with
13
+ * the feature `typed-git`, and no fallback is tried.
14
+ *
15
+ * The README's "Git versions" table is checked against this one by
16
+ * `tests/features.test.ts`.
17
+ */
18
+ import { type GitFailure } from './failure.ts';
19
+ import { type GitVersion } from './git-version.ts';
20
+ import type { GitVerb } from './verbs.ts';
21
+ /** A `major.minor.patch` release, without the `text` a probed version carries. */
22
+ export type GitRelease = Pick<GitVersion, 'major' | 'minor' | 'patch'>;
23
+ /**
24
+ * The oldest git this package supports: 2.34, the git of Ubuntu 22.04 LTS.
25
+ * Every flag typed-git passes unconditionally is at least this old.
26
+ */
27
+ export declare const GIT_FLOOR: GitRelease;
28
+ /** One row of {@link GIT_FEATURES}. */
29
+ export interface GitFeatureSpec {
30
+ /** The first git release with the feature. */
31
+ readonly minimum: GitRelease;
32
+ /** The methods that use it. */
33
+ readonly usedBy: readonly string[];
34
+ /**
35
+ * What runs instead on an older git, for a feature whose older form gives
36
+ * the same answer. A feature without one fails as `unsupported-git`.
37
+ */
38
+ readonly fallback?: string;
39
+ }
40
+ /**
41
+ * Every git feature newer than {@link GIT_FLOOR} that typed-git uses.
42
+ *
43
+ * - `merge-tree --write-tree`: git 2.38 ("git merge-tree" learned a new mode
44
+ * that computes the merge tree, RelNotes/2.38.0). `--name-only` and `-z`
45
+ * arrived with it.
46
+ * - `merge-tree --merge-base`: git 2.40 ("merge-tree" learns a new
47
+ * `--merge-base` option, RelNotes/2.40.0).
48
+ * - `worktree list -z`: git 2.36 (NUL-terminated `--porcelain` output, because
49
+ * paths and lock reasons with unsafe bytes were not C-quoted correctly,
50
+ * RelNotes/2.36.0).
51
+ */
52
+ export declare const GIT_FEATURES: Readonly<{
53
+ 'merge-tree --write-tree': {
54
+ minimum: GitRelease;
55
+ usedBy: string[];
56
+ };
57
+ 'merge-tree --merge-base': {
58
+ minimum: GitRelease;
59
+ usedBy: string[];
60
+ };
61
+ 'worktree list -z': {
62
+ minimum: GitRelease;
63
+ usedBy: string[];
64
+ fallback: string;
65
+ };
66
+ }>;
67
+ /** A feature in {@link GIT_FEATURES}. */
68
+ export type GitFeature = keyof typeof GIT_FEATURES;
69
+ /** What an `unsupported-git` failure carries: the feature, the git it needs, and the git found. */
70
+ export interface UnsupportedGit {
71
+ /** The feature, or `typed-git` when the git is older than {@link GIT_FLOOR}. */
72
+ feature: GitFeature | 'typed-git';
73
+ /** The first git release that has it. */
74
+ needs: GitRelease;
75
+ /** The git that was found. */
76
+ have: GitVersion;
77
+ }
78
+ /** True when `have` has `feature`. */
79
+ export declare function gitSupports(feature: GitFeature, have: GitRelease): boolean;
80
+ /** The classified failure for a git too old for `feature`. */
81
+ export declare function unsupportedGitFailure(feature: GitFeature | 'typed-git', needs: GitRelease, have: GitVersion, argv: string[]): GitFailure;
82
+ /**
83
+ * The form of `verb` that the git at `have` can run: the verb itself when it
84
+ * needs nothing or `have` has its feature, its `fallback` when the feature has
85
+ * one in the table, otherwise a thrown `unsupported-git` failure. Below
86
+ * {@link GIT_FLOOR} a gated verb always throws.
87
+ *
88
+ * `prefix` is the repository binding the client adds, so the failure names
89
+ * the argv that would have run.
90
+ */
91
+ export declare function versionedVerb<T>(verb: GitVerb<T>, have: GitVersion, prefix?: readonly string[]): GitVerb<T>;
@@ -0,0 +1,98 @@
1
+ /**
2
+ * The git feature table: the one place that says which git release each
3
+ * version-dependent feature needs, and which of them have a fallback.
4
+ *
5
+ * A verb that uses one of these features names it in `needs` (see `GitVerb`
6
+ * in `./verbs.ts`). Before such a verb runs, the client probes the git version
7
+ * once per runner (`./git-version.ts`) and calls {@link versionedVerb}, which
8
+ * picks the verb's own form, its `fallback` form, or throws the
9
+ * `unsupported-git` failure. No other module compares versions.
10
+ *
11
+ * Every feature at or below {@link GIT_FLOOR} is used without a check. Below
12
+ * the floor itself, every version-gated verb fails as `unsupported-git` with
13
+ * the feature `typed-git`, and no fallback is tried.
14
+ *
15
+ * The README's "Git versions" table is checked against this one by
16
+ * `tests/features.test.ts`.
17
+ */
18
+ import { FailureError } from '@osdlc/result';
19
+ import { describeGitFailure } from "./failure.js";
20
+ import { compareGitVersions, formatGitVersion } from "./git-version.js";
21
+ /**
22
+ * The oldest git this package supports: 2.34, the git of Ubuntu 22.04 LTS.
23
+ * Every flag typed-git passes unconditionally is at least this old.
24
+ */
25
+ export const GIT_FLOOR = Object.freeze({ major: 2, minor: 34, patch: 0 });
26
+ const release = (major, minor) => Object.freeze({ major, minor, patch: 0 });
27
+ /**
28
+ * Every git feature newer than {@link GIT_FLOOR} that typed-git uses.
29
+ *
30
+ * - `merge-tree --write-tree`: git 2.38 ("git merge-tree" learned a new mode
31
+ * that computes the merge tree, RelNotes/2.38.0). `--name-only` and `-z`
32
+ * arrived with it.
33
+ * - `merge-tree --merge-base`: git 2.40 ("merge-tree" learns a new
34
+ * `--merge-base` option, RelNotes/2.40.0).
35
+ * - `worktree list -z`: git 2.36 (NUL-terminated `--porcelain` output, because
36
+ * paths and lock reasons with unsafe bytes were not C-quoted correctly,
37
+ * RelNotes/2.36.0).
38
+ */
39
+ export const GIT_FEATURES = Object.freeze({
40
+ 'merge-tree --write-tree': { minimum: release(2, 38), usedBy: ['mergeTree'] },
41
+ 'merge-tree --merge-base': { minimum: release(2, 40), usedBy: ['mergeTree({ mergeBase })'] },
42
+ 'worktree list -z': {
43
+ minimum: release(2, 36),
44
+ usedBy: ['worktrees'],
45
+ fallback: 'newline-split `worktree list --porcelain`: a path with a newline breaks it, and a lock reason comes back C-quoted',
46
+ },
47
+ });
48
+ /** True when `have` has `feature`. */
49
+ export function gitSupports(feature, have) {
50
+ return compareGitVersions(have, GIT_FEATURES[feature].minimum) >= 0;
51
+ }
52
+ /** `2.38` — a feature minimum as the README and the messages write it. */
53
+ function formatMinimum(v) {
54
+ return v.patch === 0 ? `${v.major}.${v.minor}` : formatGitVersion(v);
55
+ }
56
+ /** The classified failure for a git too old for `feature`. */
57
+ export function unsupportedGitFailure(feature, needs, have, argv) {
58
+ const want = formatMinimum(needs);
59
+ return {
60
+ kind: 'unsupported-git',
61
+ message: `${feature} needs git ${want} or later; found ${formatGitVersion(have)}.`,
62
+ hint: `Upgrade git to ${want} or later from https://git-scm.com.`,
63
+ detail: `git version ${have.text}`,
64
+ argv,
65
+ exitCode: null,
66
+ unsupported: { feature, needs, have },
67
+ };
68
+ }
69
+ function throwUnsupported(feature, needs, have, argv) {
70
+ const failure = unsupportedGitFailure(feature, needs, have, argv);
71
+ const thrown = new FailureError(failure);
72
+ thrown.message = describeGitFailure(failure);
73
+ throw thrown;
74
+ }
75
+ /**
76
+ * The form of `verb` that the git at `have` can run: the verb itself when it
77
+ * needs nothing or `have` has its feature, its `fallback` when the feature has
78
+ * one in the table, otherwise a thrown `unsupported-git` failure. Below
79
+ * {@link GIT_FLOOR} a gated verb always throws.
80
+ *
81
+ * `prefix` is the repository binding the client adds, so the failure names
82
+ * the argv that would have run.
83
+ */
84
+ export function versionedVerb(verb, have, prefix = []) {
85
+ const feature = verb.needs;
86
+ if (feature === undefined)
87
+ return verb;
88
+ const argv = [...prefix, ...verb.argv];
89
+ if (compareGitVersions(have, GIT_FLOOR) < 0)
90
+ throwUnsupported('typed-git', GIT_FLOOR, have, argv);
91
+ if (gitSupports(feature, have))
92
+ return verb;
93
+ const spec = GIT_FEATURES[feature];
94
+ if (spec.fallback !== undefined && verb.fallback !== undefined) {
95
+ return versionedVerb(verb.fallback, have, prefix);
96
+ }
97
+ return throwUnsupported(feature, spec.minimum, have, argv);
98
+ }
package/dist/git-url.d.ts CHANGED
@@ -18,6 +18,33 @@ export interface GitHostInfo {
18
18
  export declare function parseGitUrl(ref: string): GitHostInfo | null;
19
19
  /** `ref` as a scp-style SSH clone URL (`git@github.com:owner/repo.git`), or null. */
20
20
  export declare function gitSshUrl(ref: string): string | null;
21
+ /** The repository a git remote names, and the host it is on. */
22
+ export interface RemoteRepo {
23
+ /** The host, lower-cased and without a port: `github.com`, `git.example.com`. */
24
+ host: string;
25
+ owner: string;
26
+ repo: string;
27
+ }
28
+ /**
29
+ * `{host, owner, repo}` from a git remote reference, or null when it names no
30
+ * project (a local path, a single path segment).
31
+ *
32
+ * It reads a known host (GitHub, GitLab, Bitbucket, Sourcehut) with
33
+ * {@link parseGitUrl} first, so `owner/repo` and `github:owner/repo`
34
+ * shorthand read as GitHub and a GitLab nested group stays whole in `owner`
35
+ * (`group/sub`). Any other clone URL, such as a GitHub Enterprise or a
36
+ * self-hosted Forgejo remote, is read host-agnostically by `parseRemoteUrl`:
37
+ * `host/owner/repo`, scp-style or `scheme://`, where `owner` is the second to
38
+ * last path segment.
39
+ *
40
+ * `ssh.github.com` (GitHub's SSH over port 443) and `www.github.com` read as
41
+ * `github.com`.
42
+ *
43
+ * Use it to read a remote into the repository it names. To decide which forge
44
+ * a host is, compare `host`, never the URL text: `notgithub.com` is not
45
+ * GitHub, and neither is a path that mentions `github.com`.
46
+ */
47
+ export declare function parseRemoteRepo(url: string): RemoteRepo | null;
21
48
  export type CloneProtocol = 'https' | 'ssh';
22
49
  /**
23
50
  * A hosted repository named by any reference a person might paste: one