@git.zone/cli 7.2.3 → 7.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,350 @@
1
+ import * as plugins from "./mod.plugins.js";
2
+
3
+ /**
4
+ * Identifies a failed release command for its diagnostic. Git and pnpm
5
+ * commands are named without their arguments, because arguments can hold
6
+ * destinations and file paths the message has no use for.
7
+ */
8
+ export interface IReleaseCommandFailureContext {
9
+ /**
10
+ * Command name, for example `git ls-remote`, or a configured project
11
+ * command. It passes the same redaction and bounding as output.
12
+ */
13
+ command: string;
14
+ /** Timeout the command ran under, named when Smartshell's timeout fired. */
15
+ timeoutMs?: number;
16
+ /**
17
+ * Output whose tail the diagnostic quotes. Git reports errors on stderr;
18
+ * pnpm and project commands report many of theirs on stdout.
19
+ */
20
+ output?: "stderr" | "combined";
21
+ }
22
+
23
+ /** Longest output tail a diagnostic quotes, in characters. */
24
+ export const releaseCommandOutputTailLength = 500;
25
+
26
+ const ansiEscapePattern =
27
+ /\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)|[@-Z\\-_])/g;
28
+
29
+ /** A credential form in command output and the replacement that hides it. */
30
+ interface ICredentialPattern {
31
+ pattern: RegExp;
32
+ /** Keeps the credential's name and replaces its value with `***`. */
33
+ replacement: string;
34
+ }
35
+
36
+ /**
37
+ * Name endings that mark a credential setting: NPM_TOKEN, DEPLOY_SECRET,
38
+ * MINIO_SECRET_KEY, secretKey, DB_PASSWORD, GPG_PASSPHRASE, OPENAI_API_KEY,
39
+ * x-api-key, AWS_SECRET_ACCESS_KEY, GIT_CREDENTIALS.
40
+ */
41
+ const credentialNameEndings = String.raw`token|secret(?:[_-]?key)?|passw(?:or)?d|passphrase|api[_-]?key|access[_-]?key|private[_-]?key|credentials?`;
42
+
43
+ /**
44
+ * A name of `charsArg` characters that ends in one of `endingsArg`, or in
45
+ * PASS or PWD. PASS counts only as the whole name or after a _ or -, so BYPASS
46
+ * is no credential; PWD counts only after one, so the shell's PWD and OLDPWD,
47
+ * which hold directories, are none either.
48
+ */
49
+ const credentialName = (charsArg: string, endingsArg: string): string =>
50
+ String.raw`(?:${charsArg}*(?:${endingsArg})|(?:${charsArg}*[_-])?pass|${charsArg}*[_-]pwd)`;
51
+
52
+ /**
53
+ * Name endings of object keys, environment variables and options, which also
54
+ * name a credential by AUTH or AUTHORIZATION, or a one-time password by OTP:
55
+ * Docker's "auth", HTTPAUTH, BASIC_AUTH, --registry-auth, npm's --otp.
56
+ */
57
+ const credentialKeyEndings = String.raw`${credentialNameEndings}|auth(?:orization)?|otp`;
58
+
59
+ /** An environment variable or option name: NPM_TOKEN, DB_PASS, HTTPAUTH, --token. */
60
+ const settingName = credentialName(String.raw`\w`, credentialKeyEndings);
61
+
62
+ /**
63
+ * A key whose value follows its colon without quotes, as in YAML and log
64
+ * lines: password: …, GPG_PASSPHRASE: …, x-access-token: …, db_pass: …. PASS
65
+ * and PWD count only after a _ or -, because test runners print "pass: 12",
66
+ * and AUTH does not count, because "auth: required" is a message, not a
67
+ * setting.
68
+ */
69
+ const colonSettingName = String.raw`[\w-]*(?:${credentialNameEndings}|[_-](?:pass|pwd))`;
70
+
71
+ /**
72
+ * A setting value: a quoted string, or the text up to the next whitespace. A
73
+ * quote the line never closes hides the value to the end of the line.
74
+ */
75
+ const settingValue = String.raw`(?:"[^"\n]*"?|'[^'\n]*'?|[^\s"']\S*)`;
76
+
77
+ /**
78
+ * Credential forms that failing Git, pnpm and project commands can print, in
79
+ * the order they are redacted. Each pattern keeps what names the credential
80
+ * and replaces only the value, so a message still says which setting leaked
81
+ * into the output. Values stop at a line end, so a pattern never reaches into
82
+ * the next line of output.
83
+ *
84
+ * Redaction runs over the whole output of a command, which can be megabytes,
85
+ * so every pattern runs in time linear in its input: a run a pattern scans
86
+ * before it can fail either has a length bound or starts only where the run
87
+ * itself starts, so no position is rescanned from each of the positions
88
+ * before it.
89
+ */
90
+ const credentialPatterns: ReadonlyArray<ICredentialPattern> = [
91
+ // PEM private key blocks, whole, across lines. A block cut off by the end
92
+ // of the output is hidden up to that end. The key type before and after
93
+ // PRIVATE KEY ("OPENSSH", "ENCRYPTED", " BLOCK") is bounded.
94
+ {
95
+ pattern:
96
+ /(-----BEGIN [A-Z0-9 ]{0,40}PRIVATE KEY[A-Z ]{0,20}-----)[\s\S]*?(-----END [A-Z0-9 ]{0,40}PRIVATE KEY[A-Z ]{0,20}-----|$)/g,
97
+ replacement: "$1***$2",
98
+ },
99
+ // URL userinfo: https://user:token@host, ssh://git@host. The scheme is at
100
+ // most 32 characters long.
101
+ {
102
+ pattern: /\b([A-Za-z][A-Za-z0-9+.-]{0,31}:\/\/)[^\s/?#]*@/g,
103
+ replacement: "$1***@",
104
+ },
105
+ // JSON string values under a credential key: "_authToken": "…",
106
+ // "password": "…", "secretKey": "…", "pass": "…", "token": "…", Docker's
107
+ // "auth": "…". A value the line never closes is hidden to the line end.
108
+ {
109
+ pattern: new RegExp(
110
+ String.raw`("${credentialName(String.raw`[^"\n]`, credentialKeyEndings)}"[ \t]*:[ \t]*")(?:[^"\\\n]|\\.)*("?)`,
111
+ "gi",
112
+ ),
113
+ replacement: "$1***$2",
114
+ },
115
+ // Unquoted values under a credential key in YAML and log lines:
116
+ // password: hunter2, token: abc, GPG_PASSPHRASE: …. The colon follows the
117
+ // name directly, so "Unexpected token : in JSON" keeps its text, and null,
118
+ // undefined, true and false stay, so a printout still says that a token
119
+ // was missing. A quoted value is left to the next pattern, and this one
120
+ // runs first, so it never takes a hidden quoted value and the comma after
121
+ // it for a value of its own. A Bearer, Basic or token scheme before the
122
+ // value stays, as in the header pattern below, so PRIVATE-TOKEN: Bearer …
123
+ // and X-Auth-Token: Basic … hide the credential, not the scheme.
124
+ {
125
+ pattern: new RegExp(
126
+ String.raw`((?<![\w-])${colonSettingName}:[ \t]*(?:(?:bearer|basic|token)[ \t]+)?)(?!(?:null|undefined|true|false)(?:[\s,;)\]}]|$))[^\s"'\x60]\S*`,
127
+ "gi",
128
+ ),
129
+ replacement: "$1***",
130
+ },
131
+ // Quoted values under a credential key in JavaScript object and YAML
132
+ // printouts: password: '…', secretKey: "…", token: '…', apiKey: '…',
133
+ // 'PRIVATE-TOKEN': '…', authorization: 'Bearer …'. \x60 is the backtick
134
+ // Node prints around a string that holds both quote marks. Only a quoted
135
+ // value is hidden, so "Unexpected token : in JSON" keeps its text.
136
+ {
137
+ pattern: new RegExp(
138
+ String.raw`((?<![\w-])${credentialName(String.raw`[\w-]`, credentialKeyEndings)}'?[ \t]*:[ \t]*)(?:'(?:[^'\\\n]|\\.)*'?|"(?:[^"\\\n]|\\.)*"?|\x60(?:[^\x60\\\n]|\\.)*\x60?)`,
139
+ "gi",
140
+ ),
141
+ replacement: "$1***",
142
+ },
143
+ // HTTP headers: Authorization and Proxy-Authorization, with or without a
144
+ // scheme, GitLab's PRIVATE-TOKEN, JOB-TOKEN and Deploy-Token, Api-Key, and
145
+ // X- headers whose name ends in a credential word: X-Api-Key,
146
+ // X-Auth-Token, X-Registry-Auth, X-Amz-Security-Token. The part of an X-
147
+ // name before that word is at most 40 characters long.
148
+ {
149
+ pattern:
150
+ /(\b(?:authorization|(?:private|job|deploy)-token|api-key|x-[a-z0-9-]{0,40}?(?:token|api-key|secret|auth))[ \t]*:[ \t]*(?:(?:bearer|basic|token)[ \t]+)?)\S+/gi,
151
+ replacement: "$1***",
152
+ },
153
+ // Cookie and Set-Cookie headers. A cookie list holds spaces ("a=1; b=2"),
154
+ // so the value is hidden to the line end. The header name stands on its
155
+ // own, so a package such as tough-cookie: 4.1.3 keeps its version.
156
+ {
157
+ pattern: /((?<![\w-])(?:set-)?cookie[ \t]*:[ \t]*)\S[^\r\n]*/gi,
158
+ replacement: "$1***",
159
+ },
160
+ // npm credential settings in .npmrc lines and npm_config_ variables:
161
+ // //registry/:_authToken=…, _auth = …, npm_config__password=….
162
+ {
163
+ pattern: new RegExp(
164
+ String.raw`(_(?:authToken|auth|password)[ \t]*[=:][ \t]*)${settingValue}`,
165
+ "gi",
166
+ ),
167
+ replacement: "$1***",
168
+ },
169
+ // Query parameters: ?token=, &access_token=, &private_token=, &sig=,
170
+ // X-Amz-Signature=, X-Amz-Credential=, ?key=.
171
+ {
172
+ pattern:
173
+ /([?&][\w.-]*(?:token|secret|passw(?:or)?d|sig|signature|credential|key|auth)=)[^\s&#"'<>]+/gi,
174
+ replacement: "$1***",
175
+ },
176
+ // Environment variables and options whose name ends in a credential word:
177
+ // NPM_TOKEN=, NODE_AUTH_TOKEN=, GITHUB_TOKEN=, GITEA_TOKEN=, *_SECRET=,
178
+ // SECRET_KEY=, *_PASSWORD=, *_PASSPHRASE=, DB_PASS=, MYSQL_PWD=,
179
+ // *_API_KEY=, AWS_SECRET_ACCESS_KEY=, HTTPAUTH=, BASIC_AUTH=, --token=. A value without quotes is hidden to the
180
+ // next whitespace, & included. BYPASS=, PWD= and OLDPWD= keep their
181
+ // values, as credentialName describes. Query parameters, names that follow a ? or & (looked up at
182
+ // most 64 characters back), are left to the pattern above, which keeps the
183
+ // #fragment and the parameters after their value.
184
+ {
185
+ pattern: new RegExp(
186
+ String.raw`(\b(?=${settingName}[ \t]*=)(?<![?&][\w.-]{0,63})${settingName}[ \t]*=[ \t]*)${settingValue}`,
187
+ "gi",
188
+ ),
189
+ replacement: "$1***",
190
+ },
191
+ // Environment variables whose upper-case name ends in _KEY: SSH_KEY=,
192
+ // DEPLOY_KEY=, SIGNING_KEY=, and SSH_KEY: in a YAML env block. KEY alone
193
+ // names too much to count in other names, so only an upper-case name, as
194
+ // environment variables are written, counts: sort_key=, cacheKey: and
195
+ // primary_key: keep their values. PUBLIC_KEY holds no secret and keeps its
196
+ // value too. Query parameters are left to the pattern for them, as above.
197
+ {
198
+ pattern: new RegExp(
199
+ String.raw`(\b(?<![?&][\w.-]{0,63})[A-Z0-9_]*(?<!PUBLIC)_KEY(?:[ \t]*=|:)[ \t]*)${settingValue}`,
200
+ "g",
201
+ ),
202
+ replacement: "$1***",
203
+ },
204
+ // Credential options followed by their value: --token …, --password …,
205
+ // --secret …, --auth-token …, --npm-token …, --api-key …, --passphrase …,
206
+ // --otp ….
207
+ // The name ends in a credential word, so --password-stdin, --token-file
208
+ // and --secret-id keep the argument after them, and a --no- option takes
209
+ // no value.
210
+ {
211
+ pattern: new RegExp(
212
+ String.raw`((?<![\w-])--(?!no-)${credentialName(String.raw`[\w-]`, credentialKeyEndings)}[ \t]+)${settingValue}`,
213
+ "gi",
214
+ ),
215
+ replacement: "$1***",
216
+ },
217
+ // The password after -p in a registry login: docker login -u ci -p …,
218
+ // podman login -p=…. -p names a port or a path in most other commands, so
219
+ // it counts only after docker, podman, buildah, nerdctl or skopeo login,
220
+ // at most 256 characters further on the line. --password-stdin takes no
221
+ // value and keeps the argument after it.
222
+ {
223
+ pattern: new RegExp(
224
+ String.raw`(\b(?:docker|podman|buildah|nerdctl|skopeo)[ \t]+login\b[^\n]{0,256}?[ \t]-p(?:[ \t]+|=))${settingValue}`,
225
+ "gi",
226
+ ),
227
+ replacement: "$1***",
228
+ },
229
+ // The password in a user:password argument after -u or --user: curl -u
230
+ // ci:…, curl --user "ci:…". The user stays. -u names a user in curl,
231
+ // docker login and many other commands, but also git push -u origin and
232
+ // sort -u, so only a value that holds a colon counts. Two runs of digits
233
+ // are a uid:gid (docker run -u 1000:1000) and a value that goes on with //
234
+ // is a URL (-u https://host), so both keep their text. The user is at most
235
+ // 256 characters long.
236
+ {
237
+ pattern:
238
+ /((?<![\w-])(?:-u|--user)(?:[ \t]+|=))(?![0-9]{1,32}:[0-9]{1,32}(?!\S))(?:("[^:"\n]{0,256}:)[^"\n]*("?)|('[^:'\n]{0,256}:)[^'\n]*('?)|([^\s:"']{0,256}:)(?!\/\/)\S+)/g,
239
+ replacement: "$1$2$4$6***$3$5",
240
+ },
241
+ // .netrc entries: machine host login ci password …, on one line or across
242
+ // lines, default login ci password …, and machine host password … login
243
+ // ci. A bare password counts only with a login in the same entry, before
244
+ // it or right after its value, so "machine learning password policy" and
245
+ // "the default password is admin" keep their text. An account may stand
246
+ // before and after the login.
247
+ {
248
+ pattern: new RegExp(
249
+ String.raw`(\b(?:machine[ \t]+\S+|default)(?:\s+account[ \t]+\S+)?(?:\s+login[ \t]+\S+(?:\s+account[ \t]+\S+)?\s+password[ \t]+|\s+password[ \t]+(?=${settingValue}\s+login[ \t])))${settingValue}`,
250
+ "g",
251
+ ),
252
+ replacement: "$1***",
253
+ },
254
+ // npm access tokens.
255
+ { pattern: /\bnpm_[A-Za-z0-9]{36}\b/g, replacement: "***" },
256
+ // GitHub classic personal, OAuth, user, server and refresh tokens, and
257
+ // fine-grained personal access tokens.
258
+ {
259
+ pattern: /\b(?:gh[oprsu]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{22,})\b/g,
260
+ replacement: "***",
261
+ },
262
+ // GitLab personal access tokens.
263
+ { pattern: /\bglpat-[A-Za-z0-9_-]{20,}/g, replacement: "***" },
264
+ // Slack bot, user, app and refresh tokens.
265
+ { pattern: /\bxox[abpr]-[A-Za-z0-9-]{10,}/g, replacement: "***" },
266
+ // AWS access key IDs, long-term and temporary.
267
+ { pattern: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g, replacement: "***" },
268
+ // JSON Web Tokens: three base64url parts, the first a JSON object. A token
269
+ // starts where a run of base64url characters starts.
270
+ {
271
+ pattern:
272
+ /(?<![A-Za-z0-9_-])eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]*/g,
273
+ replacement: "***",
274
+ },
275
+ ];
276
+
277
+ /**
278
+ * Removes credentials from command output: private keys, URL userinfo,
279
+ * authorization, API key and cookie headers, credential settings in JSON,
280
+ * YAML, npm configuration, query strings, environment variables and options,
281
+ * and tokens whose shape identifies them, as listed in {@link credentialPatterns}. Git and pnpm echo remote and
282
+ * registry URLs in their errors, and project commands can print anything.
283
+ */
284
+ export const redactCommandOutput = (textArg: string): string =>
285
+ credentialPatterns.reduce(
286
+ (textSoFar, { pattern, replacement }) =>
287
+ textSoFar.replace(pattern, replacement),
288
+ textArg,
289
+ );
290
+
291
+ /**
292
+ * Reduces command output to one redacted line of at most
293
+ * {@link releaseCommandOutputTailLength} characters, keeping its end, where
294
+ * the error is. Redaction runs before truncation, so a cut can never expose
295
+ * part of a credential.
296
+ */
297
+ export const summarizeCommandOutput = (outputArg: string): string => {
298
+ const line = redactCommandOutput(outputArg.replace(ansiEscapePattern, ""))
299
+ .split(/\r\n|\r|\n/)
300
+ .map((lineArg) =>
301
+ lineArg
302
+ .replace(/[\u0000-\u001f\u007f]+/g, " ")
303
+ .replace(/\s+/g, " ")
304
+ .trim(),
305
+ )
306
+ .filter(Boolean)
307
+ .join(" | ");
308
+ return line.length > releaseCommandOutputTailLength
309
+ ? `...${line.slice(line.length - releaseCommandOutputTailLength)}`
310
+ : line;
311
+ };
312
+
313
+ const formatDuration = (msArg: number): string =>
314
+ `${Number((msArg / 1000).toFixed(3))} s`;
315
+
316
+ /**
317
+ * States how a command failed: its timeout, signal or exit code, followed by
318
+ * the tail of its output.
319
+ */
320
+ export const describeCommandFailure = (
321
+ resultArg: plugins.smartshell.IExecResult,
322
+ contextArg: IReleaseCommandFailureContext,
323
+ ): string => {
324
+ const termination = resultArg.signal
325
+ ? `was terminated by ${resultArg.signal}`
326
+ : `exited with code ${resultArg.exitCode}`;
327
+ const outcome = resultArg.timedOut
328
+ ? `timed out${
329
+ contextArg.timeoutMs === undefined
330
+ ? ""
331
+ : ` after ${formatDuration(contextArg.timeoutMs)}`
332
+ } and ${termination}`
333
+ : termination;
334
+ const outputName = contextArg.output === "combined" ? "output" : "stderr";
335
+ const tail = summarizeCommandOutput(
336
+ contextArg.output === "combined"
337
+ ? resultArg.combinedOutput
338
+ : resultArg.stderr,
339
+ );
340
+ return `\`${summarizeCommandOutput(contextArg.command)}\` ${outcome}${
341
+ tail ? `; ${outputName}: ${tail}` : ""
342
+ }`;
343
+ };
344
+
345
+ /** Appends the failure detail of a command to the sentence that names its step. */
346
+ export const formatCommandFailure = (
347
+ messageArg: string,
348
+ resultArg: plugins.smartshell.IExecResult,
349
+ contextArg: IReleaseCommandFailureContext,
350
+ ): string => `${messageArg} ${describeCommandFailure(resultArg, contextArg)}`;
@@ -4,6 +4,10 @@ import {
4
4
  type IReleaseArtifact,
5
5
  } from "./classes.releasejournal.js";
6
6
  import { assertCredentialFreeGitPushDestination } from "./helpers.releasebranch.js";
7
+ import {
8
+ describeCommandFailure,
9
+ formatCommandFailure,
10
+ } from "./helpers.commandfailure.js";
7
11
  import {
8
12
  compareReleaseVersions,
9
13
  isCanonicalReleaseVersion,
@@ -201,7 +205,13 @@ const readPnpmJson = async (
201
205
  },
202
206
  );
203
207
  if (result.exitCode !== 0 || result.timedOut) {
204
- throw new Error(`Unable to inspect pnpm ${labelArg}.`);
208
+ throw new Error(
209
+ formatCommandFailure(`Unable to inspect pnpm ${labelArg}.`, result, {
210
+ command: `pnpm ${argsArg[0]}`,
211
+ timeoutMs: capabilityCommandTimeoutMs,
212
+ output: "combined",
213
+ }),
214
+ );
205
215
  }
206
216
  if (result.stdout.trim() === "undefined") return undefined;
207
217
  try {
@@ -317,11 +327,20 @@ export const assertPnpmReleaseCapability = async (
317
327
  timeoutKillGraceMs: 5_000,
318
328
  });
319
329
  const version = versionResult.stdout.trim();
320
- if (
321
- versionResult.exitCode !== 0 ||
322
- versionResult.timedOut ||
323
- !stablePnpmVersion.test(version)
324
- ) {
330
+ if (versionResult.exitCode !== 0 || versionResult.timedOut) {
331
+ throw new Error(
332
+ formatCommandFailure(
333
+ "Exact release packaging requires a canonical stable pnpm version.",
334
+ versionResult,
335
+ {
336
+ command: "pnpm --version",
337
+ timeoutMs: capabilityCommandTimeoutMs,
338
+ output: "combined",
339
+ },
340
+ ),
341
+ );
342
+ }
343
+ if (!stablePnpmVersion.test(version)) {
325
344
  throw new Error(
326
345
  "Exact release packaging requires a canonical stable pnpm version.",
327
346
  );
@@ -341,7 +360,15 @@ export const assertPnpmReleaseCapability = async (
341
360
  );
342
361
  if (packHelp.exitCode !== 0 || packHelp.timedOut) {
343
362
  throw new Error(
344
- "Unable to inspect the selected pnpm pack capabilities. Exact release commands require standalone pnpm with support; Corepack launchers are unsupported.",
363
+ formatCommandFailure(
364
+ "Unable to inspect the selected pnpm pack capabilities. Exact release commands require standalone pnpm with support; Corepack launchers are unsupported.",
365
+ packHelp,
366
+ {
367
+ command: "pnpm pack --help",
368
+ timeoutMs: capabilityCommandTimeoutMs,
369
+ output: "combined",
370
+ },
371
+ ),
345
372
  );
346
373
  }
347
374
  requireHelpFragments(packHelp.combinedOutput, "pack");
@@ -357,7 +384,17 @@ export const assertPnpmReleaseCapability = async (
357
384
  },
358
385
  );
359
386
  if (publishHelp.exitCode !== 0 || publishHelp.timedOut) {
360
- throw new Error("Unable to inspect pnpm publish capabilities.");
387
+ throw new Error(
388
+ formatCommandFailure(
389
+ "Unable to inspect pnpm publish capabilities.",
390
+ publishHelp,
391
+ {
392
+ command: "pnpm publish --help",
393
+ timeoutMs: capabilityCommandTimeoutMs,
394
+ output: "combined",
395
+ },
396
+ ),
397
+ );
361
398
  }
362
399
  requireHelpFragments(publishHelp.combinedOutput, "publish");
363
400
  return capability;
@@ -620,7 +657,15 @@ export const packNpmArtifact = async (
620
657
  );
621
658
  if (result.exitCode !== 0) {
622
659
  throw new Error(
623
- "pnpm pack failed while creating the exact release artifact.",
660
+ formatCommandFailure(
661
+ "pnpm pack failed while creating the exact release artifact.",
662
+ result,
663
+ {
664
+ command: "pnpm pack",
665
+ timeoutMs: packCommandTimeoutMs,
666
+ output: "combined",
667
+ },
668
+ ),
624
669
  );
625
670
  }
626
671
  let report: unknown;
@@ -707,7 +752,7 @@ export const publishNpmArtifact = async (
707
752
  artifactPathArg: string,
708
753
  registryArg: string,
709
754
  capabilityArg: IPnpmReleaseCapability | undefined,
710
- ): Promise<{ exitCode: number; output: string }> => {
755
+ ): Promise<{ exitCode: number; output: string; failure?: string }> => {
711
756
  const result = await smartshellArg.execSpawn(
712
757
  "pnpm",
713
758
  buildQualifiedPnpmArgs(
@@ -720,7 +765,19 @@ export const publishNpmArtifact = async (
720
765
  timeoutKillGraceMs: 5_000,
721
766
  },
722
767
  );
723
- return { exitCode: result.exitCode, output: result.combinedOutput };
768
+ return {
769
+ exitCode: result.exitCode,
770
+ output: result.combinedOutput,
771
+ ...(result.exitCode === 0
772
+ ? {}
773
+ : {
774
+ failure: describeCommandFailure(result, {
775
+ command: "pnpm publish",
776
+ timeoutMs: publishCommandTimeoutMs,
777
+ output: "combined",
778
+ }),
779
+ }),
780
+ };
724
781
  };
725
782
 
726
783
  /**
@@ -1,4 +1,8 @@
1
1
  import * as plugins from "./mod.plugins.js";
2
+ import {
3
+ formatCommandFailure,
4
+ type IReleaseCommandFailureContext,
5
+ } from "./helpers.commandfailure.js";
2
6
 
3
7
  const mainBranch = "main";
4
8
  const mainBranchRef = `refs/heads/${mainBranch}`;
@@ -165,27 +169,50 @@ export function parseGitWorktreePorcelain(outputArg: string): IGitWorktree[] {
165
169
  return worktrees;
166
170
  }
167
171
 
172
+ interface IReleaseGitResult extends plugins.smartshell.IExecResult {
173
+ failureContext: IReleaseCommandFailureContext;
174
+ }
175
+
168
176
  const runGit = async (
169
177
  smartshellArg: TSmartshell,
170
178
  cwdArg: string,
171
179
  argsArg: string[],
172
180
  readOnlyArg = false,
173
- ) =>
174
- smartshellArg.execSpawn("git", argsArg, {
181
+ ): Promise<IReleaseGitResult> => {
182
+ const timeoutMs =
183
+ argsArg[0] === "fetch" || argsArg[0] === "push" ? 5 * 60_000 : 60_000;
184
+ const result = await smartshellArg.execSpawn("git", argsArg, {
175
185
  cwd: cwdArg,
176
186
  env: readOnlyArg ? readOnlyGitEnv : releaseGitEnv,
177
187
  silent: true,
178
- timeout:
179
- argsArg[0] === "fetch" || argsArg[0] === "push" ? 5 * 60_000 : 60_000,
188
+ timeout: timeoutMs,
180
189
  timeoutKillGraceMs: 5_000,
181
190
  });
191
+ return {
192
+ ...result,
193
+ failureContext: { command: `git ${argsArg[0]}`, timeoutMs },
194
+ };
195
+ };
196
+
197
+ /** Git's own failure, appended to the sentence that names the release step. */
198
+ const gitFailure = (
199
+ resultArg: IReleaseGitResult,
200
+ messageArg: string,
201
+ ): Error =>
202
+ new Error(
203
+ formatCommandFailure(messageArg, resultArg, resultArg.failureContext),
204
+ );
205
+
206
+ /** Exit status 1 answers Git's predicate commands; it is no failure there. */
207
+ const isGitNegativeAnswer = (resultArg: IReleaseGitResult): boolean =>
208
+ resultArg.exitCode === 1 && !resultArg.timedOut && !resultArg.signal;
182
209
 
183
210
  const requireGitSuccess = (
184
- resultArg: plugins.smartshell.IExecResult,
211
+ resultArg: IReleaseGitResult,
185
212
  messageArg: string,
186
- ): plugins.smartshell.IExecResult => {
213
+ ): IReleaseGitResult => {
187
214
  if (resultArg.exitCode !== 0) {
188
- throw new Error(messageArg);
215
+ throw gitFailure(resultArg, messageArg);
189
216
  }
190
217
  return resultArg;
191
218
  };
@@ -201,6 +228,12 @@ const resolveSymbolicBranch = async (
201
228
  ["symbolic-ref", "--quiet", "HEAD"],
202
229
  readOnlyArg,
203
230
  );
231
+ if (result.exitCode !== 0 && !isGitNegativeAnswer(result)) {
232
+ throw gitFailure(
233
+ result,
234
+ "Unable to resolve the checked-out release branch.",
235
+ );
236
+ }
204
237
  const ref = result.stdout.trim();
205
238
  if (result.exitCode !== 0 || !ref.startsWith("refs/heads/")) {
206
239
  throw new Error(
@@ -549,6 +582,12 @@ const verifyLinearAncestry = async (
549
582
  "Release merge ancestry cannot be verified in this shallow clone. Fetch complete main and feature history, then retry.",
550
583
  );
551
584
  }
585
+ if (!isGitNegativeAnswer(ancestryResult)) {
586
+ throw gitFailure(
587
+ ancestryResult,
588
+ "Unable to verify that the release branch is rebased onto main.",
589
+ );
590
+ }
552
591
  throw new Error(
553
592
  "The release branch is not cleanly rebased onto current main. Rebase it onto main, resolve conflicts, and retry.",
554
593
  );
@@ -1019,7 +1058,9 @@ const verifyCommitContained = async (
1019
1058
  ["merge-base", "--is-ancestor", ancestorOidArg, descendantOidArg],
1020
1059
  true,
1021
1060
  );
1022
- if (result.exitCode !== 0) throw new Error(messageArg);
1061
+ if (result.exitCode === 0) return;
1062
+ if (isGitNegativeAnswer(result)) throw new Error(messageArg);
1063
+ throw gitFailure(result, "Unable to verify release commit containment.");
1023
1064
  };
1024
1065
 
1025
1066
  /**
@@ -1038,8 +1079,9 @@ const ensureRemoteCommitObject = async (
1038
1079
  if (await hasCommitObject(smartshellArg, cwdArg, remoteMainOidArg, true)) {
1039
1080
  return;
1040
1081
  }
1082
+ let lastFetchFailure: IReleaseGitResult | undefined;
1041
1083
  for (const fetchTargetArg of [mainBranchRef, remoteMainOidArg]) {
1042
- await runGit(smartshellArg, cwdArg, [
1084
+ const fetchResult = await runGit(smartshellArg, cwdArg, [
1043
1085
  "fetch",
1044
1086
  "--no-tags",
1045
1087
  "--no-recurse-submodules",
@@ -1047,13 +1089,15 @@ const ensureRemoteCommitObject = async (
1047
1089
  pushUrlArg,
1048
1090
  fetchTargetArg,
1049
1091
  ]);
1092
+ if (fetchResult.exitCode !== 0) lastFetchFailure = fetchResult;
1050
1093
  if (await hasCommitObject(smartshellArg, cwdArg, remoteMainOidArg, true)) {
1051
1094
  return;
1052
1095
  }
1053
1096
  }
1054
- throw new Error(
1055
- `Remote main ${remoteMainOidArg} could not be fetched; remote containment unverified.`,
1056
- );
1097
+ const message = `Remote main ${remoteMainOidArg} could not be fetched; remote containment unverified.`;
1098
+ throw lastFetchFailure
1099
+ ? gitFailure(lastFetchFailure, message)
1100
+ : new Error(message);
1057
1101
  };
1058
1102
 
1059
1103
  /**
@@ -1232,7 +1276,11 @@ const compensateFailedLocalMainTransition = async (
1232
1276
  if (restoreResult.exitCode === 0) {
1233
1277
  return ` Local main ref was restored after the worktree update failed.${localState}`;
1234
1278
  }
1235
- return ` Local main changed before its ref could be restored.${localState}`;
1279
+ const failure = gitFailure(
1280
+ restoreResult,
1281
+ "Local main changed before its ref could be restored.",
1282
+ );
1283
+ return ` ${failure.message}${localState}`;
1236
1284
  };
1237
1285
 
1238
1286
  const rollbackLocalMain = async (
@@ -1385,7 +1433,8 @@ export async function integrateReleaseBranch(
1385
1433
  contextArg.localMainOid,
1386
1434
  ]);
1387
1435
  if (refAdvanceResult.exitCode !== 0) {
1388
- throw new Error(
1436
+ throw gitFailure(
1437
+ refAdvanceResult,
1389
1438
  "Local main changed before integration. No local ref or worktree rollback was attempted.",
1390
1439
  );
1391
1440
  }
@@ -1403,9 +1452,11 @@ export async function integrateReleaseBranch(
1403
1452
  releaseCwd,
1404
1453
  destinationGitDir,
1405
1454
  );
1406
- throw new Error(
1407
- `Local main advanced, but its index and worktree could not be updated. No remote ref or release metadata was changed.${rollbackState}`,
1455
+ const failure = gitFailure(
1456
+ worktreeAdvanceResult,
1457
+ "Local main advanced, but its index and worktree could not be updated. No remote ref or release metadata was changed.",
1408
1458
  );
1459
+ throw new Error(`${failure.message}${rollbackState}`);
1409
1460
  }
1410
1461
  try {
1411
1462
  await verifyMainWorktree(
@@ -1468,8 +1519,12 @@ export async function integrateReleaseBranch(
1468
1519
  releaseCwd,
1469
1520
  destinationGitDir,
1470
1521
  );
1522
+ const failure = gitFailure(
1523
+ pushResult,
1524
+ "Integrated main could not be confirmed at the remote. No release metadata was created.",
1525
+ );
1471
1526
  throw new Error(
1472
- `Integrated main could not be confirmed at the remote. No release metadata was created.${rollbackState}${
1527
+ `${failure.message}${rollbackState}${
1473
1528
  remoteAfterPush
1474
1529
  ? ""
1475
1530
  : " The remote outcome is unknown; inspect refs/heads/main before retrying."