@osdlc/typed-git 0.7.1 → 0.8.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/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # @osdlc/typed-git
2
2
 
3
+ ## 0.8.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 1a44195: New `pushPorcelain(remote, refspec, { atomic, forceWithLease })` on `Git` and `AsyncGit`. It runs `git push --porcelain` and returns one result per ref: `{ src, dst, flag, summary, rawReason }`. A rejected ref (`flag: '!'`) also has a typed `rejection` and the remote's `detail` line, and checking `flag` narrows the type. `rejection` is one of `stale`, `non-fast-forward`, `tag-exists`, `already-exists`, `ref-conflict`, `lock-failed`, `hook-declined` or `other`, so you no longer read git's stderr to learn why a push failed. The reason is read from git's text, including the remote's `cannot lock ref` line, not from the local git version. So the old and new wordings, such as `(failed to update ref)` from older git and `(refname conflict)` from git 2.53 and 2.54, map to the same value. A failure that reaches no ref, such as an unknown remote, a network or auth problem, or a local pre-push hook, still throws the classified failure. `forceWithLease` also takes one lease per ref. `refspec` takes a list. An empty lease list throws a `TypeError` rather than pushing with no lease.
8
+
9
+ ## 0.7.2
10
+
11
+ ### Patch Changes
12
+
13
+ - Updated dependencies [0cf31de]
14
+ - @osdlc/command-seam@0.11.0
15
+
3
16
  ## 0.7.1
4
17
 
5
18
  ### Patch Changes
package/README.md CHANGED
@@ -345,7 +345,8 @@ For the paths alone, `diffNameOnly({ diffFilter: "U" })` is cheaper.
345
345
 
346
346
  `merge`, `rebase` and `rebaseContinue` run with `LC_ALL=C`, over the client,
347
347
  backend and call `env`, so `fastForward`, `alreadyUpToDate` and `conflicts` do
348
- not change with the caller's locale. Other verbs keep the caller's locale.
348
+ not change with the caller's locale. `pushPorcelain` does the same for its
349
+ reasons. Other verbs keep the caller's locale.
349
350
 
350
351
  One trap in `checkoutSide`: on a path that is not conflicted, git exits 0 and
351
352
  does nothing. There is no error to catch, so take the path list from
@@ -377,6 +378,66 @@ need to call `lsFilesUnmerged()` after it. And it takes
377
378
  both sides as arguments rather than merging into the current branch, so
378
379
  nothing depends on where `HEAD` happens to be.
379
380
 
