@statewalker/vcs-commands 0.3.2 → 0.5.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.
Files changed (133) hide show
  1. package/README.md +19 -0
  2. package/dist/commands/add-command.d.ts +0 -6
  3. package/dist/commands/add-command.d.ts.map +1 -1
  4. package/dist/commands/blame-command.d.ts +14 -0
  5. package/dist/commands/blame-command.d.ts.map +1 -1
  6. package/dist/commands/branch-command.d.ts.map +1 -1
  7. package/dist/commands/checkout-command.d.ts +7 -24
  8. package/dist/commands/checkout-command.d.ts.map +1 -1
  9. package/dist/commands/clean-command.d.ts +34 -4
  10. package/dist/commands/clean-command.d.ts.map +1 -1
  11. package/dist/commands/clone-command.d.ts +61 -21
  12. package/dist/commands/clone-command.d.ts.map +1 -1
  13. package/dist/commands/core-config.d.ts +16 -0
  14. package/dist/commands/core-config.d.ts.map +1 -0
  15. package/dist/commands/fetch-command.d.ts +104 -37
  16. package/dist/commands/fetch-command.d.ts.map +1 -1
  17. package/dist/commands/index.d.ts +1 -0
  18. package/dist/commands/index.d.ts.map +1 -1
  19. package/dist/commands/index.js +2 -2
  20. package/dist/commands/init-command.d.ts.map +1 -1
  21. package/dist/commands/merge-command.d.ts +15 -2
  22. package/dist/commands/merge-command.d.ts.map +1 -1
  23. package/dist/commands/push-command.d.ts +58 -25
  24. package/dist/commands/push-command.d.ts.map +1 -1
  25. package/dist/commands/remote-command.d.ts +115 -6
  26. package/dist/commands/remote-command.d.ts.map +1 -1
  27. package/dist/commands/reset-command.d.ts.map +1 -1
  28. package/dist/commands/stash-apply-command.d.ts +35 -13
  29. package/dist/commands/stash-apply-command.d.ts.map +1 -1
  30. package/dist/commands/stash-create-command.d.ts +59 -25
  31. package/dist/commands/stash-create-command.d.ts.map +1 -1
  32. package/dist/commands/stash-drop-command.d.ts +8 -2
  33. package/dist/commands/stash-drop-command.d.ts.map +1 -1
  34. package/dist/commands/stash-list-command.d.ts +2 -4
  35. package/dist/commands/stash-list-command.d.ts.map +1 -1
  36. package/dist/commands/stash-working-tree.d.ts +72 -0
  37. package/dist/commands/stash-working-tree.d.ts.map +1 -0
  38. package/dist/commands/status-command.d.ts +29 -22
  39. package/dist/commands/status-command.d.ts.map +1 -1
  40. package/dist/commands/tag-command.d.ts.map +1 -1
  41. package/dist/commands/tree-restore.d.ts +52 -5
  42. package/dist/commands/tree-restore.d.ts.map +1 -1
  43. package/dist/commands/worktree-overwrite-checks.d.ts +64 -0
  44. package/dist/commands/worktree-overwrite-checks.d.ts.map +1 -0
  45. package/dist/{commands-COO4tJhv.js → commands-CsLNyvZ1.js} +3370 -1057
  46. package/dist/core-commands/add.command.impl.d.ts +0 -4
  47. package/dist/core-commands/add.command.impl.d.ts.map +1 -1
  48. package/dist/core-commands/index.d.ts +1 -3
  49. package/dist/core-commands/index.d.ts.map +1 -1
  50. package/dist/core-commands/store-worktree-file.d.ts +6 -0
  51. package/dist/core-commands/store-worktree-file.d.ts.map +1 -0
  52. package/dist/errors/checkout-errors.d.ts +13 -0
  53. package/dist/errors/checkout-errors.d.ts.map +1 -1
  54. package/dist/errors/index.js +18 -1
  55. package/dist/git-command.d.ts +10 -1
  56. package/dist/git-command.d.ts.map +1 -1
  57. package/dist/git.d.ts +21 -3
  58. package/dist/git.d.ts.map +1 -1
  59. package/dist/index.js +4 -4
  60. package/dist/remote-config/index.d.ts +1 -0
  61. package/dist/remote-config/index.d.ts.map +1 -1
  62. package/dist/remote-config/remote-config-store.d.ts +22 -0
  63. package/dist/remote-config/remote-config-store.d.ts.map +1 -1
  64. package/dist/remote-config/remote-refs.d.ts +37 -0
  65. package/dist/remote-config/remote-refs.d.ts.map +1 -0
  66. package/dist/results/clone-result.d.ts +6 -0
  67. package/dist/results/clone-result.d.ts.map +1 -1
  68. package/dist/results/diff-formatter.d.ts +14 -7
  69. package/dist/results/diff-formatter.d.ts.map +1 -1
  70. package/dist/results/fetch-result.d.ts +16 -1
  71. package/dist/results/fetch-result.d.ts.map +1 -1
  72. package/dist/results/index.js +28 -23
  73. package/dist/results/push-result.d.ts +9 -2
  74. package/dist/results/push-result.d.ts.map +1 -1
  75. package/dist/results/status-result.d.ts +91 -20
  76. package/dist/results/status-result.d.ts.map +1 -1
  77. package/dist/{status-result-BwAyxq6R.js → status-result-BpyUK1Sg.js} +115 -5
  78. package/dist/transport-command.d.ts +12 -0
  79. package/dist/transport-command.d.ts.map +1 -1
  80. package/package.json +14 -12
  81. package/src/commands/add-command.ts +23 -30
  82. package/src/commands/blame-command.ts +41 -0
  83. package/src/commands/branch-command.ts +2 -53
  84. package/src/commands/checkout-command.ts +205 -127
  85. package/src/commands/clean-command.ts +187 -81
  86. package/src/commands/clone-command.ts +334 -137
  87. package/src/commands/core-config.ts +41 -0
  88. package/src/commands/fetch-command.ts +536 -211
  89. package/src/commands/gc-command.ts +1 -1
  90. package/src/commands/index.ts +1 -0
  91. package/src/commands/init-command.ts +108 -11
  92. package/src/commands/merge-command.ts +60 -27
  93. package/src/commands/pack-refs-command.ts +2 -2
  94. package/src/commands/push-command.ts +242 -308
  95. package/src/commands/reflog-command.ts +2 -2
  96. package/src/commands/remote-command.ts +429 -19
  97. package/src/commands/reset-command.ts +18 -5
  98. package/src/commands/stash-apply-command.ts +632 -97
  99. package/src/commands/stash-create-command.ts +142 -62
  100. package/src/commands/stash-drop-command.ts +53 -5
  101. package/src/commands/stash-list-command.ts +10 -4
  102. package/src/commands/stash-working-tree.ts +243 -0
  103. package/src/commands/status-command.ts +197 -91
  104. package/src/commands/tag-command.ts +2 -53
  105. package/src/commands/tree-restore.ts +143 -18
  106. package/src/commands/worktree-overwrite-checks.ts +215 -0
  107. package/src/core-commands/add.command.impl.ts +15 -20
  108. package/src/core-commands/index.ts +1 -8
  109. package/src/core-commands/store-worktree-file.ts +5 -0
  110. package/src/errors/checkout-errors.ts +20 -0
  111. package/src/git-command.ts +42 -1
  112. package/src/git.ts +30 -2
  113. package/src/remote-config/index.ts +1 -0
  114. package/src/remote-config/remote-config-store.ts +95 -8
  115. package/src/remote-config/remote-refs.ts +103 -0
  116. package/src/results/clone-result.ts +6 -0
  117. package/src/results/diff-formatter.ts +31 -38
  118. package/src/results/fetch-result.ts +16 -1
  119. package/src/results/push-result.ts +9 -2
  120. package/src/results/status-result.ts +212 -29
  121. package/src/transport-command.ts +18 -0
  122. package/dist/core-commands/checkout.command.d.ts +0 -103
  123. package/dist/core-commands/checkout.command.d.ts.map +0 -1
  124. package/dist/core-commands/checkout.command.impl.d.ts +0 -114
  125. package/dist/core-commands/checkout.command.impl.d.ts.map +0 -1
  126. package/dist/pack-import/index.d.ts +0 -8
  127. package/dist/pack-import/index.d.ts.map +0 -1
  128. package/dist/pack-import/pack-import.d.ts +0 -11
  129. package/dist/pack-import/pack-import.d.ts.map +0 -1
  130. package/src/core-commands/checkout.command.impl.ts +0 -586
  131. package/src/core-commands/checkout.command.ts +0 -125
  132. package/src/pack-import/index.ts +0 -8
  133. package/src/pack-import/pack-import.ts +0 -24
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Multi-ref writes of the remote commands (`git remote remove`, `git remote rename`,
3
+ * `git fetch --prune`), as one ref batch where the store can apply it.
4
+ *
5
+ * Internal to the package.
6
+ */
7
+
8
+ import { isSymbolicRef, type OwnReflogLine, type Refs } from "@statewalker/vcs-core";
9
+
10
+ /** One ref of a {@link moveRefs}: where it goes and the reflog it takes along. */
11
+ export interface RefMove {
12
+ from: string;
13
+ to: string;
14
+ /** The reflog lines of the new name, oldest first (git carries the old log over) */
15
+ reflog?: OwnReflogLine[];
16
+ }
17
+
18
+ /**
19
+ * Deletes `names` with their reflogs: the refs holding an object id in one atomic batch
20
+ * (logged `message` where the store logs deletes), symbolic refs themselves (not their
21
+ * targets) one by one, as git deletes with REF_NO_DEREF. A store that cannot batch several
22
+ * refs (`unsupported`) deletes them one by one.
23
+ *
24
+ * @throws Error naming the refs when the batch is refused (nothing deleted then)
25
+ */
26
+ export async function deleteRefs(refs: Refs, names: string[], message: string): Promise<void> {
27
+ const direct: string[] = [];
28
+ const symbolic: string[] = [];
29
+ for (const name of names) {
30
+ const ref = await refs.get(name);
31
+ if (!ref) continue;
32
+ (isSymbolicRef(ref) ? symbolic : direct).push(name);
33
+ }
34
+ if (direct.length > 0) {
35
+ const result = await refs.batch(
36
+ direct.map((name) => ({ name, new: null })),
37
+ { message },
38
+ );
39
+ if (!result.ok) {
40
+ if (!result.rejected.every((r) => r.reason === "unsupported")) throw refused(result);
41
+ for (const name of direct) await refs.remove(name);
42
+ }
43
+ }
44
+ for (const name of symbolic) await refs.remove(name);
45
+ }
46
+
47
+ /**
48
+ * Renames refs, as `git remote rename` moves `refs/remotes/<old>/*`: the refs holding an
49
+ * object id are deleted and created under their new names in one atomic batch, each new
50
+ * name with the reflog lines given (the old log, carried over); symbolic refs are then
51
+ * re-created under their new names pointing at `symbolicTarget(old target)`. A store whose
52
+ * batch refuses several refs (`unsupported`: vcs-core's interim `kvStoreRefs`, which keeps
53
+ * no reflogs) moves them one by one: each new name is created only if it does not exist
54
+ * (compare-and-swap) before the old one goes, so no ref is overwritten or lost.
55
+ *
56
+ * @throws Error naming the refs when the batch is refused (a name conflict: nothing moved),
57
+ * or naming the ref whose new name exists in the one-by-one move (the refs before it moved)
58
+ */
59
+ export async function moveRefs(
60
+ refs: Refs,
61
+ moves: RefMove[],
62
+ symbolicTarget: (target: string) => string,
63
+ ): Promise<void> {
64
+ const direct: { move: RefMove; id: string }[] = [];
65
+ const symbolic: { move: RefMove; target: string }[] = [];
66
+ for (const move of moves) {
67
+ const ref = await refs.get(move.from);
68
+ if (!ref) continue;
69
+ if (isSymbolicRef(ref)) symbolic.push({ move, target: ref.target });
70
+ else if (ref.objectId) direct.push({ move, id: ref.objectId });
71
+ }
72
+ if (direct.length > 0) {
73
+ const commands = [
74
+ ...direct.map(({ move, id }) => ({ name: move.from, old: id, new: null })),
75
+ ...direct.map(({ move, id }) => ({
76
+ name: move.to,
77
+ old: null,
78
+ new: id,
79
+ ...(move.reflog ? { reflog: move.reflog } : {}),
80
+ })),
81
+ ];
82
+ const result = await refs.batch(commands);
83
+ if (!result.ok) {
84
+ if (!result.rejected.every((r) => r.reason === "unsupported")) throw refused(result);
85
+ for (const { move, id } of direct) {
86
+ if (!(await refs.compareAndSwap(move.to, undefined, id)).success) {
87
+ throw new Error(`Cannot update refs: ${move.to} exists`);
88
+ }
89
+ await refs.remove(move.from);
90
+ }
91
+ }
92
+ }
93
+ for (const { move, target } of symbolic) {
94
+ if (await refs.has(move.to)) throw new Error(`Cannot update refs: ${move.to} exists`);
95
+ await refs.setSymbolic(move.to, symbolicTarget(target));
96
+ await refs.remove(move.from);
97
+ }
98
+ }
99
+
100
+ function refused(result: { rejected: { name: string; reason: string }[] }): Error {
101
+ const why = result.rejected.map((r) => `${r.name}: ${r.reason}`).join(", ");
102
+ return new Error(`Cannot update refs: ${why}`);
103
+ }
@@ -22,4 +22,10 @@ export interface CloneResult {
22
22
  bare: boolean;
23
23
  /** Head commit after clone */
24
24
  headCommit?: ObjectId;
25
+ /**
26
+ * Files of the checked-out tree whose paths differ only in case (`README`, `readme`),
27
+ * on a worktree that folds case (`core.ignorecase`): only one of each group is in the
28
+ * worktree, as with git's "the following paths have collided" warning.
29
+ */
30
+ collidedPaths?: string[];
25
31
  }
