@catamorphic/git 0.1.0-alpha.42 → 0.1.0-alpha.44
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/checkout-remote-backend.d.ts.map +1 -1
- package/dist/fs-backend.d.ts +8 -0
- package/dist/fs-backend.d.ts.map +1 -1
- package/dist/fs-remote-backend.d.ts +43 -9
- package/dist/fs-remote-backend.d.ts.map +1 -1
- package/dist/git-objects.d.ts +77 -0
- package/dist/git-objects.d.ts.map +1 -0
- package/dist/git-sync.d.ts +16 -17
- package/dist/git-sync.d.ts.map +1 -1
- package/dist/index.d.ts +6 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3912 -3059
- package/dist/index.js.map +23 -21
- package/dist/native-git.d.ts +114 -2
- package/dist/native-git.d.ts.map +1 -1
- package/dist/native-project-repo.d.ts +40 -5
- package/dist/native-project-repo.d.ts.map +1 -1
- package/dist/network-sync.d.ts.map +1 -1
- package/dist/network.d.ts +14 -9
- package/dist/network.d.ts.map +1 -1
- package/dist/object-origin-cache.d.ts +86 -0
- package/dist/object-origin-cache.d.ts.map +1 -0
- package/dist/object-remote-backend.d.ts +64 -10
- package/dist/object-remote-backend.d.ts.map +1 -1
- package/dist/origin-draft.d.ts.map +1 -1
- package/dist/origin-objects.d.ts +7 -2
- package/dist/origin-objects.d.ts.map +1 -1
- package/dist/project-manager.d.ts +22 -0
- package/dist/project-manager.d.ts.map +1 -1
- package/dist/project-paths.d.ts +20 -0
- package/dist/project-paths.d.ts.map +1 -0
- package/dist/ref-names.d.ts +35 -0
- package/dist/ref-names.d.ts.map +1 -1
- package/dist/types.d.ts +37 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/workspace-checkout.d.ts +31 -0
- package/dist/workspace-checkout.d.ts.map +1 -0
- package/dist/workspace-mirror.d.ts +38 -5
- package/dist/workspace-mirror.d.ts.map +1 -1
- package/dist/workspace-save.d.ts +27 -2
- package/dist/workspace-save.d.ts.map +1 -1
- package/package.json +4 -4
- package/src/checkout-remote-backend.ts +77 -29
- package/src/fs-backend.ts +69 -7
- package/src/fs-remote-backend.ts +255 -133
- package/src/git-objects.ts +363 -0
- package/src/git-sync.ts +124 -453
- package/src/index.ts +17 -7
- package/src/native-git.ts +566 -25
- package/src/native-project-repo.ts +318 -99
- package/src/network-sync.ts +43 -35
- package/src/network.ts +177 -153
- package/src/object-origin-cache.ts +689 -0
- package/src/object-remote-backend.ts +277 -20
- package/src/origin-draft.ts +22 -15
- package/src/origin-objects.ts +21 -5
- package/src/project-manager.ts +261 -73
- package/src/project-paths.ts +142 -0
- package/src/ref-names.ts +56 -0
- package/src/types.ts +38 -4
- package/src/workspace-checkout.ts +192 -0
- package/src/workspace-mirror.ts +276 -68
- package/src/workspace-save.ts +99 -30
- package/dist/project-repo.d.ts +0 -81
- package/dist/project-repo.d.ts.map +0 -1
- package/src/project-repo.ts +0 -821
package/src/index.ts
CHANGED
|
@@ -2,18 +2,20 @@ export { CheckoutRemoteBackend } from "./checkout-remote-backend.js";
|
|
|
2
2
|
export { type FileReadOptions, readFileSnapshot } from "./file-reads.js";
|
|
3
3
|
export { FsBackend } from "./fs-backend.js";
|
|
4
4
|
export { FsOriginRepo, FsRemoteBackend } from "./fs-remote-backend.js";
|
|
5
|
-
export {
|
|
6
|
-
|
|
7
|
-
PushNotFastForwardError,
|
|
8
|
-
pull,
|
|
9
|
-
push,
|
|
10
|
-
} from "./git-sync.js";
|
|
5
|
+
export { OBJECT_MAX_BYTES, ObjectTooLargeError } from "./git-objects.js";
|
|
6
|
+
export { fetchRemote, PushNotFastForwardError, push } from "./git-sync.js";
|
|
11
7
|
export { InMemoryObjectStore } from "./in-memory-object-store.js";
|
|
12
8
|
export { migrateWorkflowToProject } from "./migrate-workflow.js";
|
|
13
9
|
export {
|
|
10
|
+
assertNativeGit,
|
|
14
11
|
discoverLocalFolder,
|
|
12
|
+
gitErrorText,
|
|
15
13
|
hasLocalGit,
|
|
14
|
+
initManagedRepository,
|
|
16
15
|
type LocalFolder,
|
|
16
|
+
markManagedRepository,
|
|
17
|
+
type NativeGitAuth,
|
|
18
|
+
NativeGitUnavailableError,
|
|
17
19
|
nativeGit,
|
|
18
20
|
} from "./native-git.js";
|
|
19
21
|
export { NativeProjectRepo } from "./native-project-repo.js";
|
|
@@ -71,7 +73,6 @@ export {
|
|
|
71
73
|
PROJECT_GITIGNORE,
|
|
72
74
|
ProjectManager,
|
|
73
75
|
} from "./project-manager.js";
|
|
74
|
-
export { ProjectRepoImpl } from "./project-repo.js";
|
|
75
76
|
export { RefMovedError } from "./ref-moved-error.js";
|
|
76
77
|
export {
|
|
77
78
|
assertValidRefName,
|
|
@@ -104,6 +105,13 @@ export type {
|
|
|
104
105
|
RepoStatus,
|
|
105
106
|
StorageBackend,
|
|
106
107
|
} from "./types.js";
|
|
108
|
+
export {
|
|
109
|
+
advertiseCheckout,
|
|
110
|
+
CHECKOUT_BRANCH,
|
|
111
|
+
type CheckoutSource,
|
|
112
|
+
openCheckoutSource,
|
|
113
|
+
serveCheckout,
|
|
114
|
+
} from "./workspace-checkout.js";
|
|
107
115
|
export {
|
|
108
116
|
type BaseMoveOutcome,
|
|
109
117
|
buildSeedPack,
|
|
@@ -114,11 +122,13 @@ export {
|
|
|
114
122
|
moveCheckoutBase,
|
|
115
123
|
parseWorkspaceRef,
|
|
116
124
|
seedPackInstallScript,
|
|
125
|
+
seedPackParts,
|
|
117
126
|
shellQuote,
|
|
118
127
|
unpinMirrorRef,
|
|
119
128
|
type WorkspaceBase,
|
|
120
129
|
} from "./workspace-mirror.js";
|
|
121
130
|
export {
|
|
131
|
+
assertHeldCommit,
|
|
122
132
|
assertSavedPath,
|
|
123
133
|
assertSavedTree,
|
|
124
134
|
parseSavedChanges,
|
package/src/native-git.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { execFile } from "node:child_process";
|
|
1
|
+
import { type ChildProcess, execFile, spawn } from "node:child_process";
|
|
2
2
|
import fs from "node:fs/promises";
|
|
3
|
+
import { devNull } from "node:os";
|
|
3
4
|
import path from "node:path";
|
|
4
5
|
import { promisify } from "node:util";
|
|
5
6
|
|
|
@@ -11,32 +12,321 @@ export interface NativeGitAuth {
|
|
|
11
12
|
password: string;
|
|
12
13
|
}
|
|
13
14
|
|
|
15
|
+
/** The oldest Git every command Work runs is known to work with. */
|
|
16
|
+
const MINIMUM_GIT = [2, 32] as const;
|
|
17
|
+
|
|
18
|
+
/** How long a command that moves a whole history may run. */
|
|
19
|
+
export const TRANSFER_TIMEOUT_MS = 2 * 60 * 60_000;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* How long a command that writes or reads a whole working tree may run: a
|
|
23
|
+
* large repository's files take minutes to write out, and a command killed
|
|
24
|
+
* part way leaves the tree half written.
|
|
25
|
+
*/
|
|
26
|
+
export const CHECKOUT_TIMEOUT_MS = 30 * 60_000;
|
|
27
|
+
|
|
28
|
+
/** The commands whose cost follows the size of the working tree. */
|
|
29
|
+
const WORKING_TREE_COMMANDS: ReadonlySet<string> = new Set([
|
|
30
|
+
"add",
|
|
31
|
+
"checkout",
|
|
32
|
+
"clean",
|
|
33
|
+
"commit",
|
|
34
|
+
"diff",
|
|
35
|
+
"grep",
|
|
36
|
+
"ls-files",
|
|
37
|
+
"merge",
|
|
38
|
+
"read-tree",
|
|
39
|
+
"rebase",
|
|
40
|
+
"reset",
|
|
41
|
+
"restore",
|
|
42
|
+
"stash",
|
|
43
|
+
"status",
|
|
44
|
+
]);
|
|
45
|
+
|
|
46
|
+
const NETWORK_COMMANDS: ReadonlySet<string> = new Set([
|
|
47
|
+
"fetch",
|
|
48
|
+
"push",
|
|
49
|
+
"clone",
|
|
50
|
+
"ls-remote",
|
|
51
|
+
]);
|
|
52
|
+
|
|
53
|
+
/** The Git command an argument list runs: the first that is not an option. */
|
|
54
|
+
function commandOf(args: readonly string[]): string {
|
|
55
|
+
return args.find((arg) => !arg.startsWith("-") && !arg.includes("=")) ?? "";
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** How long a command may run when its caller names no budget. */
|
|
59
|
+
function budgetFor(args: readonly string[]): number {
|
|
60
|
+
const command = commandOf(args);
|
|
61
|
+
return NETWORK_COMMANDS.has(command)
|
|
62
|
+
? 15 * 60_000
|
|
63
|
+
: WORKING_TREE_COMMANDS.has(command)
|
|
64
|
+
? CHECKOUT_TIMEOUT_MS
|
|
65
|
+
: 60_000;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Whether Git was stopped for running past its budget, not by its own error. */
|
|
69
|
+
export function wasStopped(error: unknown): boolean {
|
|
70
|
+
return (
|
|
71
|
+
error !== null &&
|
|
72
|
+
typeof error === "object" &&
|
|
73
|
+
(("killed" in error && error.killed === true) ||
|
|
74
|
+
("signal" in error &&
|
|
75
|
+
(error.signal === "SIGTERM" || error.signal === "SIGKILL")))
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The Git program is missing on this machine, or too old for Work. */
|
|
80
|
+
export class NativeGitUnavailableError extends Error {
|
|
81
|
+
constructor(message: string) {
|
|
82
|
+
super(message);
|
|
83
|
+
this.name = "NativeGitUnavailableError";
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function missingGit(): NativeGitUnavailableError {
|
|
88
|
+
return new NativeGitUnavailableError(
|
|
89
|
+
`Work keeps projects with the Git program, and none was found on this machine. Install Git ${MINIMUM_GIT.join(".")} or newer where Work runs, then try again.`,
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function isMissingProgram(error: unknown): boolean {
|
|
94
|
+
return (
|
|
95
|
+
error instanceof Error &&
|
|
96
|
+
"code" in error &&
|
|
97
|
+
error.code === "ENOENT" &&
|
|
98
|
+
"syscall" in error &&
|
|
99
|
+
String(error.syscall).startsWith("spawn")
|
|
100
|
+
);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Check that this machine has a Git that Work can use, and say which. A
|
|
105
|
+
* host calls it once at startup so a missing or old Git stops the start
|
|
106
|
+
* with a plain reason instead of failing the first project operation.
|
|
107
|
+
*/
|
|
108
|
+
export async function assertNativeGit(): Promise<{ version: string }> {
|
|
109
|
+
const output = await execute("git", ["--version"], { timeout: 30_000 }).then(
|
|
110
|
+
(result) => result.stdout,
|
|
111
|
+
(error: unknown) => {
|
|
112
|
+
throw isMissingProgram(error) ? missingGit() : error;
|
|
113
|
+
},
|
|
114
|
+
);
|
|
115
|
+
const found = /(\d+)\.(\d+)(?:\.(\d+))?/.exec(output);
|
|
116
|
+
const version = found?.[0] ?? output.trim();
|
|
117
|
+
const major = Number(found?.[1] ?? 0);
|
|
118
|
+
const minor = Number(found?.[2] ?? 0);
|
|
119
|
+
if (
|
|
120
|
+
major < MINIMUM_GIT[0] ||
|
|
121
|
+
(major === MINIMUM_GIT[0] && minor < MINIMUM_GIT[1])
|
|
122
|
+
)
|
|
123
|
+
throw new NativeGitUnavailableError(
|
|
124
|
+
`Work needs Git ${MINIMUM_GIT.join(".")} or newer, and this machine has Git ${version}. Update Git where Work runs, then try again.`,
|
|
125
|
+
);
|
|
126
|
+
return { version };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* The file that marks a repository as one Work made and manages: a chat's
|
|
131
|
+
* copy, a project's own copy, a bare origin, a mirror, a cache, a scratch
|
|
132
|
+
* repository. It sits in the Git directory, which no sandbox mounts.
|
|
133
|
+
*/
|
|
134
|
+
const MANAGED_MARKER = "work-managed";
|
|
135
|
+
|
|
136
|
+
const exists = (file: string) =>
|
|
137
|
+
fs.access(file).then(
|
|
138
|
+
() => true,
|
|
139
|
+
() => false,
|
|
140
|
+
);
|
|
141
|
+
|
|
142
|
+
/** Whether the repository at `repoPath` is one Work manages. */
|
|
143
|
+
export async function isManagedRepository(repoPath: string): Promise<boolean> {
|
|
144
|
+
return (
|
|
145
|
+
(await exists(path.join(repoPath, ".git", MANAGED_MARKER))) ||
|
|
146
|
+
(await exists(path.join(repoPath, MANAGED_MARKER)))
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Mark the repository at `repoPath` as one Work manages, so every Git
|
|
152
|
+
* command there runs with the environment Work builds for it and none of
|
|
153
|
+
* the service account's. Nothing is written where there is no repository.
|
|
154
|
+
* Never call it on a person's own folder.
|
|
155
|
+
*/
|
|
156
|
+
export async function markManagedRepository(repoPath: string): Promise<void> {
|
|
157
|
+
const worktree = path.join(repoPath, ".git");
|
|
158
|
+
const gitdir = (await fs.stat(worktree).catch(() => null))?.isDirectory()
|
|
159
|
+
? worktree
|
|
160
|
+
: (await exists(path.join(repoPath, "HEAD"))) &&
|
|
161
|
+
(await exists(path.join(repoPath, "objects")))
|
|
162
|
+
? repoPath
|
|
163
|
+
: null;
|
|
164
|
+
if (!gitdir) return;
|
|
165
|
+
const marker = path.join(gitdir, MANAGED_MARKER);
|
|
166
|
+
if (!(await exists(marker))) await fs.writeFile(marker, "");
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* What a managed repository's Git may inherit from the process that runs
|
|
171
|
+
* Work: where programs and temporary files are, the locale, and how to
|
|
172
|
+
* reach the network. Nothing named `GIT_*` beyond the two that only name
|
|
173
|
+
* certificate files, so no inherited variable can point Git at another
|
|
174
|
+
* repository, configuration, editor, or helper.
|
|
175
|
+
*/
|
|
176
|
+
const INHERITED = [
|
|
177
|
+
"PATH",
|
|
178
|
+
"HOME",
|
|
179
|
+
"TMPDIR",
|
|
180
|
+
"TMP",
|
|
181
|
+
"TEMP",
|
|
182
|
+
"SYSTEMROOT",
|
|
183
|
+
"LANG",
|
|
184
|
+
"LC_ALL",
|
|
185
|
+
"LC_CTYPE",
|
|
186
|
+
"SSL_CERT_FILE",
|
|
187
|
+
"SSL_CERT_DIR",
|
|
188
|
+
"GIT_SSL_CAINFO",
|
|
189
|
+
"GIT_SSL_CAPATH",
|
|
190
|
+
"HTTPS_PROXY",
|
|
191
|
+
"HTTP_PROXY",
|
|
192
|
+
"NO_PROXY",
|
|
193
|
+
"ALL_PROXY",
|
|
194
|
+
"https_proxy",
|
|
195
|
+
"http_proxy",
|
|
196
|
+
"no_proxy",
|
|
197
|
+
"all_proxy",
|
|
198
|
+
] as const;
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* The configuration every command in a managed repository runs with, over
|
|
202
|
+
* whatever the repository's own configuration says. What an agent commits
|
|
203
|
+
* (`.gitattributes`, `.lfsconfig`, hooks it names) is data there: no
|
|
204
|
+
* filter, hook, signing program, or credential helper of the machine runs
|
|
205
|
+
* for it, and Git speaks only the transports Work itself uses.
|
|
206
|
+
*/
|
|
207
|
+
const MANAGED_CONFIG: ReadonlyArray<readonly [string, string]> = [
|
|
208
|
+
// Who Work is when a command names no author of its own (`-c` on the
|
|
209
|
+
// command still wins): never whoever the service account is.
|
|
210
|
+
["user.name", "Work"],
|
|
211
|
+
["user.email", "system@work.software"],
|
|
212
|
+
["core.hooksPath", devNull],
|
|
213
|
+
["core.attributesFile", devNull],
|
|
214
|
+
["core.excludesFile", devNull],
|
|
215
|
+
["core.fsmonitor", "false"],
|
|
216
|
+
["credential.helper", ""],
|
|
217
|
+
["commit.gpgSign", "false"],
|
|
218
|
+
["tag.gpgSign", "false"],
|
|
219
|
+
// Large-file storage is the filter machines most often have installed
|
|
220
|
+
// for every repository; it would fetch from an address the files name.
|
|
221
|
+
["filter.lfs.smudge", ""],
|
|
222
|
+
["filter.lfs.clean", ""],
|
|
223
|
+
["filter.lfs.process", ""],
|
|
224
|
+
["filter.lfs.required", "false"],
|
|
225
|
+
["submodule.recurse", "false"],
|
|
226
|
+
["fetch.recurseSubmodules", "false"],
|
|
227
|
+
// Copies borrow from one another: nothing is repacked or pruned.
|
|
228
|
+
["gc.auto", "0"],
|
|
229
|
+
// A code host over HTTPS (or HTTP, on a private network or a test), and
|
|
230
|
+
// the local paths Work passes between its own repositories. Nothing
|
|
231
|
+
// else: no `ext::`, `ssh://`, `git://` or helper of any other name.
|
|
232
|
+
["protocol.allow", "never"],
|
|
233
|
+
["protocol.https.allow", "always"],
|
|
234
|
+
["protocol.http.allow", "always"],
|
|
235
|
+
["protocol.file.allow", "always"],
|
|
236
|
+
// Work made these repositories under its own data folder; who owns the
|
|
237
|
+
// folder on disk (a restored volume) decides nothing here.
|
|
238
|
+
["safe.directory", "*"],
|
|
239
|
+
];
|
|
240
|
+
|
|
241
|
+
export interface NativeGitOptions {
|
|
242
|
+
timeoutMs?: number;
|
|
243
|
+
/**
|
|
244
|
+
* Whether the repository is one Work manages. Left out, the repository
|
|
245
|
+
* says so itself (see {@link markManagedRepository}); a person's own
|
|
246
|
+
* folder keeps the person's configuration.
|
|
247
|
+
*/
|
|
248
|
+
managed?: boolean;
|
|
249
|
+
/**
|
|
250
|
+
* Let Git look for a repository above `cwd`, as it does on a command
|
|
251
|
+
* line. Only for finding out what a folder a person chose is part of.
|
|
252
|
+
*/
|
|
253
|
+
discover?: boolean;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* The environment one Git command runs in. Git never looks above `cwd`
|
|
258
|
+
* for a repository unless asked to: a folder that should be a repository
|
|
259
|
+
* and is not (a copy whose creation stopped half way) fails there instead
|
|
260
|
+
* of acting on whatever repository encloses it.
|
|
261
|
+
*/
|
|
262
|
+
export async function nativeGitEnvironment(input: {
|
|
263
|
+
cwd: string;
|
|
264
|
+
auth?: NativeGitAuth;
|
|
265
|
+
managed?: boolean;
|
|
266
|
+
discover?: boolean;
|
|
267
|
+
}): Promise<NodeJS.ProcessEnv> {
|
|
268
|
+
const managed = input.managed ?? (await isManagedRepository(input.cwd));
|
|
269
|
+
const config: Array<readonly [string, string]> = [
|
|
270
|
+
...(managed ? MANAGED_CONFIG : []),
|
|
271
|
+
...(input.auth
|
|
272
|
+
? [
|
|
273
|
+
[
|
|
274
|
+
`http.${input.auth.url}.extraHeader`,
|
|
275
|
+
`Authorization: Basic ${Buffer.from(`${input.auth.username}:${input.auth.password}`).toString("base64")}`,
|
|
276
|
+
] as const,
|
|
277
|
+
]
|
|
278
|
+
: []),
|
|
279
|
+
];
|
|
280
|
+
const inherited: NodeJS.ProcessEnv = {};
|
|
281
|
+
if (managed)
|
|
282
|
+
for (const name of INHERITED) {
|
|
283
|
+
const value = process.env[name];
|
|
284
|
+
if (value !== undefined) inherited[name] = value;
|
|
285
|
+
}
|
|
286
|
+
const env: NodeJS.ProcessEnv = {
|
|
287
|
+
...(managed ? inherited : process.env),
|
|
288
|
+
GIT_OPTIONAL_LOCKS: "0",
|
|
289
|
+
GIT_TERMINAL_PROMPT: "0",
|
|
290
|
+
...(managed
|
|
291
|
+
? {
|
|
292
|
+
GIT_CONFIG_NOSYSTEM: "1",
|
|
293
|
+
GIT_CONFIG_SYSTEM: devNull,
|
|
294
|
+
GIT_CONFIG_GLOBAL: devNull,
|
|
295
|
+
GIT_ATTR_NOSYSTEM: "1",
|
|
296
|
+
}
|
|
297
|
+
: {}),
|
|
298
|
+
...(input.discover
|
|
299
|
+
? {}
|
|
300
|
+
: {
|
|
301
|
+
GIT_CEILING_DIRECTORIES: path.dirname(path.resolve(input.cwd)),
|
|
302
|
+
}),
|
|
303
|
+
};
|
|
304
|
+
if (config.length > 0) {
|
|
305
|
+
env.GIT_CONFIG_COUNT = String(config.length);
|
|
306
|
+
for (const [index, [key, value]] of config.entries()) {
|
|
307
|
+
env[`GIT_CONFIG_KEY_${index}`] = key;
|
|
308
|
+
env[`GIT_CONFIG_VALUE_${index}`] = value;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
return env;
|
|
312
|
+
}
|
|
313
|
+
|
|
14
314
|
/** Native Git runs outside the host event loop and never refreshes the index on reads. */
|
|
15
315
|
export async function nativeGit(
|
|
16
316
|
cwd: string,
|
|
17
317
|
args: readonly string[],
|
|
18
318
|
auth?: NativeGitAuth,
|
|
319
|
+
options?: NativeGitOptions,
|
|
19
320
|
): Promise<string> {
|
|
20
|
-
//
|
|
21
|
-
|
|
22
|
-
args[0] ?? "",
|
|
23
|
-
);
|
|
321
|
+
// A transfer, and a command over a whole working tree, need a different
|
|
322
|
+
// budget from a local read.
|
|
24
323
|
return (
|
|
25
324
|
await execute("git", ["-C", cwd, ...args], {
|
|
26
|
-
env: {
|
|
27
|
-
|
|
28
|
-
GIT_OPTIONAL_LOCKS: "0",
|
|
29
|
-
GIT_TERMINAL_PROMPT: "0",
|
|
30
|
-
...(auth
|
|
31
|
-
? {
|
|
32
|
-
GIT_CONFIG_COUNT: "1",
|
|
33
|
-
GIT_CONFIG_KEY_0: `http.${auth.url}.extraHeader`,
|
|
34
|
-
GIT_CONFIG_VALUE_0: `Authorization: Basic ${Buffer.from(`${auth.username}:${auth.password}`).toString("base64")}`,
|
|
35
|
-
}
|
|
36
|
-
: {}),
|
|
37
|
-
},
|
|
38
|
-
timeout: networkOperation ? 15 * 60_000 : 60_000,
|
|
325
|
+
env: await nativeGitEnvironment({ cwd, auth, ...options }),
|
|
326
|
+
timeout: options?.timeoutMs ?? budgetFor(args),
|
|
39
327
|
maxBuffer: 32 * 1024 * 1024,
|
|
328
|
+
}).catch((error: unknown) => {
|
|
329
|
+
throw isMissingProgram(error) ? missingGit() : error;
|
|
40
330
|
})
|
|
41
331
|
).stdout;
|
|
42
332
|
}
|
|
@@ -45,10 +335,11 @@ export async function nativeGitBytes(
|
|
|
45
335
|
cwd: string,
|
|
46
336
|
args: readonly string[],
|
|
47
337
|
input?: Uint8Array,
|
|
338
|
+
options?: NativeGitOptions,
|
|
48
339
|
): Promise<Uint8Array> {
|
|
49
340
|
const command = execute("git", ["-C", cwd, ...args], {
|
|
50
|
-
env: {
|
|
51
|
-
timeout: 60_000,
|
|
341
|
+
env: await nativeGitEnvironment({ cwd, ...options }),
|
|
342
|
+
timeout: options?.timeoutMs ?? 60_000,
|
|
52
343
|
maxBuffer: 64 * 1024 * 1024,
|
|
53
344
|
encoding: "buffer",
|
|
54
345
|
});
|
|
@@ -56,6 +347,250 @@ export async function nativeGitBytes(
|
|
|
56
347
|
return new Uint8Array((await command).stdout);
|
|
57
348
|
}
|
|
58
349
|
|
|
350
|
+
/** What Git said went wrong, without anything that could carry a credential. */
|
|
351
|
+
export function gitErrorText(error: unknown): string {
|
|
352
|
+
const stderr =
|
|
353
|
+
error && typeof error === "object" && "stderr" in error
|
|
354
|
+
? String(error.stderr)
|
|
355
|
+
: "";
|
|
356
|
+
const text = (stderr || (error instanceof Error ? error.message : ""))
|
|
357
|
+
.split("\n")
|
|
358
|
+
.map((line) => line.trim())
|
|
359
|
+
.filter((line) => line.length > 0 && !/authorization/i.test(line))
|
|
360
|
+
.slice(-2)
|
|
361
|
+
.join(" ");
|
|
362
|
+
return text || "Git gave no reason";
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
function stopChild(child: ChildProcess): void {
|
|
366
|
+
if (child.exitCode === null && child.signalCode === null)
|
|
367
|
+
child.kill("SIGKILL");
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Run Git with a stream on each side, so neither what it reads nor what it
|
|
372
|
+
* writes is ever held whole in this process: a list of a history's objects,
|
|
373
|
+
* or a pack. Resolves once Git exits cleanly; `onOutput` sees every chunk
|
|
374
|
+
* of what it prints as it arrives.
|
|
375
|
+
*/
|
|
376
|
+
export async function nativeGitStream(opts: {
|
|
377
|
+
cwd: string;
|
|
378
|
+
args: readonly string[];
|
|
379
|
+
/** Written to Git's standard input, then closed. */
|
|
380
|
+
input?: string | AsyncIterable<Uint8Array>;
|
|
381
|
+
/** Called with each chunk of standard output, in order. */
|
|
382
|
+
onOutput?: (chunk: Uint8Array) => void | Promise<void>;
|
|
383
|
+
auth?: NativeGitAuth;
|
|
384
|
+
timeoutMs?: number;
|
|
385
|
+
managed?: boolean;
|
|
386
|
+
}): Promise<void> {
|
|
387
|
+
const child = spawn("git", ["-C", opts.cwd, ...opts.args], {
|
|
388
|
+
env: await nativeGitEnvironment({
|
|
389
|
+
cwd: opts.cwd,
|
|
390
|
+
auth: opts.auth,
|
|
391
|
+
managed: opts.managed,
|
|
392
|
+
}),
|
|
393
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
394
|
+
});
|
|
395
|
+
const timer = setTimeout(
|
|
396
|
+
() => stopChild(child),
|
|
397
|
+
opts.timeoutMs ?? TRANSFER_TIMEOUT_MS,
|
|
398
|
+
);
|
|
399
|
+
timer.unref?.();
|
|
400
|
+
const stderr: Buffer[] = [];
|
|
401
|
+
let stderrBytes = 0;
|
|
402
|
+
child.stderr.on("data", (chunk: Buffer) => {
|
|
403
|
+
if (stderrBytes > 64 * 1024) return;
|
|
404
|
+
stderr.push(chunk);
|
|
405
|
+
stderrBytes += chunk.byteLength;
|
|
406
|
+
});
|
|
407
|
+
const exited = new Promise<number | null>((resolve, reject) => {
|
|
408
|
+
child.once("error", (error) =>
|
|
409
|
+
reject(isMissingProgram(error) ? missingGit() : error),
|
|
410
|
+
);
|
|
411
|
+
child.once("close", (code) => resolve(code));
|
|
412
|
+
});
|
|
413
|
+
child.stdin.on("error", () => {});
|
|
414
|
+
const written = (async () => {
|
|
415
|
+
try {
|
|
416
|
+
if (typeof opts.input === "string") child.stdin.write(opts.input);
|
|
417
|
+
else if (opts.input)
|
|
418
|
+
for await (const chunk of opts.input) {
|
|
419
|
+
if (!child.stdin.write(chunk))
|
|
420
|
+
await new Promise<void>((resolve) =>
|
|
421
|
+
child.stdin.once("drain", () => resolve()),
|
|
422
|
+
);
|
|
423
|
+
}
|
|
424
|
+
} finally {
|
|
425
|
+
child.stdin.end();
|
|
426
|
+
}
|
|
427
|
+
})();
|
|
428
|
+
try {
|
|
429
|
+
for await (const chunk of child.stdout)
|
|
430
|
+
if (chunk instanceof Uint8Array) await opts.onOutput?.(chunk);
|
|
431
|
+
await written;
|
|
432
|
+
const code = await exited;
|
|
433
|
+
if (code !== 0)
|
|
434
|
+
throw Object.assign(
|
|
435
|
+
new Error(
|
|
436
|
+
`git ${opts.args.find((arg) => !arg.startsWith("-") && !arg.includes("=")) ?? ""} failed`,
|
|
437
|
+
),
|
|
438
|
+
{ code, stderr: Buffer.concat(stderr).toString("utf8") },
|
|
439
|
+
);
|
|
440
|
+
} finally {
|
|
441
|
+
clearTimeout(timer);
|
|
442
|
+
stopChild(child);
|
|
443
|
+
// Whatever stopped this early, neither side is left unobserved.
|
|
444
|
+
await Promise.allSettled([written, exited]);
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/**
|
|
449
|
+
* Everything Git prints as records ended by NUL (`-z`), however many there
|
|
450
|
+
* are: a listing of a large tree is read as it comes and never held as one
|
|
451
|
+
* buffer with a cap on its size.
|
|
452
|
+
*/
|
|
453
|
+
export async function nativeGitRecords(
|
|
454
|
+
cwd: string,
|
|
455
|
+
args: readonly string[],
|
|
456
|
+
): Promise<string[]> {
|
|
457
|
+
const records: string[] = [];
|
|
458
|
+
for await (const record of nativeGitLines({
|
|
459
|
+
cwd,
|
|
460
|
+
args,
|
|
461
|
+
separator: "\0",
|
|
462
|
+
timeoutMs: CHECKOUT_TIMEOUT_MS,
|
|
463
|
+
}))
|
|
464
|
+
records.push(record);
|
|
465
|
+
return records;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/** The lines Git prints, one at a time, however many there are. */
|
|
469
|
+
export async function* nativeGitLines(opts: {
|
|
470
|
+
cwd: string;
|
|
471
|
+
args: readonly string[];
|
|
472
|
+
input?: string;
|
|
473
|
+
timeoutMs?: number;
|
|
474
|
+
managed?: boolean;
|
|
475
|
+
/** What ends a record; a line break when left out. */
|
|
476
|
+
separator?: string;
|
|
477
|
+
}): AsyncGenerator<string> {
|
|
478
|
+
const child = spawn("git", ["-C", opts.cwd, ...opts.args], {
|
|
479
|
+
env: await nativeGitEnvironment({ cwd: opts.cwd, managed: opts.managed }),
|
|
480
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
481
|
+
});
|
|
482
|
+
const timer = setTimeout(
|
|
483
|
+
() => stopChild(child),
|
|
484
|
+
opts.timeoutMs ?? TRANSFER_TIMEOUT_MS,
|
|
485
|
+
);
|
|
486
|
+
timer.unref?.();
|
|
487
|
+
const stderr: Buffer[] = [];
|
|
488
|
+
child.stderr.on("data", (chunk: Buffer) => {
|
|
489
|
+
if (stderr.length < 64) stderr.push(chunk);
|
|
490
|
+
});
|
|
491
|
+
const exited = new Promise<number | null>((resolve, reject) => {
|
|
492
|
+
child.once("error", (error) =>
|
|
493
|
+
reject(isMissingProgram(error) ? missingGit() : error),
|
|
494
|
+
);
|
|
495
|
+
child.once("close", (code) => resolve(code));
|
|
496
|
+
});
|
|
497
|
+
// A caller that stops reading early leaves nothing to reject later.
|
|
498
|
+
exited.catch(() => {});
|
|
499
|
+
child.stdin.on("error", () => {});
|
|
500
|
+
child.stdin.end(opts.input ?? "");
|
|
501
|
+
let finished = false;
|
|
502
|
+
try {
|
|
503
|
+
let rest = "";
|
|
504
|
+
const decoder = new TextDecoder();
|
|
505
|
+
for await (const chunk of child.stdout) {
|
|
506
|
+
if (!(chunk instanceof Uint8Array)) continue;
|
|
507
|
+
const lines = (rest + decoder.decode(chunk, { stream: true })).split(
|
|
508
|
+
opts.separator ?? "\n",
|
|
509
|
+
);
|
|
510
|
+
rest = lines.pop() ?? "";
|
|
511
|
+
for (const line of lines) yield line;
|
|
512
|
+
}
|
|
513
|
+
if (rest) yield rest;
|
|
514
|
+
const code = await exited;
|
|
515
|
+
if (code !== 0)
|
|
516
|
+
throw Object.assign(new Error("git failed"), {
|
|
517
|
+
code,
|
|
518
|
+
stderr: Buffer.concat(stderr).toString("utf8"),
|
|
519
|
+
});
|
|
520
|
+
finished = true;
|
|
521
|
+
} finally {
|
|
522
|
+
clearTimeout(timer);
|
|
523
|
+
if (!finished) stopChild(child);
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/** Where a repository keeps its objects: a bare one, a checkout, a worktree. */
|
|
528
|
+
export async function objectsDirectory(repoPath: string): Promise<string> {
|
|
529
|
+
return path.resolve(
|
|
530
|
+
repoPath,
|
|
531
|
+
(await nativeGit(repoPath, ["rev-parse", "--git-path", "objects"])).trim(),
|
|
532
|
+
);
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/**
|
|
536
|
+
* Let the repository at `repoPath` read every object kept in `objects`
|
|
537
|
+
* (another repository's object folder on this machine) without copying
|
|
538
|
+
* them: Git's own alternates. Safe to repeat.
|
|
539
|
+
*/
|
|
540
|
+
export async function borrowObjects(opts: {
|
|
541
|
+
repoPath: string;
|
|
542
|
+
objects: string;
|
|
543
|
+
}): Promise<void> {
|
|
544
|
+
if (/[\n"]/.test(opts.objects))
|
|
545
|
+
throw new Error("That folder's path cannot be borrowed from");
|
|
546
|
+
const own = await objectsDirectory(opts.repoPath);
|
|
547
|
+
if (path.resolve(own) === path.resolve(opts.objects)) return;
|
|
548
|
+
const file = path.join(own, "info", "alternates");
|
|
549
|
+
const current = await fs.readFile(file, "utf8").catch(() => "");
|
|
550
|
+
const lines = current.split("\n").filter(Boolean);
|
|
551
|
+
if (lines.includes(opts.objects)) return;
|
|
552
|
+
await fs.mkdir(path.dirname(file), { recursive: true });
|
|
553
|
+
await fs.writeFile(file, `${[...lines, opts.objects].join("\n")}\n`);
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
/** The object folders a repository borrows from, as its alternates name them. */
|
|
557
|
+
export async function borrowedObjects(repoPath: string): Promise<string[]> {
|
|
558
|
+
const own = await objectsDirectory(repoPath);
|
|
559
|
+
const current = await fs
|
|
560
|
+
.readFile(path.join(own, "info", "alternates"), "utf8")
|
|
561
|
+
.catch(() => "");
|
|
562
|
+
return current
|
|
563
|
+
.split("\n")
|
|
564
|
+
.filter(Boolean)
|
|
565
|
+
.map((line) => path.resolve(own, line));
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
/** Create an empty repository Work manages; one already there is left alone. */
|
|
569
|
+
export async function initManagedRepository(opts: {
|
|
570
|
+
path: string;
|
|
571
|
+
bare?: boolean;
|
|
572
|
+
/** The format of its object ids; `sha1` when left out. */
|
|
573
|
+
objectFormat?: "sha1" | "sha256";
|
|
574
|
+
}): Promise<void> {
|
|
575
|
+
await fs.mkdir(opts.path, { recursive: true });
|
|
576
|
+
await nativeGit(
|
|
577
|
+
opts.path,
|
|
578
|
+
[
|
|
579
|
+
"init",
|
|
580
|
+
"--quiet",
|
|
581
|
+
"--initial-branch=main",
|
|
582
|
+
`--object-format=${opts.objectFormat ?? "sha1"}`,
|
|
583
|
+
...(opts.bare ? ["--bare"] : []),
|
|
584
|
+
],
|
|
585
|
+
undefined,
|
|
586
|
+
{ managed: true },
|
|
587
|
+
);
|
|
588
|
+
await markManagedRepository(opts.path);
|
|
589
|
+
// Copies borrow from one another, so nothing may ever be pruned behind
|
|
590
|
+
// a borrower's back: Work repacks nothing on its own.
|
|
591
|
+
await nativeGit(opts.path, ["config", "gc.auto", "0"]);
|
|
592
|
+
}
|
|
593
|
+
|
|
59
594
|
export interface LocalFolder {
|
|
60
595
|
path: string;
|
|
61
596
|
commonDirectory: string | null;
|
|
@@ -100,10 +635,12 @@ export async function discoverLocalFolder(input: {
|
|
|
100
635
|
) {
|
|
101
636
|
if (
|
|
102
637
|
(
|
|
103
|
-
await nativeGit(
|
|
104
|
-
|
|
105
|
-
"--is-bare-repository",
|
|
106
|
-
|
|
638
|
+
await nativeGit(
|
|
639
|
+
ancestor,
|
|
640
|
+
["rev-parse", "--is-bare-repository"],
|
|
641
|
+
undefined,
|
|
642
|
+
{ discover: true },
|
|
643
|
+
).catch(() => "")
|
|
107
644
|
).trim() === "true"
|
|
108
645
|
)
|
|
109
646
|
throw new Error("Choose a working folder, not a bare Git repository");
|
|
@@ -121,7 +658,11 @@ export async function discoverLocalFolder(input: {
|
|
|
121
658
|
ancestor = parent;
|
|
122
659
|
}
|
|
123
660
|
const root = await fs.realpath(
|
|
124
|
-
(
|
|
661
|
+
(
|
|
662
|
+
await nativeGit(requested, ["rev-parse", "--show-toplevel"], undefined, {
|
|
663
|
+
discover: true,
|
|
664
|
+
})
|
|
665
|
+
).trim(),
|
|
125
666
|
);
|
|
126
667
|
const common = (
|
|
127
668
|
await nativeGit(root, ["rev-parse", "--git-common-dir"])
|