381
+ ## Pushing: a rejected ref is a value
382
+
383
+ `push` throws when git exits non-zero. `pushPorcelain` runs
384
+ `git push --porcelain` and returns one result per ref, so a lease that lost a
385
+ race is an answer you can branch on, not stderr you grep:
386
+
387
+ ```ts
388
+ const report = git.pushPorcelain("origin", `${next}:refs/heads/lease`, {
389
+ forceWithLease: { ref: "refs/heads/lease", expect: seen },
390
+ });
391
+ const ref = report.refs[0];
392
+ // { src, dst, flag, summary, rawReason }, plus { rejection, detail } when flag is "!"
393
+ if (ref.flag === "!") {
394
+ switch (ref.rejection) {
395
+ case "stale": // the lease check failed before anything was sent
396
+ case "lock-failed": // another writer moved or deleted it at the remote
397
+ case "already-exists": // a create lost to another writer
398
+ return retry();
399
+ default: // tag-exists, ref-conflict, hook-declined, non-fast-forward, other
400
+ throw new Error(`${ref.dst}: ${ref.rawReason} ${ref.detail ?? ""}`);
401
+ }
402
+ }
403
+ ```
404
+
405
+ It takes a refspec or a list, and `{ atomic, forceWithLease }`, where
406
+ `forceWithLease` also takes one lease per ref. `flag` is git's status
407
+ character: `' '` fast-forward, `'+'` forced, `'-'` deleted, `'*'` new, `'!'`
408
+ rejected, `'='` up to date. A failure that reaches no ref still throws the
409
+ classified failure: an unknown remote, auth, network, TLS, a refspec that
410
+ matches nothing, or a local pre-push hook.
411
+
412
+ `rejection` is read from the reason text, never from the local git version,
413
+ because a `[remote rejected]` reason is written by the remote's git. The
414
+ wording has changed across versions:
415
+
416
+ | Case | git 2.53 / 2.54 | Older git | `rejection` |
417
+ | --- | --- | --- | --- |
418
+ | lease expects a sha the remote no longer holds | `[rejected] (stale info)` | same | `stale` |
419
+ | behind the remote, or the old or new value is not a commit | `(non-fast-forward)`, `(fetch first)`, `(needs force)` | same | `non-fast-forward` |
420
+ | existing tag | `[rejected] (already exists)` | same | `tag-exists` |
421
+ | another writer moved the ref after the lease check | `(incorrect old value provided)` | `(failed to update ref)` + `… but expected …` | `lock-failed` |
422
+ | another writer deleted it | `(reference does not exist)` | `(failed to update ref)` + `unable to resolve reference` | `lock-failed` |
423
+ | another writer created it first | `(reference already exists)` | `(failed to update ref)` + `reference already exists` | `already-exists` |
424
+ | `<ref>` beside an existing `<ref>/child` | `(refname conflict)` | `(failed to update ref)` + `'<ref>/child' exists; cannot create '<ref>'` | `ref-conflict` |
425
+ | a remote hook refused it | `(pre-receive hook declined)`, `(hook declined)` | same | `hook-declined` |
426
+ | a `.lock` file in the way, an unwritable refs directory | `(reference already exists)`, `(failed to update refs)` + `Unable to create '….lock'` | `(failed to update ref)` + the same | `other` |
427
+ | the other refs of a failed `--atomic` push | `[rejected] (atomic push failed)`, `[remote rejected] (atomic transaction failed)` | same | `other` |
428
+
429
+ The "+ …" text is the remote's `cannot lock ref '<ref>': …` line. git prints
430
+ it on stderr, not on the ref line, and `detail` carries it for the ref it
431
+ names. With several push URLs, a ref's lines go to its rejected entries in
432
+ order. `(failed to update ref)` alone is never read as a race, because a ref
433
+ clash, an unwritable directory and a stale lock all end that way. One case
434
+ the text cannot settle: a 2.53 remote prints no detail line, so a stale
435
+ `.lock` there reads exactly like a lost create, `already-exists`. A 2.54
436
+ remote prints the detail, and that reads as `other`.
437
+
438
+ This table is the one list of wordings. `tests/push.test.ts` covers each
439
+ row, against real git or as a canned row in `CANNED`.
440
+
380
441
  ## `log` hands back bytes
381
442
 