@@ -4,7 +4,7 @@
4
4
  * Based on JGit's DiffFormatter class.
5
5
  */
6
6
 
7
- import type { Blobs, ObjectId } from "@statewalker/vcs-core";
7
+ import { type Blobs, DEFAULT_BIG_FILE_THRESHOLD, probeBlob } from "@statewalker/vcs-core";
8
8
  import {
9
9
  DEFAULT_ALGORITHM,
10
10
  type DiffAlgorithm,
@@ -31,6 +31,11 @@ export interface DiffFormatterOptions {
31
31
  abbreviationLength?: number;
32
32
  /** Diff algorithm to use (default: histogram) */
33
33
  algorithm?: SupportedAlgorithm;
34
+ /**
35
+ * Files larger than this are binary: they show as "Binary files differ" and are
36
+ * never loaded (git's `core.bigFileThreshold`). Default 50 MiB.
37
+ */
38
+ bigFileThreshold?: number;
34
39
  }
35
40
 
36
41
  /**
@@ -67,9 +72,9 @@ export interface FileContentDiff {
67
72
  indexLine?: string;
68
73
  /** Hunks of changes */
69
74
  hunks: DiffHunk[];
70
- /** Raw old content (for binary display or further processing) */
75
+ /** Raw old content of a text file (binary files are not loaded) */
71
76
  oldContent?: Uint8Array;
72
- /** Raw new content (for binary display or further processing) */
77
+ /** Raw new content of a text file (binary files are not loaded) */
73
78
  newContent?: Uint8Array;
74
79
  }
