@waffle-os/git 0.0.0-stage → 0.0.25
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/LICENSE +21 -0
- package/README.md +14 -2
- package/dist/git-cli.js +182 -0
- package/dist/git-command.d.ts +1 -0
- package/dist/git-command.js +177 -0
- package/dist/git.NOTICES.txt +1439 -0
- package/docs/git-local.md +68 -0
- package/docs/rev-parse.md +67 -0
- package/package-artifacts.json +8 -0
- package/package.json +55 -4
- package/provenance/waffle-transfer.json +9 -0
- package/src/cli.ts +17 -0
- package/src/git-command.ts +159 -0
- package/src/git-context.ts +189 -0
- package/src/git-diff.ts +110 -0
- package/src/git-filesystem.ts +85 -0
- package/src/git-history.ts +190 -0
- package/src/git-index.ts +28 -0
- package/src/git-merge.ts +65 -0
- package/src/git-revision.ts +185 -0
- package/src/git-stash.ts +208 -0
- package/src/git-types.ts +45 -0
- package/src/git.ts +41 -0
- package/src/node-filesystem.ts +24 -0
- package/src/program.ts +127 -0
- package/third-party/git/Apache-2.0.txt +202 -0
- package/third-party/git/provenance.json +53 -0
package/src/git-stash.ts
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import * as git from "isomorphic-git";
|
|
2
|
+
import { FileSystem } from "isomorphic-git/models";
|
|
3
|
+
import {
|
|
4
|
+
arity,
|
|
5
|
+
clean,
|
|
6
|
+
exists,
|
|
7
|
+
GitFailure,
|
|
8
|
+
identity,
|
|
9
|
+
options,
|
|
10
|
+
output,
|
|
11
|
+
text,
|
|
12
|
+
type GitContext,
|
|
13
|
+
} from "./git-context";
|
|
14
|
+
|
|
15
|
+
export async function gitStash(context: GitContext, args: readonly string[]) {
|
|
16
|
+
const parsed = options(
|
|
17
|
+
args,
|
|
18
|
+
["--index", "-u", "--include-untracked"],
|
|
19
|
+
["-m", "--message", "--format"],
|
|
20
|
+
);
|
|
21
|
+
const op = parsed.paths[0] ?? "push";
|
|
22
|
+
if (parsed.flags.has("--index") && op !== "apply" && op !== "pop")
|
|
23
|
+
throw new GitFailure("--index requires stash apply or pop", 129);
|
|
24
|
+
if (parsed.named.has("--format") && op !== "list")
|
|
25
|
+
throw new GitFailure("--format requires stash list", 129);
|
|
26
|
+
if (
|
|
27
|
+
(parsed.named.has("-m") ||
|
|
28
|
+
parsed.named.has("--message") ||
|
|
29
|
+
parsed.flags.has("-u") ||
|
|
30
|
+
parsed.flags.has("--include-untracked")) &&
|
|
31
|
+
op !== "push"
|
|
32
|
+
)
|
|
33
|
+
throw new GitFailure("message and untracked options require stash push", 129);
|
|
34
|
+
if (op === "list") return list(context, parsed);
|
|
35
|
+
if (!["push", "apply", "pop", "drop", "clear"].includes(op))
|
|
36
|
+
throw new GitFailure(`unsupported stash operation '${op}'`, 129);
|
|
37
|
+
arity(parsed.paths, 0, op === "push" || op === "clear" ? 1 : 2);
|
|
38
|
+
const entries = await stashEntries(context);
|
|
39
|
+
const refIdx = stashIndex(parsed.paths[1]);
|
|
40
|
+
if (op !== "push" && op !== "clear" && refIdx >= entries.length)
|
|
41
|
+
throw new GitFailure("no stash entry found", 1);
|
|
42
|
+
if (op === "push") return push(context, parsed);
|
|
43
|
+
if (op === "clear" || op === "drop") {
|
|
44
|
+
await git.stash({ ...context, op, refIdx });
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
await apply(context, entries[refIdx].oid, parsed.flags.has("--index"));
|
|
48
|
+
if (op === "pop") await git.stash({ ...context, op: "drop", refIdx });
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function stashIndex(value?: string) {
|
|
52
|
+
if (value === undefined) return 0;
|
|
53
|
+
const match = /^(?:stash@\{(\d+)\}|(\d+))$/.exec(value);
|
|
54
|
+
const index = match ? Number(match[1] ?? match[2]) : NaN;
|
|
55
|
+
if (!Number.isSafeInteger(index)) throw new GitFailure("invalid stash reference", 129);
|
|
56
|
+
return index;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function list(context: GitContext, parsed: ReturnType<typeof options>) {
|
|
60
|
+
arity(parsed.paths, 1);
|
|
61
|
+
const format = parsed.named.get("--format");
|
|
62
|
+
if (format && format !== "%gs") throw new GitFailure("only stash --format=%gs is supported", 129);
|
|
63
|
+
const entries = await stashEntries(context);
|
|
64
|
+
await output(
|
|
65
|
+
context,
|
|
66
|
+
entries
|
|
67
|
+
.map(({ message }, index) => `${format ? "" : `stash@{${index}}: `}${message}\n`)
|
|
68
|
+
.join(""),
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function stashEntries(context: GitContext) {
|
|
73
|
+
const path = `${context.dir}/.git/logs/refs/stash`;
|
|
74
|
+
if (!(await exists(context.fs, path))) return [];
|
|
75
|
+
return (await text(context.fs, path))
|
|
76
|
+
.trimEnd()
|
|
77
|
+
.split("\n")
|
|
78
|
+
.reverse()
|
|
79
|
+
.filter(Boolean)
|
|
80
|
+
.map((line) => {
|
|
81
|
+
const oid = line.split(" ")[1];
|
|
82
|
+
if (!/^[a-f0-9]{40}$/.test(oid) || !line.includes("\t"))
|
|
83
|
+
throw new GitFailure("invalid stash reflog");
|
|
84
|
+
return { oid, message: line.slice(line.indexOf("\t") + 1) };
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function push(context: GitContext, parsed: ReturnType<typeof options>) {
|
|
89
|
+
if (await exists(context.fs, `${context.dir}/.git/MERGE_HEAD`))
|
|
90
|
+
throw new GitFailure("finish or abort the current merge first", 1);
|
|
91
|
+
const rows = await git.statusMatrix(context);
|
|
92
|
+
const untracked =
|
|
93
|
+
parsed.flags.has("-u") || parsed.flags.has("--include-untracked")
|
|
94
|
+
? rows.filter(([, head, , stage]) => head === 0 && stage === 0).map(([path]) => path)
|
|
95
|
+
: [];
|
|
96
|
+
const tracked = rows.filter(([, head, , stage]) => head !== 0 || stage !== 0);
|
|
97
|
+
if (
|
|
98
|
+
!untracked.length &&
|
|
99
|
+
!tracked.some(([, head, work, stage]) => head !== work || head !== stage)
|
|
100
|
+
)
|
|
101
|
+
return;
|
|
102
|
+
const head = await git.resolveRef({ ...context, ref: "HEAD" });
|
|
103
|
+
const branch = (await git.currentBranch(context)) ?? "(no branch)";
|
|
104
|
+
const message = parsed.named.get("-m") ?? parsed.named.get("--message");
|
|
105
|
+
const subject = (await git.readCommit({ ...context, oid: head })).commit.message.split("\n")[0];
|
|
106
|
+
const label = message
|
|
107
|
+
? `On ${branch}: ${message}`
|
|
108
|
+
: `WIP on ${branch}: ${head.slice(0, 7)} ${subject}`;
|
|
109
|
+
const oid = await snapshot(context, head, tracked, untracked, label);
|
|
110
|
+
await saveEntry(context, oid, label);
|
|
111
|
+
await git.checkout({ ...context, ref: head, noUpdateHead: true, force: true });
|
|
112
|
+
for (const path of untracked) await context.fs.promises.unlink(`${context.dir}/${path}`);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async function snapshot(
|
|
116
|
+
context: GitContext,
|
|
117
|
+
head: string,
|
|
118
|
+
tracked: git.StatusRow[],
|
|
119
|
+
untracked: string[],
|
|
120
|
+
message: string,
|
|
121
|
+
) {
|
|
122
|
+
const indexPath = `${context.dir}/.git/index`;
|
|
123
|
+
const original = (await exists(context.fs, indexPath))
|
|
124
|
+
? await context.fs.promises.readFile(indexPath)
|
|
125
|
+
: undefined;
|
|
126
|
+
const author = await identity(context, "AUTHOR");
|
|
127
|
+
const committer = await identity(context, "COMMITTER");
|
|
128
|
+
const commit = (parent: string[], message: string) =>
|
|
129
|
+
git.commit({ ...context, parent, message, author, committer, noUpdateBranch: true });
|
|
130
|
+
try {
|
|
131
|
+
const index = await commit([head], "index on stash base");
|
|
132
|
+
await stageWorktree(context, tracked);
|
|
133
|
+
const work = await commit([head], message);
|
|
134
|
+
const tree = (await git.readCommit({ ...context, oid: work })).commit.tree;
|
|
135
|
+
const parent = [head, index];
|
|
136
|
+
if (untracked.length) parent.push(await untrackedCommit(context, untracked, commit));
|
|
137
|
+
return await git.commit({
|
|
138
|
+
...context,
|
|
139
|
+
parent,
|
|
140
|
+
tree,
|
|
141
|
+
message,
|
|
142
|
+
author,
|
|
143
|
+
committer,
|
|
144
|
+
noUpdateBranch: true,
|
|
145
|
+
});
|
|
146
|
+
} finally {
|
|
147
|
+
if (original !== undefined) await context.fs.promises.writeFile(indexPath, original);
|
|
148
|
+
else if (await exists(context.fs, indexPath)) await context.fs.promises.unlink(indexPath);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async function stageWorktree(context: GitContext, rows: git.StatusRow[]) {
|
|
153
|
+
for (const [filepath, , work] of rows) {
|
|
154
|
+
if (work === 0) await git.remove({ ...context, filepath });
|
|
155
|
+
else await git.add({ ...context, filepath, force: true });
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async function untrackedCommit(
|
|
160
|
+
context: GitContext,
|
|
161
|
+
paths: string[],
|
|
162
|
+
commit: (parent: string[], message: string) => Promise<string>,
|
|
163
|
+
) {
|
|
164
|
+
await git.remove({ ...context, filepath: await git.listFiles(context) });
|
|
165
|
+
for (const filepath of paths) await git.add({ ...context, filepath });
|
|
166
|
+
return commit([], "untracked files on stash base");
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
async function saveEntry(context: GitContext, oid: string, message: string) {
|
|
170
|
+
const author = await identity(context, "AUTHOR");
|
|
171
|
+
const timestamp = author.timestamp ?? Math.floor(Date.now() / 1000);
|
|
172
|
+
const offset = author.timezoneOffset ?? new Date().getTimezoneOffset();
|
|
173
|
+
const zone = `${offset > 0 ? "-" : "+"}${String(Math.floor(Math.abs(offset) / 60)).padStart(2, "0")}${String(Math.abs(offset) % 60).padStart(2, "0")}`;
|
|
174
|
+
const old = (await stashEntries(context))[0]?.oid ?? "0".repeat(40);
|
|
175
|
+
const path = `${context.dir}/.git/logs/refs/stash`;
|
|
176
|
+
const log = (await exists(context.fs, path)) ? await text(context.fs, path) : "";
|
|
177
|
+
await new FileSystem(context.fs).mkdir(`${context.dir}/.git/logs/refs`);
|
|
178
|
+
await context.fs.promises.writeFile(
|
|
179
|
+
path,
|
|
180
|
+
`${log}${old} ${oid} ${author.name} <${author.email}> ${timestamp} ${zone}\t${message}\n`,
|
|
181
|
+
);
|
|
182
|
+
await git.writeRef({ ...context, ref: "refs/stash", value: oid, force: true });
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
async function apply(context: GitContext, oid: string, restoreIndex: boolean) {
|
|
186
|
+
await clean(context);
|
|
187
|
+
const { commit } = await git.readCommit({ ...context, oid });
|
|
188
|
+
const [base, index, untracked] = commit.parent;
|
|
189
|
+
if (!base || !index || commit.parent.length > 3) throw new GitFailure("invalid stash commit");
|
|
190
|
+
if ((await git.resolveRef({ ...context, ref: "HEAD" })) !== base)
|
|
191
|
+
throw new GitFailure("stash apply currently requires its original HEAD", 1);
|
|
192
|
+
const loose = untracked ? await git.listFiles({ ...context, ref: untracked }) : [];
|
|
193
|
+
for (const path of loose) {
|
|
194
|
+
if (await exists(context.fs, `${context.dir}/${path}`))
|
|
195
|
+
throw new GitFailure(`untracked file '${path}' would be overwritten`, 1);
|
|
196
|
+
}
|
|
197
|
+
await git.checkout({ ...context, ref: oid, noUpdateHead: true, dryRun: true });
|
|
198
|
+
await git.checkout({ ...context, ref: oid, noUpdateHead: true });
|
|
199
|
+
const ref = restoreIndex ? index : base;
|
|
200
|
+
const paths = new Set(
|
|
201
|
+
(await git.listFiles(context)).concat(await git.listFiles({ ...context, ref })),
|
|
202
|
+
);
|
|
203
|
+
for (const filepath of paths) await git.resetIndex({ ...context, filepath, ref });
|
|
204
|
+
for (const filepath of loose) {
|
|
205
|
+
const { blob } = await git.readBlob({ ...context, oid: untracked, filepath });
|
|
206
|
+
await new FileSystem(context.fs).write(`${context.dir}/${filepath}`, blob);
|
|
207
|
+
}
|
|
208
|
+
}
|
package/src/git-types.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
export interface GitInvocation {
|
|
2
|
+
/** Arguments after `git`, without a shell parser or executable name. */
|
|
3
|
+
readonly argv: readonly string[];
|
|
4
|
+
readonly cwd: string;
|
|
5
|
+
readonly env?: Readonly<Record<string, string>>;
|
|
6
|
+
readonly stdout: (bytes: Uint8Array) => void | Promise<void>;
|
|
7
|
+
readonly stderr: (bytes: Uint8Array) => void | Promise<void>;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface GitInstallation {
|
|
11
|
+
/** Run a local command in the page. `waffle-git/program` installs the same backend on PATH. */
|
|
12
|
+
run(invocation: GitInvocation): Promise<number>;
|
|
13
|
+
/** Stop admission and join accepted commands; never dispose the caller's Runtime. */
|
|
14
|
+
dispose(): Promise<void>;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface GitStat {
|
|
18
|
+
readonly mode: number;
|
|
19
|
+
readonly size: number;
|
|
20
|
+
readonly ino: number;
|
|
21
|
+
readonly mtimeMs: number;
|
|
22
|
+
readonly ctimeMs: number;
|
|
23
|
+
readonly uid: number;
|
|
24
|
+
readonly gid: number;
|
|
25
|
+
readonly dev: number;
|
|
26
|
+
isFile(): boolean;
|
|
27
|
+
isDirectory(): boolean;
|
|
28
|
+
isSymbolicLink(): boolean;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The upstream promise-FS operations used by the local command backend. */
|
|
32
|
+
export interface GitFilesystem {
|
|
33
|
+
readonly promises: {
|
|
34
|
+
readFile(path: string, encoding?: string | { encoding?: string }): Promise<Uint8Array | string>;
|
|
35
|
+
writeFile(path: string, data: Uint8Array | string): Promise<void>;
|
|
36
|
+
unlink(path: string): Promise<void>;
|
|
37
|
+
readdir(path: string): Promise<string[]>;
|
|
38
|
+
mkdir(path: string): Promise<void>;
|
|
39
|
+
rmdir(path: string): Promise<void>;
|
|
40
|
+
stat(path: string): Promise<GitStat>;
|
|
41
|
+
lstat(path: string): Promise<GitStat>;
|
|
42
|
+
readlink(path: string): Promise<string>;
|
|
43
|
+
symlink(target: string, path: string): Promise<void>;
|
|
44
|
+
};
|
|
45
|
+
}
|
package/src/git.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { Runtime } from "@waffle-os/runtime";
|
|
2
|
+
import type { GitInstallation, GitInvocation } from "./git-types";
|
|
3
|
+
export type { GitInstallation, GitInvocation } from "./git-types";
|
|
4
|
+
const installed = new WeakSet<Runtime>();
|
|
5
|
+
|
|
6
|
+
/** Borrow the page's filesystem. Load the local Git core on the first command.
|
|
7
|
+
* This is the in-page API; `installGitProgram` puts the same backend on PATH as `/usr/bin/git`.
|
|
8
|
+
*/
|
|
9
|
+
export async function installGit(runtime: Runtime): Promise<GitInstallation> {
|
|
10
|
+
if (runtime.disposed) throw new Error("Runtime is disposed");
|
|
11
|
+
if (installed.has(runtime)) throw new Error("Git is already installed on this Runtime");
|
|
12
|
+
installed.add(runtime);
|
|
13
|
+
let closed = false;
|
|
14
|
+
let tail: Promise<unknown> = Promise.resolve();
|
|
15
|
+
let backend: Promise<typeof import("../dist/git-command.js")> | undefined;
|
|
16
|
+
let filesystem: Promise<typeof import("./git-filesystem.ts")> | undefined;
|
|
17
|
+
let disposal: Promise<void> | undefined;
|
|
18
|
+
const execute = async (invocation: GitInvocation) => {
|
|
19
|
+
if (runtime.disposed) throw new Error("Runtime is disposed");
|
|
20
|
+
backend ??= import("../dist/git-command.js");
|
|
21
|
+
filesystem ??= import("./git-filesystem.ts");
|
|
22
|
+
const [command, adapter] = await Promise.all([backend, filesystem]);
|
|
23
|
+
return command.runGit(adapter.gitFilesystem(runtime.filesystem), invocation);
|
|
24
|
+
};
|
|
25
|
+
return {
|
|
26
|
+
run(invocation) {
|
|
27
|
+
if (closed) return Promise.reject(new Error("Git installation is disposed"));
|
|
28
|
+
const snapshot = { ...invocation, argv: invocation.argv.slice(), env: { ...invocation.env } };
|
|
29
|
+
const result = tail.then(() => execute(snapshot));
|
|
30
|
+
tail = result.catch(() => {});
|
|
31
|
+
return result;
|
|
32
|
+
},
|
|
33
|
+
dispose() {
|
|
34
|
+
closed = true;
|
|
35
|
+
disposal ??= tail.then(() => {
|
|
36
|
+
installed.delete(runtime);
|
|
37
|
+
});
|
|
38
|
+
return disposal;
|
|
39
|
+
},
|
|
40
|
+
};
|
|
41
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import * as fs from "node:fs/promises";
|
|
2
|
+
import type { GitFilesystem } from "./git-types";
|
|
3
|
+
|
|
4
|
+
/** Node-compatible promise FS. Under a Waffle interpreter (Bun) this is the shared Waffle filesystem. */
|
|
5
|
+
export const nodeGitFilesystem: GitFilesystem = {
|
|
6
|
+
promises: {
|
|
7
|
+
async readFile(path, encoding) {
|
|
8
|
+
const bytes = await fs.readFile(path);
|
|
9
|
+
const format = typeof encoding === "string" ? encoding : encoding?.encoding;
|
|
10
|
+
return format ? bytes.toString("utf8") : bytes;
|
|
11
|
+
},
|
|
12
|
+
writeFile: fs.writeFile,
|
|
13
|
+
unlink: fs.unlink,
|
|
14
|
+
readdir: fs.readdir,
|
|
15
|
+
async mkdir(path) {
|
|
16
|
+
await fs.mkdir(path);
|
|
17
|
+
},
|
|
18
|
+
rmdir: fs.rmdir,
|
|
19
|
+
stat: fs.stat,
|
|
20
|
+
lstat: fs.lstat,
|
|
21
|
+
readlink: fs.readlink,
|
|
22
|
+
symlink: fs.symlink,
|
|
23
|
+
},
|
|
24
|
+
};
|
package/src/program.ts
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { defineProgramPackage } from "@waffle-os/runtime/programs";
|
|
2
|
+
import type { Runtime } from "@waffle-os/runtime";
|
|
3
|
+
import { FilesystemClient } from "@waffle-os/runtime/adapter/worker";
|
|
4
|
+
import { FilesystemError } from "@waffle-os/runtime/adapter/worker";
|
|
5
|
+
|
|
6
|
+
/** Bundler-visible URL for the prepared CLI script. */
|
|
7
|
+
export const GIT_CLI_URL = new URL("../dist/git-cli.js", import.meta.url);
|
|
8
|
+
|
|
9
|
+
export interface GitProgramOptions {
|
|
10
|
+
/** The bundled `dist/git-cli.js` text. Callers fetch it from the package asset URL. */
|
|
11
|
+
readonly source: string;
|
|
12
|
+
/** A registered JavaScript interpreter on this Runtime, for example bun-wasm's `/bin/bun`. */
|
|
13
|
+
readonly interpreter?: string;
|
|
14
|
+
/** Absolute canonical program path. */
|
|
15
|
+
readonly path?: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface GitProgramInstallation {
|
|
19
|
+
readonly path: string;
|
|
20
|
+
/** Remove the script only while it still holds the bytes this installation wrote. */
|
|
21
|
+
dispose(): Promise<void>;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export class GitProgramConflictError extends Error {
|
|
25
|
+
readonly code = "GIT_PROGRAM_CONFLICT";
|
|
26
|
+
readonly path: string;
|
|
27
|
+
constructor(path: string) {
|
|
28
|
+
super(`Cannot install git: a different filesystem entry already exists at ${path}`);
|
|
29
|
+
this.path = path;
|
|
30
|
+
this.name = "GitProgramConflictError";
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const sameBytes = (left: Uint8Array | undefined, right: Uint8Array) =>
|
|
35
|
+
left !== undefined &&
|
|
36
|
+
left.length === right.length &&
|
|
37
|
+
left.every((byte, index) => byte === right[index]);
|
|
38
|
+
|
|
39
|
+
/** Install `git` as an interpreter script on the Runtime's filesystem.
|
|
40
|
+
* Waffle's shebang admission runs it with the caller's interpreter; no executable is registered here.
|
|
41
|
+
*/
|
|
42
|
+
export async function installGitProgram(
|
|
43
|
+
runtime: Runtime,
|
|
44
|
+
options: GitProgramOptions,
|
|
45
|
+
): Promise<GitProgramInstallation> {
|
|
46
|
+
if (runtime.disposed) throw new Error("Runtime is disposed");
|
|
47
|
+
const path = options.path ?? "/usr/bin/git";
|
|
48
|
+
const interpreter = options.interpreter ?? "/bin/bun";
|
|
49
|
+
for (const name of [path, interpreter]) {
|
|
50
|
+
if (
|
|
51
|
+
!name.startsWith("/") ||
|
|
52
|
+
name
|
|
53
|
+
.slice(1)
|
|
54
|
+
.split("/")
|
|
55
|
+
.some((part) => !part || part === "." || part === "..")
|
|
56
|
+
)
|
|
57
|
+
throw new TypeError(`Path must be absolute and canonical: ${name}`);
|
|
58
|
+
}
|
|
59
|
+
const bytes = new TextEncoder().encode(`#!${interpreter}\n${options.source}`);
|
|
60
|
+
// Order after queued page writes, then use a private connection for exclusive creation.
|
|
61
|
+
await runtime.filesystem.resolvePath("/");
|
|
62
|
+
const filesystem = new FilesystemClient(runtime.filesystem.fork());
|
|
63
|
+
let owned: number | undefined;
|
|
64
|
+
try {
|
|
65
|
+
await filesystem.asyncCall("mkdirp", [path.slice(0, path.lastIndexOf("/")) || "/"]);
|
|
66
|
+
if (await createScript(filesystem, path, bytes))
|
|
67
|
+
owned = (await filesystem.asyncCall("lookup", [path]))?.ino;
|
|
68
|
+
} finally {
|
|
69
|
+
filesystem.dispose();
|
|
70
|
+
}
|
|
71
|
+
let disposal: Promise<void> | undefined;
|
|
72
|
+
return {
|
|
73
|
+
path,
|
|
74
|
+
dispose() {
|
|
75
|
+
disposal ??=
|
|
76
|
+
owned === undefined ? Promise.resolve() : removeOwned(runtime, path, owned, bytes);
|
|
77
|
+
return disposal;
|
|
78
|
+
},
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async function createScript(filesystem: FilesystemClient, path: string, bytes: Uint8Array) {
|
|
83
|
+
try {
|
|
84
|
+
await filesystem.asyncCall("writeFile", [path, false, true], bytes);
|
|
85
|
+
return true;
|
|
86
|
+
} catch (error) {
|
|
87
|
+
if (!(error instanceof FilesystemError) || error.errno !== 20) throw error;
|
|
88
|
+
// An identical script from an earlier install may be reused, but is not owned for deletion.
|
|
89
|
+
const entry = await filesystem.asyncCall("lookup", [path]);
|
|
90
|
+
if (entry?.kind !== "file" || !sameBytes(await filesystem.asyncCall("readFile", [path]), bytes))
|
|
91
|
+
throw new GitProgramConflictError(path);
|
|
92
|
+
return false;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Lookup does not follow a final symlink: only the created regular file, unchanged, is removed.
|
|
97
|
+
* Replacement symlinks, directories and files (even with identical bytes) are the caller's. */
|
|
98
|
+
async function removeOwned(runtime: Runtime, path: string, ino: number, bytes: Uint8Array) {
|
|
99
|
+
if (runtime.disposed) return;
|
|
100
|
+
const entry = await runtime.filesystem.lookup(path);
|
|
101
|
+
if (entry?.kind !== "file" || entry.ino !== ino) return;
|
|
102
|
+
if (!sameBytes(await runtime.filesystem.readFile(path), bytes)) return;
|
|
103
|
+
await runtime.filesystem.remove(path);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** A script package borrows an explicitly registered interpreter. It never installs one. */
|
|
107
|
+
export function createGitPackage(options: {
|
|
108
|
+
readonly interpreter: string;
|
|
109
|
+
readonly source?: () => Promise<string>;
|
|
110
|
+
}) {
|
|
111
|
+
return defineProgramPackage({
|
|
112
|
+
name: "git",
|
|
113
|
+
programs: [
|
|
114
|
+
{
|
|
115
|
+
path: "/usr/bin/git",
|
|
116
|
+
aliases: ["/bin/git"],
|
|
117
|
+
script: { interpreter: options.interpreter, source: options.source ?? gitSource },
|
|
118
|
+
},
|
|
119
|
+
],
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async function gitSource(): Promise<string> {
|
|
124
|
+
const response = await fetch(GIT_CLI_URL);
|
|
125
|
+
if (!response.ok) throw new Error(`Git script fetch failed: ${response.status}`);
|
|
126
|
+
return response.text();
|
|
127
|
+
}
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|