382
443
  ```ts
@@ -529,14 +590,15 @@ empty repository from a dangling HEAD or a missing object store. Use
529
590
  Every mutation except `configRemoveSection` declares no absence: a non-zero
530
591
  exit throws the classified failure, because the only sane handling of "the write did
531
592
  not happen" is to surface it. `configRemoveSection` declares 128 absent and
532
- returns `false` when there is no such section.
593
+ returns `false` when there is no such section. `pushPorcelain`, listed under
594
+ Integration, declares exit 1 absent and returns the rejected refs.
533
595
 
534
596
  | Method | git |
535
597
  | --- | --- |
536
598
  | `fetch(remote, refspec, { prune, quiet, noWriteFetchHead, depth, noTags })` | `fetch` |
537
599
  | `add(paths, { all, update, intentToAdd })` | `add` (paths go after `--`) |
538
600
  | `commit({ message, body } \| { messageFile } \| { messageStdin }, { allowEmpty, amend, noVerify, signoff })` | `commit` — one message source, enforced by the types; `messageStdin` is `-F -` with the string on stdin, no temp file |
539
- | `push(remote, refspec, { forceWithLease })` | `push` — `forceWithLease` takes `true` or a pinned `{ ref, expect }` (`expect: null` = ref must be absent); `forceWithLeaseArg(lease)` is the pure formatter. `true` is the bare form: it overwrites whatever is on the remote, so prefer the pinned form |
601
+ | `push(remote, refspec, { forceWithLease })` | `push` — `forceWithLease` takes `true` or a pinned `{ ref, expect }` (`expect: null` = ref must be absent); `forceWithLeaseArg(lease)` is the pure formatter. `true` is the bare form: it overwrites whatever is on the remote, so prefer the pinned form. To learn why a push was rejected, use `pushPorcelain` |
540
602
  | `configSet(key, value, { scope })` | `config` |
541
603
  | `configRemoveSection(name)` | `config --remove-section` — `false` when there is no such section |
542
604
  | `init(path, { bare, initialBranch, quiet })` | `init` |
@@ -556,8 +618,8 @@ returns `false` when there is no such section.
556
618
 
557
619
  ### Integration
558
620
 
559
- Exit 1 is declared absence: a conflict is an answer. Every other non-zero exit
560
- throws.
621
+ Exit 1 is declared absence: a conflict or a rejected ref is an answer. Every
622
+ other non-zero exit throws.
561
623
 
562
624
  | Method | git | Returns |
563
625
  | --- | --- | --- |
@@ -566,6 +628,7 @@ throws.
566
628
  | `rebaseContinue()` | `-c core.editor=true rebase --continue` | `RebaseOutcome` |
567
629
  | `mergeTree(ours, theirs, { mergeBase })` | `merge-tree --write-tree --name-only -z` | `MergeTreeOutcome` |
568
630
  | `lsFilesUnmerged()` | `ls-files -u -z` | `UnmergedEntry[]` — mode, sha, stage, path |
631
+ | `pushPorcelain(remote, refspec \| refspecs, { atomic, forceWithLease })` | `push --porcelain` | `PushReport` — `{ refs, stderr }`, one `PushRefResult` per ref; a `'!'` ref also has `rejection` and `detail`; exit 1 without a rejected ref throws |
569
632
 
570
633
  ### Escape hatches and re-rooting
571
634
 
@@ -792,7 +855,7 @@ de-duplicate.
792
855
  `CommandFailed`, with the raw `result`.
793
856
  - `UnsupportedRequest` is not a git failure, so `try` and `soft` let it
794
857
  through.
795
- - `merge`, `rebase` and `rebaseContinue` run with `LC_ALL=C`. Any other verb
858
+ - `merge`, `rebase`, `rebaseContinue` and `pushPorcelain` run with `LC_ALL=C`. Any other verb
796
859
  that reads git's messages assumes English output, so a localized git can
797
860
  change what it returns.
798
861
  - Test fixtures need a manual `cleanup()`.
package/dist/async.d.ts CHANGED
@@ -16,7 +16,7 @@ import type { CommandResult } from '@osdlc/command-seam';
16
16
  import { type GitBackend, type GitCallOptions } from './backend.ts';
17
17
  import { type Soft, type TriedAsync } from './outcome.ts';
18
18
  import { type RemoteCoordinate } from './remote-url.ts';
19
- import { type AddOptions, type AheadBehind, type CommitOptions, type CheckoutOptions, type ConfigGetOptions, type CloneOptions, type ConflictSide, type MergeOptions, type MergeOutcome, type MergeTreeOptions, type MergeTreeOutcome, type RebaseOptions, type RebaseOutcome, type RemoteGetUrlOptions, type TaggedFile, type UnmergedEntry, type ConfigSetOptions, 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 NumstatEntry, type RemoteRef, type CleanOptions, type DiffCheckOptions, type DiffCheckResult, type StatusEntry, type StatusPorcelainOptions, type TreeEntry, type Worktree, type WorktreeMoveOptions } from './verbs.ts';
19
+ import { type AddOptions, type AheadBehind, type CommitOptions, type CheckoutOptions, type ConfigGetOptions, type CloneOptions, type ConflictSide, type MergeOptions, type MergeOutcome, type MergeTreeOptions, type MergeTreeOutcome, type RebaseOptions, type RebaseOutcome, type RemoteGetUrlOptions, type TaggedFile, type UnmergedEntry, type ConfigSetOptions, 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 NumstatEntry, type PushPorcelainOptions, type PushReport, type RemoteRef, type CleanOptions, type DiffCheckOptions, type DiffCheckResult, type StatusEntry, type StatusPorcelainOptions, type TreeEntry, type Worktree, type WorktreeMoveOptions } from './verbs.ts';
20
20
  /** A typed, awaitable git client bound to one working directory. */
21
21
  export declare class AsyncGit {
22
22
  readonly cwd: string;
@@ -258,6 +258,12 @@ export declare class AsyncGit {
258
258
  push(remote: string, refspec: string, opts?: GitCallOptions & {
259
259
  forceWithLease?: boolean | ForceLease | undefined;
260
260
  }): Promise<void>;
261
+ /**
262
+ * `git push --porcelain`, read into one result per ref. A rejected ref comes
263
+ * back with a typed `rejection` rather than a rejection of the promise. See
264
+ * {@link Git.pushPorcelain}.
265
+ */
266
+ pushPorcelain(remote: string, refspec: string | string[], opts?: GitCallOptions & PushPorcelainOptions): Promise<PushReport>;
261
267
  /** `git clean -f`, plus `-d` with `directories`. Ignored files are kept. */
262
268
  clean(opts?: GitCallOptions & CleanOptions): Promise<void>;
263
269
  /** `git reset --hard <rev>`. */
package/dist/async.js CHANGED
@@ -426,6 +426,15 @@ export class AsyncGit {
426
426
  push(remote, refspec, opts = {}) {
427
427
  return this.backend.execute(this.cwd, { kind: 'push', remote, refspec, forceWithLease: opts.forceWithLease }, opts);
428
428
  }
429
+ /**
430
+ * `git push --porcelain`, read into one result per ref. A rejected ref comes
431
+ * back with a typed `rejection` rather than a rejection of the promise. See
432
+ * {@link Git.pushPorcelain}.
433
+ */
434
+ pushPorcelain(remote, refspec, opts = {}) {
435
+ const [call, req] = splitCallOptions(opts);
436
+ return this.backend.execute(this.cwd, { kind: 'pushPorcelain', remote, refspec, ...req }, call);
437
+ }
429
438
  /** `git clean -f`, plus `-d` with `directories`. Ignored files are kept. */
430
439
  clean(opts = {}) {
431
440
  const [call, req] = splitCallOptions(opts);
package/dist/backend.d.ts CHANGED
@@ -18,7 +18,7 @@
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 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 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';
22
22
  /** Per-call concerns that are not part of the operation itself. */
23
23
  export interface GitCallOptions {
24
24
  /**
@@ -188,7 +188,11 @@ export type GitRequest = {
188
188
  remote: string;
189
189
  refspec: string;
190
190
  forceWithLease?: boolean | ForceLease | undefined;
191
- } | {
191
+ } | ({
192
+ kind: 'pushPorcelain';
193
+ remote: string;
194
+ refspec: string | string[];
195
+ } & PushPorcelainOptions) | {
192
196
  kind: 'resetHard';
193
197
  rev: string;
194
198
  } | ({
@@ -315,6 +319,7 @@ export interface GitResults {
315
319
  init: void;
316
320
  clone: void;
317
321
  push: void;
322
+ pushPorcelain: PushReport;
318
323
  resetHard: void;
319
324
  clean: void;
320
325
  deleteBranch: void;
package/dist/backend.js CHANGED
@@ -126,6 +126,8 @@ function toVerb(request) {
126
126
  return v.push(request.remote, request.refspec, {
127
127
  forceWithLease: request.forceWithLease,
128
128
  });
129
+ case 'pushPorcelain':
130
+ return v.pushPorcelain(request.remote, request.refspec, request);
129
131
  case 'resetHard':
130
132
  return v.resetHard(request.rev);
131
133
  case 'clean':
package/dist/client.d.ts CHANGED
@@ -20,5 +20,5 @@ 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 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 { 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';
24
24
  export { asAsync, CommandFailed, runChecked, runCheckedAsync, spawnRunner, spawnRunnerAsync, type AsyncCommandRunner, type AsyncCommandRunOptions, type CommandResult, type CommandRunner, type CommandRunOptions, } from '@osdlc/command-seam';
package/dist/sync.d.ts CHANGED
@@ -18,7 +18,7 @@
18
18
  import { type CommandResult, type CommandRunner } from '@osdlc/command-seam';
19
19
  import { type Soft, type TriedSync } from './outcome.ts';
20
20
  import { type RemoteCoordinate } from './remote-url.ts';
21
- import { type AddOptions, type AheadBehind, type CommitOptions, type CheckoutOptions, type ConfigGetOptions, type CloneOptions, type ConflictSide, type MergeOptions, type MergeOutcome, type MergeTreeOptions, type MergeTreeOutcome, type RebaseOptions, type RebaseOutcome, type RemoteGetUrlOptions, type TaggedFile, type UnmergedEntry, type ConfigSetOptions, 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 NumstatEntry, type RemoteRef, type CleanOptions, type DiffCheckOptions, type DiffCheckResult, type StatusEntry, type StatusPorcelainOptions, type TreeEntry, type Worktree, type WorktreeMoveOptions } from './verbs.ts';
21
+ import { type AddOptions, type AheadBehind, type CommitOptions, type CheckoutOptions, type ConfigGetOptions, type CloneOptions, type ConflictSide, type MergeOptions, type MergeOutcome, type MergeTreeOptions, type MergeTreeOutcome, type RebaseOptions, type RebaseOutcome, type RemoteGetUrlOptions, type TaggedFile, type UnmergedEntry, type ConfigSetOptions, 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 NumstatEntry, type PushPorcelainOptions, type PushReport, type RemoteRef, type CleanOptions, type DiffCheckOptions, type DiffCheckResult, type StatusEntry, type StatusPorcelainOptions, type TreeEntry, type Worktree, type WorktreeMoveOptions } from './verbs.ts';
22
22
  /**
23
23
  * Per-call concerns that are not part of the operation itself.
24
24
  *
@@ -363,6 +363,13 @@ export declare class Git {
363
363
  push(remote: string, refspec: string, opts?: GitSyncCallOptions & {
364
364
  forceWithLease?: boolean | ForceLease | undefined;
365
365
  }): void;
366
+ /**
367
+ * `git push --porcelain`, read into one result per ref. A rejected ref comes
368
+ * back with a typed `rejection` rather than a throw; a failure that reaches
369
+ * no ref (an unknown remote, auth, network) still throws. See
370
+ * `pushPorcelain` in `verbs.ts`.
371
+ */
372
+ pushPorcelain(remote: string, refspec: string | string[], opts?: GitSyncCallOptions & PushPorcelainOptions): PushReport;
366
373
  /** `git clean -f`, plus `-d` with `directories`. Ignored files are kept. */
367
374
  clean(opts?: GitSyncCallOptions & CleanOptions): void;
368
375
  /** `git reset --hard <rev>`. */
package/dist/sync.js CHANGED
@@ -508,6 +508,15 @@ export class Git {
508
508
  push(remote, refspec, opts = {}) {
509
509
  this.exec(v.push(remote, refspec, opts), opts);
510
510
  }
511
+ /**
512
+ * `git push --porcelain`, read into one result per ref. A rejected ref comes
513
+ * back with a typed `rejection` rather than a throw; a failure that reaches
514
+ * no ref (an unknown remote, auth, network) still throws. See
515
+ * `pushPorcelain` in `verbs.ts`.
516
+ */
517
+ pushPorcelain(remote, refspec, opts = {}) {
518
+ return this.exec(v.pushPorcelain(remote, refspec, opts), opts);
519
+ }
511
520
  /** `git clean -f`, plus `-d` with `directories`. Ignored files are kept. */
512
521
  clean(opts = {}) {
513
522
  this.exec(v.clean(opts), opts);
package/dist/verbs.d.ts CHANGED
@@ -33,10 +33,10 @@ export interface GitVerb<T> {
33
33
  * 1 for a missing object. Those codes reach {@link GitVerb.parse}, which
34
34
  * turns them into the verb's absence value; any other non-zero exit throws.
35
35
  *
36
- * A mutation declares `[]`: nothing about a failed `push` is an answer
37
- * (`configRemoveSection` is the one exception). That
38
- * is the whole checked/unchecked distinction, so there is no `checked` flag
39
- * to contradict it.
36
+ * A mutation declares `[]`: nothing about a failed `push` is an answer,
37
+ * unless the verb declares a code whose failure is an answer (see its own
38
+ * `absent`). That is the whole checked/unchecked distinction, so there is
39
+ * no `checked` flag to contradict it.
40
40
  */
41
41
  absent: readonly number[];
42
42
  /**
@@ -997,6 +997,100 @@ export declare function forceWithLeaseArg(lease: ForceLease): string;
997
997
  export declare function push(remote: string, refspec: string, opts?: {
998
998
  forceWithLease?: boolean | ForceLease | undefined;
999
999
  }): GitVerb<void>;
1000
+ /** Options for {@link pushPorcelain}. */
1001
+ export interface PushPorcelainOptions {
1002
+ /**
1003
+ * `--force-with-lease`: `true` for the bare form, a {@link ForceLease}, or
1004
+ * one lease per ref for a multi-ref push. See {@link push} for why `true` is
1005
+ * the unsafe form. An empty list throws a `TypeError`.
1006
+ */
1007
+ forceWithLease?: boolean | ForceLease | ForceLease[] | undefined;
1008
+ /** `--atomic` — the remote updates every ref or none. */
1009
+ atomic?: boolean | undefined;
1010
+ }
1011
+ /**
1012
+ * The status character `git push --porcelain` prints for a ref: `' '`
1013
+ * fast-forward, `'+'` forced, `'-'` deleted, `'*'` new, `'!'` rejected, `'='`
1014
+ * up to date.
1015
+ */
1016
+ export type PushFlag = ' ' | '+' | '-' | '*' | '!' | '=';
1017
+ /**
1018
+ * Why a ref was rejected, read from git's reason text. The wording each value
1019
+ * comes from, by git version, is in the README section "Pushing: a rejected
1020
+ * ref is a value".
1021
+ *
1022
+ * - `stale`: the lease check failed before anything was sent.
1023
+ * - `non-fast-forward`: the push needs a force (`non-fast-forward`, `fetch
1024
+ * first`, `needs force`).
1025
+ * - `tag-exists`: the tag is there already. A retry fails the same way.
1026
+ * - `already-exists`: a create the remote lost to another writer.
1027
+ * - `ref-conflict`: the remote cannot hold this ref beside another, such as
1028
+ * `<ref>` beside `<ref>/child`. Nothing raced.
1029
+ * - `lock-failed`: another writer moved or deleted the ref at the remote
1030
+ * after the lease check passed.
1031
+ * - `hook-declined`: a remote hook refused the ref.
1032
+ * - `other`: anything else, kept in `rawReason` and `detail`. This includes
1033
+ * a lock file in the way, an unwritable refs directory, the collateral refs
1034
+ * of a failed `--atomic` push, and git's `new shallow roots not allowed`,
1035
+ * `remote does not support deleting refs` and `remote failed to report
1036
+ * status`.
1037
+ */
1038
+ export type PushRejection = 'stale' | 'non-fast-forward' | 'tag-exists' | 'already-exists' | 'ref-conflict' | 'lock-failed' | 'hook-declined' | 'other';
1039
+ /** The fields every ref line of `git push --porcelain` has. */
1040
+ interface PushRefFields {
1041
+ /** The local side as git printed it: a ref, `HEAD`, a sha, or `''` for a delete. */
1042
+ src: string;
1043
+ /** The remote ref. */
1044
+ dst: string;
1045
+ /** The summary without the reason: `[rejected]`, `[new branch]`, `abc..def`. */
1046
+ summary: string;
1047
+ /** The text in parentheses after the summary, or null when there is none. */
1048
+ rawReason: string | null;
1049
+ }
1050
+ /**
1051
+ * One ref line of `git push --porcelain`. A rejected ref (`flag: '!'`)
1052
+ * carries its `rejection` and `detail`; check `flag` and TypeScript knows
1053
+ * which you have.
1054
+ */
1055
+ export type PushRefResult = (PushRefFields & {
1056
+ flag: '!';
1057
+ rejection: PushRejection;
1058
+ /**
1059
+ * The remote's `cannot lock ref '<dst>': …` line for this ref, without
1060
+ * the `remote: error: ` prefix, or null when the remote printed none.
1061
+ * git prints it on stderr, apart from the ref line, and some versions
1062
+ * not at all. With several push URLs, a ref's lines are handed out in
1063
+ * the order the rejected refs appear.
1064
+ */
1065
+ detail: string | null;
1066
+ }) | (PushRefFields & {
1067
+ flag: Exclude<PushFlag, '!'>;
1068
+ rejection?: never;
1069
+ detail?: never;
1070
+ });
1071
+ /** What {@link pushPorcelain} returns. */
1072
+ export interface PushReport {
1073
+ /** One entry per ref line. A remote with several push URLs repeats its refs. */
1074
+ refs: PushRefResult[];
1075
+ /** git's stderr, for the remote's own messages, such as a hook's reason. */
1076
+ stderr: string;
1077
+ }
1078
+ /**
1079
+ * `git push --porcelain [--atomic] [--force-with-lease…] <remote> <refspec…>`,
1080
+ * read into one result per ref.
1081
+ *
1082
+ * A rejected ref is a value, not a throw. git exits 1 when any ref is
1083
+ * rejected, so exit 1 is declared absent, and the parse throws unless a ref
1084
+ * line says `!`. A local pre-push hook decline and a refspec that matches
1085
+ * nothing exit 1 with no ref lines, so they throw. So does every transport
1086
+ * failure (exit 128: an unknown remote, auth, network, TLS), as the
1087
+ * classified failure.
1088
+ *
1089
+ * Runs with `LC_ALL=C`, so the caller's locale does not change the reason
1090
+ * text. An empty refspec list throws a `TypeError`: git would push its
1091
+ * default set.
1092
+ */
1093
+ export declare function pushPorcelain(remote: string, refspec: string | string[], opts?: PushPorcelainOptions): GitVerb<PushReport>;
1000
1094
  /** `git reset --hard <rev>`. */
1001
1095
  export declare function resetHard(rev: string): GitVerb<void>;
1002
1096
  /** Options for {@link clean}. */
@@ -1229,3 +1323,4 @@ export interface CheckoutOptions {
1229
1323
  * not an absence.
1230
1324
  */
1231
1325
  export declare function checkout(ref: string, opts?: CheckoutOptions): GitVerb<void>;
1326
+ export {};
package/dist/verbs.js CHANGED
@@ -1297,18 +1297,156 @@ export function forceWithLeaseArg(lease) {
1297
1297
  * is overwritten. Pin the lease whenever the expected remote sha is known.
1298
1298
  */
1299
1299
  export function push(remote, refspec, opts = {}) {
1300
- const argv = ['push'];
1301
- const lease = opts.forceWithLease;
1302
- if (lease === true)
1303
- argv.push('--force-with-lease');
1304
- else if (typeof lease === 'object' && lease !== null)
1305
- argv.push(forceWithLeaseArg(lease));
1306
- else if (lease !== undefined && lease !== false) {
1307
- throw new Error(`force-with-lease: unsupported value ${JSON.stringify(lease)}`);
1308
- }
1300
+ const argv = ['push', ...forceWithLeaseArgs('push', opts.forceWithLease)];
1309
1301
  argv.push(positional('push', 'remote', remote), positional('push', 'refspec', refspec));
1310
1302
  return { argv, absent: NONE, parse: nothing };
1311
1303
  }
1304
+ /**
1305
+ * The `--force-with-lease` arguments for a `forceWithLease` option: none, the
1306
+ * bare flag, or one per pinned lease. An empty lease list throws a
1307
+ * `TypeError`: git would push with no lease at all.
1308
+ */
1309
+ function forceWithLeaseArgs(verb, lease) {
1310
+ if (lease === undefined || lease === false)
1311
+ return [];
1312
+ if (lease === true)
1313
+ return ['--force-with-lease'];
1314
+ if (Array.isArray(lease)) {
1315
+ if (lease.length === 0)
1316
+ throw new TypeError(`typed-git: ${verb}: forceWithLease list is empty`);
1317
+ return lease.map(forceWithLeaseArg);
1318
+ }
1319
+ if (typeof lease === 'object' && lease !== null)
1320
+ return [forceWithLeaseArg(lease)];
1321
+ throw new Error(`force-with-lease: unsupported value ${JSON.stringify(lease)}`);
1322
+ }
1323
+ /** `<flag>\t<src>:<dst>\t<summary>[ (<reason>)]` */
1324
+ const PUSH_REF_LINE = /^([ +\-*!=])\t([^\t]*)\t(.*)$/;
1325
+ /**
1326
+ * A remote's per-ref lock error on stderr. git pads the line with spaces to
1327
+ * clear progress output; it uses an escape code only on a terminal, which
1328
+ * captured stderr never is.
1329
+ */
1330
+ const LOCK_DETAIL = /^remote: (?:error: )?(cannot lock ref '([^']+)': .*?)\s*$/gm;
1331
+ /** git could not create the ref's lock file: one is in the way, or the directory is read-only. Not a race. */
1332
+ const LOCK_FILE = /unable to create '[^']*\.lock'/;
1333
+ /**
1334
+ * The rejection for a reason and its detail. Two rules hold it together.
1335
+ * It matches on text, never on the local git version, because a `[remote
1336
+ * rejected]` reason is written by the remote's git. And `failed to update
1337
+ * ref` alone is never a race: a ref clash, an unwritable refs directory and a
1338
+ * stale lock all end that way, so only the detail can say more. A host may
1339
+ * put the whole lock error in the reason, so the detail patterns are tried on
1340
+ * both. The wordings are listed in the README section "Pushing: a rejected
1341
+ * ref is a value" and tested in `CANNED` in `tests/push.test.ts`.
1342
+ */
1343
+ function pushRejection(reason, detail) {
1344
+ const r = (reason ?? '').toLowerCase();
1345
+ const d = (detail ?? '').toLowerCase();
1346
+ if (r === 'stale info' || r === 'remote ref updated since checkout')
1347
+ return 'stale';
1348
+ if (r === 'non-fast-forward' || r === 'fetch first' || r === 'needs force') {
1349
+ return 'non-fast-forward';
1350
+ }
1351
+ if (r === 'already exists')
1352
+ return 'tag-exists';
1353
+ if (r.includes('hook declined'))
1354
+ return 'hook-declined';
1355
+ if (r === 'refname conflict')
1356
+ return 'ref-conflict';
1357
+ if (r === 'incorrect old value provided' || r === 'reference does not exist') {
1358
+ return 'lock-failed';
1359
+ }
1360
+ const text = `${r}\n${d}`;
1361
+ if (LOCK_FILE.test(text))
1362
+ return 'other';
1363
+ if (/' exists; cannot create '/.test(text))
1364
+ return 'ref-conflict';
1365
+ if (text.includes(' but expected ') || text.includes('unable to resolve reference')) {
1366
+ return 'lock-failed';
1367
+ }
1368
+ if (text.includes('reference already exists'))
1369
+ return 'already-exists';
1370
+ return 'other';
1371
+ }
1372
+ /** Read `git push --porcelain` output into per-ref results. */
1373
+ function parsePushReport(stdout, stderr) {
1374
+ // Each dst's lock lines, in order: a remote with several push URLs prints
1375
+ // one per URL that rejected it.
1376
+ const details = new Map();
1377
+ for (const m of stderr.matchAll(LOCK_DETAIL)) {
1378
+ const queue = details.get(m[2]) ?? [];
1379
+ queue.push(m[1]);
1380
+ details.set(m[2], queue);
1381
+ }
1382
+ const refs = [];
1383
+ for (const line of stdout.split('\n')) {
1384
+ const m = PUSH_REF_LINE.exec(line.replace(/\r$/, ''));
1385
+ if (m === null)
1386
+ continue;
1387
+ const [, flag, pair, status] = m;
1388
+ // A ref name cannot hold `:`, so the first one splits the pair.
1389
+ const colon = pair.indexOf(':');
1390
+ const dst = pair.slice(colon + 1);
1391
+ // A summary never holds ` (`, so the first one opens the reason.
1392
+ const open = status.indexOf(' (');
1393
+ const hasReason = open >= 0 && status.endsWith(')');
1394
+ const rawReason = hasReason ? status.slice(open + 2, -1) : null;
1395
+ const fields = {
1396
+ src: pair.slice(0, colon),
1397
+ dst,
1398
+ summary: hasReason ? status.slice(0, open) : status,
1399
+ rawReason,
1400
+ };
1401
+ if (flag === '!') {
1402
+ const detail = details.get(dst)?.shift() ?? null;
1403
+ refs.push({ ...fields, flag, rejection: pushRejection(rawReason, detail), detail });
1404
+ }
1405
+ else {
1406
+ refs.push({ ...fields, flag });
1407
+ }
1408
+ }
1409
+ return { refs, stderr };
1410
+ }
1411
+ /**
1412
+ * `git push --porcelain [--atomic] [--force-with-lease…] <remote> <refspec…>`,
1413
+ * read into one result per ref.
1414
+ *
1415
+ * A rejected ref is a value, not a throw. git exits 1 when any ref is
1416
+ * rejected, so exit 1 is declared absent, and the parse throws unless a ref
1417
+ * line says `!`. A local pre-push hook decline and a refspec that matches
1418
+ * nothing exit 1 with no ref lines, so they throw. So does every transport
1419
+ * failure (exit 128: an unknown remote, auth, network, TLS), as the
1420
+ * classified failure.
1421
+ *
1422
+ * Runs with `LC_ALL=C`, so the caller's locale does not change the reason
1423
+ * text. An empty refspec list throws a `TypeError`: git would push its
1424
+ * default set.
1425
+ */
1426
+ export function pushPorcelain(remote, refspec, opts = {}) {
1427
+ const specs = typeof refspec === 'string' ? [refspec] : refspec;
1428
+ if (specs.length === 0)
1429
+ throw new TypeError('typed-git: pushPorcelain: refspec list is empty');
1430
+ const argv = ['push', '--porcelain'];
1431
+ if (opts.atomic)
1432
+ argv.push('--atomic');
1433
+ argv.push(...forceWithLeaseArgs('pushPorcelain', opts.forceWithLease));
1434
+ argv.push(positional('pushPorcelain', 'remote', remote));
1435
+ for (const spec of specs)
1436
+ argv.push(positional('pushPorcelain', 'refspec', spec));
1437
+ return {
1438
+ argv,
1439
+ env: C_LOCALE,
1440
+ absent: [1],
1441
+ parse(r, ranArgv) {
1442
+ const report = parsePushReport(r.stdout, r.stderr);
1443
+ if (r.exitCode !== 0 && !report.refs.some((ref) => ref.flag === '!')) {
1444
+ throw new CommandFailed(ranArgv, r);
1445
+ }
1446
+ return report;
1447
+ },
1448
+ };
1449
+ }
1312
1450
  /** `git reset --hard <rev>`. */
1313
1451
  export function resetHard(rev) {
1314
1452
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@osdlc/typed-git",
3
- "version": "0.7.1",
3
+ "version": "0.8.0",
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.10.0",
55
+ "@osdlc/command-seam": "^0.11.0",
56
56
  "@osdlc/result": "^0.1.0"
57
57
  },
58
58
  "devDependencies": {