75
80
 
@@ -96,6 +101,7 @@ export class DiffFormatter {
96
101
  private abbreviateIds: boolean;
97
102
  private abbreviationLength: number;
98
103
  private diffAlgorithm: DiffAlgorithm;
104
+ private bigFileThreshold: number;
99
105
 
100
106
  constructor(
101
107
  private readonly blobs: Blobs,
@@ -106,23 +112,31 @@ export class DiffFormatter {
106
112
  this.abbreviateIds = options.abbreviateIds ?? true;
107
113
  this.abbreviationLength = options.abbreviationLength ?? 7;
108
114
  this.diffAlgorithm = getAlgorithm(options.algorithm ?? DEFAULT_ALGORITHM);
115
+ this.bigFileThreshold = options.bigFileThreshold ?? DEFAULT_BIG_FILE_THRESHOLD;
109
116
  }
110
117
 
111
118
  /**
112
119
  * Format a DiffEntry into a content diff.
113
120
  *
121
+ * Each side is probed first (its size, and a NUL byte in its first 8000
122
+ * bytes, as git checks). A side over `bigFileThreshold` or binary makes the
123
+ * entry binary, and then the other side is not loaded. Text sides are loaded
124
+ * whole, as the diff algorithms need them, by the same single read as the probe.
125
+ *
114
126
  * @param entry The diff entry to format
115
127
  * @returns Content diff with hunks
116
128
  */
117
129
  async format(entry: DiffEntry): Promise<FileContentDiff> {
118
- // Load content for old and new
119
- const oldContent = entry.oldId ? await this.loadContent(entry.oldId) : null;
120
- const newContent = entry.newId ? await this.loadContent(entry.newId) : null;
130
+ // The probe of a text side reads it whole, once; a binary side only to 8000 bytes
131
+ const options = { bigFileThreshold: this.bigFileThreshold, loadText: true };
132
+ const oldProbe = entry.oldId ? await probeBlob(this.blobs, entry.oldId, options) : null;
133
+ const newProbe =
134
+ !oldProbe?.binary && entry.newId ? await probeBlob(this.blobs, entry.newId, options) : null;
135
+ const isBinary = (oldProbe?.binary ?? false) || (newProbe?.binary ?? false);
121
136
 
122
- // Check for binary content
123
- const isBinary =
124
- (oldContent !== null && RawText.isBinary(oldContent)) ||
125
- (newContent !== null && RawText.isBinary(newContent));
137
+ // Text only: binary and big files are never loaded
138
+ const oldContent = !isBinary ? (oldProbe?.content ?? null) : null;
139
+ const newContent = !isBinary ? (newProbe?.content ?? null) : null;
126
140
 
127
141
  // Build headers
128
142
  const result: FileContentDiff = {
@@ -180,9 +194,13 @@ export class DiffFormatter {
180
194
  }
181
195
 
182
196
  if (diff.isBinary) {
183
- lines.push(
184
- `Binary files ${diff.entry.oldPath ?? "/dev/null"} and ${diff.entry.newPath ?? "/dev/null"} differ`,
185
- );
197
+ // git's wording: a/ and b/ prefixes, /dev/null for a side that does not exist
198
+ const e = diff.entry;
199
+ const oldName =
200
+ e.changeType === ChangeType.ADD || !e.oldPath ? "/dev/null" : `a/${e.oldPath}`;
201
+ const newName =
202
+ e.changeType === ChangeType.DELETE || !e.newPath ? "/dev/null" : `b/${e.newPath}`;
203
+ lines.push(`Binary files ${oldName} and ${newName} differ`);
186
204
  return lines.join("\n");
187
205
  }
188
206
 
@@ -220,31 +238,6 @@ export class DiffFormatter {
220
238
  return parts.join("\n");
221
239
  }
222
240
 
223
- /**
224
- * Load blob content from storage.
225
- */
226
- private async loadContent(objectId: ObjectId): Promise<Uint8Array> {
227
- const content = await this.blobs.load(objectId);
228
- if (!content) {
229
- throw new Error(`Blob not found: ${objectId}`);
230
- }
231
- const chunks: Uint8Array[] = [];
232
- for await (const chunk of content) {
233
- chunks.push(chunk);
234
- }
235
-
236
- // Combine chunks
237
- const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
238
- const result = new Uint8Array(totalLength);
239
- let offset = 0;
240
- for (const chunk of chunks) {
241
- result.set(chunk, offset);
242
- offset += chunk.length;
243
- }
244
-
245
- return result;
246
- }
247
-
248
241
  /**
249
242
  * Build the diff header line.
250
243
  */
@@ -16,6 +16,13 @@ export interface TrackingRefUpdate {
16
16
  newObjectId: ObjectId;
17
17
  /** Update result status */
18
18
  status: RefUpdateStatus;
19
+ /**
20
+ * How git prints the update: `[new branch]`, `[new tag]`, `abc1234..def5678` (fast-forward),
21
+ * `+ abc1234...def5678` (forced), `[rejected]`, `[up to date]`
22
+ */
23
+ summary?: string;
24
+ /** Why a ref was rejected (`non-fast-forward`, `would clobber existing tag`, a lock failure) */
25
+ reason?: string;
19
26
  }
20
27
 
21
28
  /**
@@ -65,8 +72,16 @@ export interface FetchResult {
65
72
  bytesReceived: number;
66
73
  /** Whether the remote repository was empty */
67
74
  isEmpty: boolean;
68
- /** Messages from the remote */
75
+ /**
76
+ * Messages as git prints them: the `followRemoteHEAD=warn` warning and its hint lines,
77
+ * the symbolic refs a prune left dangling
78
+ */
69
79
  messages: string[];
80
+ /**
81
+ * What failed without stopping the fetch (a refused prune), where git reports an error
82
+ * and exits 1; absent when nothing failed
83
+ */
84
+ errors?: string[];
70
85
  /** Submodule fetch results (if any) */
71
86
  submodules?: Map<string, FetchResult>;
72
87
  }
@@ -10,6 +10,8 @@ export enum PushStatus {
10
10
  OK = "ok",
11
11
  /** Update was rejected (not fast-forward) */
12
12
  REJECTED_NONFASTFORWARD = "rejected-nonfastforward",
13
+ /** Update was rejected: the remote ref no longer has the leased value (`--force-with-lease`) */
14
+ REJECTED_REMOTE_CHANGED = "rejected-remote-changed",
13
15
  /** Update was rejected (other reason) */
14
16
  REJECTED_OTHER = "rejected-other",
15
17
  /** Update failed (remote error) */
@@ -38,9 +40,14 @@ export interface RemoteRefUpdate {
38
40
  newObjectId: ObjectId;
39
41
  /** Status of the update */
40
42
  status: PushStatus;
41
- /** Message from server (if any) */
43
+ /** Why the update was refused: the server's reason, or git's status column */
42
44
  message?: string;
43
- /** Whether this was a forced update */
45
+ /**
46
+ * git's status column (`[new branch]`, `abc1234..def5678`, `[rejected] (fetch first)`,
47
+ * `[remote rejected] (hook declined)`, …)
48
+ */
49
+ summary?: string;
50
+ /** Whether the update was allowed to be a non-fast-forward (`+`, setForce, a lease that held) */
44
51
  forceUpdate: boolean;
45
52
  /** Whether this was a delete operation */
46
53
  delete: boolean;
@@ -1,65 +1,248 @@
1
+ import type { ObjectId } from "@statewalker/vcs-core";
2
+ import type { StageStateValue } from "@statewalker/vcs-working-tree";
3
+
4
+ /**
5
+ * One column of `git status --porcelain`: `X` (the index against HEAD) or `Y` (the
6
+ * worktree against the index). `" "` unchanged, `M` modified, `T` type changed, `A` added,
7
+ * `D` deleted, `U` unmerged, `?` untracked, `!` ignored.
8
+ */
9
+ export type StatusCode = " " | "M" | "T" | "A" | "D" | "U" | "?" | "!";
10
+
11
+ /** A side of a path: its mode and object id. */
12
+ export interface StatusSide {
13
+ mode: number;
14
+ id: ObjectId;
15
+ }
16
+
1
17
  /**
2
- * Status of the staging area compared to HEAD.
18
+ * The status of one path, as a line of `git status --porcelain` describes it.
3
19
  *
4
- * This is a simplified version for repositories without working trees,
5
- * focusing on staged changes and conflicts.
20
+ * @example
21
+ * ```typescript
22
+ * const entry = status.files.find((f) => f.path === "a.txt");
23
+ * // { path: "a.txt", index: "M", worktree: " ", head: {...}, staged: {...} }
24
+ * ```
25
+ */
26
+ export interface StatusFileEntry {
27
+ path: string;
28
+ /** `X`: the index against HEAD (`U` for an unmerged path, `?`/`!` for untracked/ignored) */
29
+ index: StatusCode;
30
+ /** `Y`: the worktree against the index */
31
+ worktree: StatusCode;
32
+ /** The HEAD entry, if HEAD has the path */
33
+ head?: StatusSide;
34
+ /** The index entry (stage 0), if the index has the path */
35
+ staged?: StatusSide;
36
+ /** The mode git would stage for the worktree file, if there is one */
37
+ worktreeMode?: number;
38
+ /** A submodule whose checked-out commit differs from the index's (porcelain v2 `SC..`) */
39
+ submoduleCommitChanged?: boolean;
40
+ /** An unmerged path's stages 1-3 (base, ours, theirs) */
41
+ stages?: [StatusSide | undefined, StatusSide | undefined, StatusSide | undefined];
42
+ }
43
+
44
+ /**
45
+ * Status of the repository: the index against HEAD, and the worktree against the index, as
46
+ * `git status` reports them.
6
47
  *
7
- * Based on JGit's Status but without working tree operations.
48
+ * Based on JGit's Status.
8
49
  */
9
50
  export interface Status {
10
- /**
11
- * Files added to staging (not in HEAD).
12
- */
51
+ /** Files added to the index (not in HEAD). */
13
52
  readonly added: Set<string>;
14
-
15
- /**
16
- * Files modified in staging (different from HEAD).
17
- */
53
+ /** Files changed in the index (content, mode or type differs from HEAD). */
18
54
  readonly changed: Set<string>;
19
-
20
- /**
21
- * Files removed from staging (in HEAD but not in staging).
22
- */
55
+ /** Files removed from the index (in HEAD, not in the index). */
23
56
  readonly removed: Set<string>;
24
-
57
+ /** Files with merge conflicts (unmerged index entries). */
58
+ readonly conflicting: Set<string>;
59
+ /** The kind of each conflict (both modified, deleted by them, ...). */
60
+ readonly conflictingStageState: Map<string, StageStateValue>;
61
+ /** Tracked files whose worktree content, mode or type differs from the index. */
62
+ readonly modified: Set<string>;
63
+ /** Tracked files missing from the worktree. */
64
+ readonly missing: Set<string>;
65
+ /** Files the index does not track (a nested repository as `sub/`). */
66
+ readonly untracked: Set<string>;
67
+ /** Untracked files the ignore rules exclude (only with `setIgnored(true)`). */
68
+ readonly ignored: Set<string>;
25
69
  /**
26
- * Files with merge conflicts.
70
+ * Every path with a status, as the lines of `git status --porcelain`: a path HEAD has,
71
+ * the index removed and the worktree still holds appears twice (`D ` and `??`).
27
72
  */
28
- readonly conflicting: Set<string>;
73
+ readonly files: StatusFileEntry[];
29
74
 
30
75
  /**
31
- * Check if the staging area is clean (no changes, no conflicts).
76
+ * Whether there is nothing to report: no staged or unstaged change, no conflict and no
77
+ * untracked file (`git status`: "nothing to commit, working tree clean").
32
78
  */
33
79
  isClean(): boolean;
34
80
 
35
81
  /**
36
- * Check if there are uncommitted changes.
37
- * True if any files are added, changed, removed, or conflicting.
82
+ * Whether there are uncommitted changes to tracked files: staged, unstaged or conflicting
83
+ * (untracked files are not changes).
38
84
  */
39
85
  hasUncommittedChanges(): boolean;
40
86
  }
41
87
 
42
88
  /**
43
- * Implementation of Status interface.
89
+ * Implementation of the Status interface.
44
90
  */
45
91
  export class StatusImpl implements Status {
92
+ readonly modified: Set<string>;
93
+ readonly missing: Set<string>;
94
+ readonly untracked: Set<string>;
95
+ readonly ignored: Set<string>;
96
+ readonly conflictingStageState: Map<string, StageStateValue>;
97
+ readonly files: StatusFileEntry[];
98
+
46
99
  constructor(
47
100
  public readonly added: Set<string>,
48
101
  public readonly changed: Set<string>,
49
102
  public readonly removed: Set<string>,
50
103
  public readonly conflicting: Set<string>,
51
- ) {}
104
+ worktree: {
105
+ modified?: Set<string>;
106
+ missing?: Set<string>;
107
+ untracked?: Set<string>;
108
+ ignored?: Set<string>;
109
+ conflictingStageState?: Map<string, StageStateValue>;
110
+ files?: StatusFileEntry[];
111
+ } = {},
112
+ ) {
113
+ this.modified = worktree.modified ?? new Set();
114
+ this.missing = worktree.missing ?? new Set();
115
+ this.untracked = worktree.untracked ?? new Set();
116
+ this.ignored = worktree.ignored ?? new Set();
117
+ this.conflictingStageState = worktree.conflictingStageState ?? new Map();
118
+ this.files = worktree.files ?? [];
119
+ }
52
120
 
53
121
  isClean(): boolean {
122
+ return !this.hasUncommittedChanges() && this.untracked.size === 0;
123
+ }
124
+
125
+ hasUncommittedChanges(): boolean {
54
126
  return (
55
- this.added.size === 0 &&
56
- this.changed.size === 0 &&
57
- this.removed.size === 0 &&
58
- this.conflicting.size === 0
127
+ this.added.size > 0 ||
128
+ this.changed.size > 0 ||
129
+ this.removed.size > 0 ||
130
+ this.conflicting.size > 0 ||
131
+ this.modified.size > 0 ||
132
+ this.missing.size > 0
59
133
  );
60
134
  }
135
+ }
61
136
 
62
- hasUncommittedChanges(): boolean {
63
- return !this.isClean();
137
+ /** git's byte order of paths (UTF-8 code units, as `strcmp`). */
138
+ function comparePaths(a: string, b: string): number {
139
+ const ea = new TextEncoder().encode(a);
140
+ const eb = new TextEncoder().encode(b);
141
+ const n = Math.min(ea.length, eb.length);
142
+ for (let i = 0; i < n; i++) if (ea[i] !== eb[i]) return ea[i] - eb[i];
143
+ return ea.length - eb.length;
144
+ }
145
+
146
+ const ZERO_ID = "0".repeat(40);
147
+ const octal = (mode: number | undefined) => (mode ?? 0).toString(8).padStart(6, "0");
148
+
149
+ /**
150
+ * git's quoting of a path in status output (`core.quotePath`, on by default); porcelain v1
151
+ * quotes a path with a space too (`QUOTE_PATH_QUOTE_SP`), v2 does not.
152
+ */
153
+ function quotePath(path: string, quoteSpace = false): string {
154
+ const bytes = new TextEncoder().encode(path);
155
+ let needs = false;
156
+ let out = "";
157
+ for (const b of bytes) {
158
+ if (b === 0x22 || b === 0x5c) {
159
+ needs = true;
160
+ out += `\\${String.fromCharCode(b)}`;
161
+ } else if (b === 0x09) {
162
+ needs = true;
163
+ out += "\\t";
164
+ } else if (b === 0x0a) {
165
+ needs = true;
166
+ out += "\\n";
167
+ } else if (b === 0x20 && quoteSpace) {
168
+ needs = true;
169
+ out += " ";
170
+ } else if (b < 0x20 || b >= 0x7f) {
171
+ needs = true;
172
+ out += `\\${b.toString(8).padStart(3, "0")}`;
173
+ } else out += String.fromCharCode(b);
174
+ }
175
+ return needs ? `"${out}"` : path;
176
+ }
177
+
178
+ /**
179
+ * The status as `git status --porcelain` (v1) or `--porcelain=v2` prints it, with
180
+ * `--untracked-files=all` (and the ignored files when the status has them): the changed
181
+ * tracked paths first, then the untracked, then the ignored ones, each in git's path order.
182
+ * Renames are not detected (as `-c status.renames=false`).
183
+ *
184
+ * @example
185
+ * ```typescript
186
+ * formatStatusPorcelain(await git.status().call());
187
+ * // " M a.txt\nA b.txt\n?? new.txt\n"
188
+ * ```
189
+ */
190
+ export function formatStatusPorcelain(status: Status, version: 1 | 2 = 1): string {
191
+ const entries = status.files;
192
+ const tracked = entries
193
+ .filter((e) => e.index !== "?" && e.index !== "!")
194
+ .sort((a, b) => comparePaths(a.path, b.path));
195
+ const untracked = entries
196
+ .filter((e) => e.index === "?")
197
+ .sort((a, b) => comparePaths(a.path, b.path));
198
+ const ignored = entries
199
+ .filter((e) => e.index === "!")
200
+ .sort((a, b) => comparePaths(a.path, b.path));
201
+ const lines: string[] = [];
202
+ for (const e of tracked) {
203
+ const path = quotePath(e.path, version === 1);
204
+ if (version === 1) {
205
+ lines.push(`${e.index}${e.worktree} ${path}`);
206
+ continue;
207
+ }
208
+ const xy = `${e.index === " " ? "." : e.index}${e.worktree === " " ? "." : e.worktree}`;
209
+ const isSubmodule = e.staged?.mode === 0o160000 || e.head?.mode === 0o160000;
210
+ const sub = isSubmodule ? `S${e.submoduleCommitChanged ? "C" : "."}..` : "N...";
211
+ if (e.stages) {
212
+ const [s1, s2, s3] = e.stages;
213
+ lines.push(
214
+ [
215
+ "u",
216
+ xy,
217
+ sub,
218
+ octal(s1?.mode),
219
+ octal(s2?.mode),
220
+ octal(s3?.mode),
221
+ octal(e.worktreeMode),
222
+ s1?.id ?? ZERO_ID,
223
+ s2?.id ?? ZERO_ID,
224
+ s3?.id ?? ZERO_ID,
225
+ path,
226
+ ].join(" "),
227
+ );
228
+ continue;
229
+ }
230
+ lines.push(
231
+ [
232
+ "1",
233
+ xy,
234
+ sub,
235
+ octal(e.head?.mode),
236
+ octal(e.staged?.mode),
237
+ octal(e.worktreeMode),
238
+ e.head?.id ?? ZERO_ID,
239
+ e.staged?.id ?? ZERO_ID,
240
+ path,
241
+ ].join(" "),
242
+ );
64
243
  }
244
+ const mark = version === 1 ? ["??", "!!"] : ["?", "!"];
245
+ for (const e of untracked) lines.push(`${mark[0]} ${quotePath(e.path, version === 1)}`);
246
+ for (const e of ignored) lines.push(`${mark[1]} ${quotePath(e.path, version === 1)}`);
247
+ return lines.map((l) => `${l}\n`).join("");
65
248
  }
@@ -17,6 +17,8 @@ export interface TransportOptions {
17
17
  headers?: Record<string, string>;
18
18
  /** Request timeout in milliseconds */
19
19
  timeout?: number;
20
+ /** Gzip large fetch request bodies (default true, as git; see `setGzipRequests`) */
21
+ gzipRequests?: boolean;
20
22
  /** Progress callback */
21
23
  onProgress?: ProgressCallback;
22
24
  /** Raw progress message callback */
@@ -38,6 +40,8 @@ export abstract class TransportCommand<T> extends GitCommand<T> {
38
40
  protected timeout?: number;
39
41
  /** Custom HTTP headers */
40
42
  protected headers?: Record<string, string>;
43
+ /** Gzip large fetch request bodies (undefined: the transport's default, true) */
44
+ protected gzipRequests?: boolean;
41
45
  /** Progress callback */
42
46
  protected progressCallback?: ProgressCallback;
43
47
  /** Progress message callback */
@@ -77,6 +81,19 @@ export abstract class TransportCommand<T> extends GitCommand<T> {
77
81
  return this;
78
82
  }
79
83
 
84
+ /**
85
+ * Send large upload-pack request bodies (a fetch's have-batches over 1024 bytes) gzipped,
86
+ * with `Content-Encoding: gzip`, as git does (default true). Pass false for a browser behind
87
+ * a CORS proxy that does not allow that header (it is not CORS-safelisted).
88
+ *
89
+ * @param gzip Whether to gzip large request bodies
90
+ */
91
+ setGzipRequests(gzip: boolean): this {
92
+ this.checkCallable();
93
+ this.gzipRequests = gzip;
94
+ return this;
95
+ }
96
+
80
97
  /**
81
98
  * Set custom HTTP headers.
82
99
  *
@@ -118,6 +135,7 @@ export abstract class TransportCommand<T> extends GitCommand<T> {
118
135
  auth: this.credentials,
119
136
  headers: this.headers,
120
137
  timeout: this.timeout,
138
+ gzipRequests: this.gzipRequests,
121
139
  onProgress: this.progressCallback,
122
140
  onProgressMessage: this.progressMessageCallback,
123
141
  };