@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
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
# Local Git
|
|
2
|
+
|
|
3
|
+
`waffle-git` runs local repository commands through isomorphic-git 1.44.5 on the embedding page's Waffle filesystem. It creates no runtime, process service, worker or executable marker. The Git core and text-diff library load on the first command from `dist/git-command.js`. Package preparation builds that self-contained asset with the verified upstream patch, so tarball consumers also receive the corrected backend.
|
|
4
|
+
|
|
5
|
+
The public exports contain TypeScript source. Node consumers need a loader or bundler that handles TypeScript inside `node_modules`; Node's built-in type stripping alone does not load dependency source there. Both exports support strip-only TypeScript loaders.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { installGit } from "waffle-git";
|
|
9
|
+
|
|
10
|
+
const git = await installGit(runtime);
|
|
11
|
+
await runtime.filesystem.mkdirp("/project");
|
|
12
|
+
const status = await git.run({
|
|
13
|
+
argv: ["init", "-b", "main"],
|
|
14
|
+
cwd: "/project",
|
|
15
|
+
env: {
|
|
16
|
+
GIT_AUTHOR_NAME: "Ada",
|
|
17
|
+
GIT_AUTHOR_EMAIL: "ada@example.invalid",
|
|
18
|
+
GIT_COMMITTER_NAME: "Ada",
|
|
19
|
+
GIT_COMMITTER_EMAIL: "ada@example.invalid",
|
|
20
|
+
},
|
|
21
|
+
stdout: (bytes) => terminal.write(bytes),
|
|
22
|
+
stderr: (bytes) => terminal.write(bytes),
|
|
23
|
+
});
|
|
24
|
+
await git.dispose();
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Arguments exclude the executable name. Streams receive bytes and may return promises. `run` returns a numeric status. One installation per runtime serializes its commands; dispose closes admission, joins accepted commands and leaves the caller's filesystem and runtime alive. Edits through other filesystem users must finish before starting a Git command.
|
|
28
|
+
|
|
29
|
+
## Supported commands
|
|
30
|
+
|
|
31
|
+
| Command | Local slice |
|
|
32
|
+
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
33
|
+
| `init` | Optional directory, `-b`/`--initial-branch`, SHA-1; no templates |
|
|
34
|
+
| `add` | Literal files/directories, `.`, `-A`, `-u`, `-f`; stages deletions |
|
|
35
|
+
| `commit` | Required `-m`, optional `--allow-empty`; environment identity/date or repository user config |
|
|
36
|
+
| `status` | Porcelain v1 with all untracked files, also the default output |
|
|
37
|
+
| `log` | Git's default layout (commit, author, author-zone date, indented message), `%s`, `%H`, `%h %s`, `%H %s` formats, `--oneline`, `--first-parent`, `-n`/`--max-count` |
|
|
38
|
+
| `diff` | Index/worktree or `--cached`/`--staged`; unified UTF-8 text diff, binary notice, `--name-only`, `--no-prefix`, `--quiet`, `--exit-code` |
|
|
39
|
+
| `branch` | List/current, create, delete `-d`/`-D`; no patterns |
|
|
40
|
+
| `checkout` | Existing local revision, `-b`; refuses tracked edits that could be lost |
|
|
41
|
+
| `switch` | Existing local branch, `-c`/`--create`; same refusal as `checkout` |
|
|
42
|
+
| `merge` | Clean fast-forward and divergent merges, text conflict markers and index stages, `--abort`, resolution commits, `--ff-only`, `--no-ff`, `-m` |
|
|
43
|
+
| `stash` | Push/list/apply/pop/drop/clear, `-u`/`--include-untracked`, `-m`, `--index` on apply/pop, `%gs` list format |
|
|
44
|
+
| `config` | Repository-local `user.name` and `user.email` only |
|
|
45
|
+
|
|
46
|
+
Waffle's high-level filesystem API exposes regular files and directories, without executable mode control. This adapter rejects symlinks. Remotes, network relay, submodules, hooks, editors, filters, arbitrary config and Git aliases are outside this slice. Unsupported commands/options return an error. Conflicting text merges return 1 and leave real conflict stages and markers for `add` and `commit`, or `merge --abort`. Checkout and stash push reject an unfinished merge. Stash saves native-shaped worktree, index, and optional untracked commits. `apply --index` and `pop --index` restore every saved index path while preserving the saved worktree, including staged additions deleted before stashing. Apply and pop require the saved original HEAD and a clean tracked worktree; applying across different commits is not supported. Untracked collisions fail before saved files are restored. Ignored files are excluded from `-u`. Executable bits, symlinks, rename detection, complex file/directory conflicts, and recursive multi-base merges are not supported.
|
|
47
|
+
|
|
48
|
+
## The `git` program
|
|
49
|
+
|
|
50
|
+
`waffle-git/program` installs `/usr/bin/git` as an interpreter script: `#!/bin/bun` followed by `dist/git-cli.js`. Waffle's shebang admission runs it with the JavaScript interpreter already registered on the caller's Runtime (bun-wasm's `/bin/bun`), so shells, `Bun.spawn("git")` and any other process reach it on `PATH`. The CLI calls the same `runGit` backend with process argv, cwd, env and stdio, and uses the interpreter's `node:fs`, which is the shared Waffle filesystem. It registers no executable, adapter or worker of its own.
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
import { installGitProgram, GIT_CLI_URL } from "waffle-git/program";
|
|
54
|
+
|
|
55
|
+
const git = await installGitProgram(runtime, { source: await (await fetch(GIT_CLI_URL)).text() });
|
|
56
|
+
// ... spawn /usr/bin/git through any process on the runtime
|
|
57
|
+
await git.dispose();
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Installation writes the script once, exclusively; a foreign file at the path is a conflict. Dispose removes only the unchanged regular file with the inode this install created. Without a registered interpreter the spawn fails at admission. There is no native Git or stub-module fallback.
|
|
61
|
+
|
|
62
|
+
## Verification and source
|
|
63
|
+
|
|
64
|
+
`node scripts/test-git-local.ts` replays all four committed native-Git scenarios and 96 steps, plus binary preservation, stash deletion, collision, and refusal checks. `node scripts/test-git-browser.ts` (inherited from bash-web, not rerun in this package) repeats all 96 steps and tracked stash in Chromium on the actual Waffle filesystem. It checks first-use loading, zero process admission, command retirement, pending-output joins, reinstallation, and caller lifetime. Neither backend nor browser replay invokes native Git. `bun run --cwd packages/git test:browser` runs the six everyday commands in Chromium through both the API and `/usr/bin/git` on bun-wasm, on one Waffle filesystem. `npm run test:browser:lookup` has the Bash shell and `Bun.spawn(["git", ...])` find `git` by name on `PATH=/usr/bin:/bin` against one shared repository; it builds Bash from a staged source export (`GIT_BASH_SOURCE`) and its CI shell guest (`GIT_SHELL_GUEST`) as test composition only.
|
|
65
|
+
|
|
66
|
+
No scenarios are excluded. The fixture source and exact oracle environment are owned by `scripts/record-git-local.ts`; `node scripts/record-git-local.ts --check` audits its native recording without changing owner HOME/global config.
|
|
67
|
+
|
|
68
|
+
`scripts/patch-git-source.ts` verifies the pristine ESM/CJS hashes, adds module-local browser Buffer imports for the core and exported filesystem/index helpers, and fixes upstream `compareStats` to compare subsecond timestamps and rehash files in the racy-index window. The patch also uses `HEAD` in local conflict markers, completes clean index changes alongside conflicts, and preserves binary bytes and removes merged additions in upstream `abortMerge`. It is idempotent and refuses changed upstream source. It prevents same-sized edits within a second from appearing clean. The package license files remain in the dependency; `bun run --cwd packages/git notices` emits the complete bundled dependency notices.
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
# Revision queries
|
|
2
|
+
|
|
3
|
+
`git rev-parse` uses the same read-only backend through `installGit` and the bundled
|
|
4
|
+
`/usr/bin/git` program. It never starts native Git, a shell, hooks or config commands.
|
|
5
|
+
|
|
6
|
+
```sh
|
|
7
|
+
git rev-parse HEAD refs/heads/main
|
|
8
|
+
git rev-parse --verify HEAD
|
|
9
|
+
git rev-parse --short=8 HEAD
|
|
10
|
+
git rev-parse --show-toplevel --show-prefix --is-inside-work-tree
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Supported forms
|
|
14
|
+
|
|
15
|
+
- `HEAD`, unambiguous local, tag and remote ref names, and full `refs/...` names produce
|
|
16
|
+
full SHA-1 object IDs. Packed refs, symbolic remote HEAD refs, detached HEAD and annotated
|
|
17
|
+
tag object IDs work through isomorphic-git. Tags are not automatically peeled.
|
|
18
|
+
- Full 40-digit IDs are accepted even when the object is absent, as in Git. Existing,
|
|
19
|
+
unique hexadecimal prefixes of at least four digits resolve to full IDs.
|
|
20
|
+
- Multiple revision operands print one full ID per line in operand order.
|
|
21
|
+
- `--verify` requires exactly one revision. `--short[=N]` implies `--verify` and prints
|
|
22
|
+
a unique object prefix, extending beyond `N` when other loose or packed objects collide.
|
|
23
|
+
Explicit decimal lengths clamp to 4 through 40. The default minimum is seven; numeric
|
|
24
|
+
repository-local `core.abbrev` values from 4 through 40 and `core.abbrev=no` are honored.
|
|
25
|
+
- `--show-toplevel` prints the absolute working-tree root. `--show-prefix` prints the
|
|
26
|
+
repository-relative working directory with a trailing slash, or a blank line at the root.
|
|
27
|
+
Paths containing spaces and Unicode are emitted literally.
|
|
28
|
+
- `--is-inside-work-tree` prints `true` in the working tree and `false` inside its `.git`
|
|
29
|
+
directory. Location queries can be combined and print in option order before revisions.
|
|
30
|
+
`--show-toplevel` inside `.git` fails with status 128.
|
|
31
|
+
|
|
32
|
+
Options must precede operands. Empty arguments produce no output and status 0 inside a
|
|
33
|
+
repository. Outside a repository, queries return status 128. Missing revisions also return
|
|
34
|
+
128; `--verify` emits `fatal: Needed a single revision` without revision output.
|
|
35
|
+
Queries do not change repository files, the index or the working tree.
|
|
36
|
+
|
|
37
|
+
## Deliberate limits
|
|
38
|
+
|
|
39
|
+
Revision expressions such as `HEAD~1`, `HEAD^`, `ref:path`, ranges and reflog selectors,
|
|
40
|
+
path operands, `--`, other options, nondecimal short lengths, and options after an operand
|
|
41
|
+
return status 129. Bare repositories and Git environment overrides such as `GIT_DIR` or
|
|
42
|
+
`GIT_WORK_TREE` are outside this local working-tree interface. Automatic abbreviation
|
|
43
|
+
configuration such as `core.abbrev=auto` is unsupported; use an explicit `--short=N`.
|
|
44
|
+
|
|
45
|
+
Ambiguous ref shorthands return 129 and ask for the full ref name, rather than choosing
|
|
46
|
+
between a branch and a tag. Ambiguous object prefixes return 128 and ask for a longer ID.
|
|
47
|
+
Their diagnostics are Waffle-specific; native Git prints additional ambiguity warnings and
|
|
48
|
+
candidate details. No revision/path disambiguation or shell expansion is performed.
|
|
49
|
+
|
|
50
|
+
## Verification
|
|
51
|
+
|
|
52
|
+
After preparing the Git package, run from `packages/git`:
|
|
53
|
+
|
|
54
|
+
```sh
|
|
55
|
+
node --test tests/git-rev-parse.test.ts
|
|
56
|
+
bun tests/git-rev-parse-browser.ts
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
The first command compares stdout, stderr and status with native Git on disposable fixtures,
|
|
60
|
+
checks collision and refusal behavior, forbids backend filesystem mutations, and exercises
|
|
61
|
+
`dist/git-cli.js` on Bun. Native Git is only a test oracle. The browser smoke uses one real
|
|
62
|
+
Waffle runtime, the public API and installed CLI, the existing process helper, and the
|
|
63
|
+
integrity-checked published Bun guest. Prepare Waffle's real network asset before running
|
|
64
|
+
the browser smoke, as required by the Bun interpreter's runtime integration. The runner
|
|
65
|
+
refuses a missing asset rather than building a guest or using a substitute.
|
|
66
|
+
It checks repository bytes and disposes its runtime,
|
|
67
|
+
browser, listener, downloaded guest and scratch files. It needs network access to that guest.
|
package/package.json
CHANGED
|
@@ -1,6 +1,57 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@waffle-os/git",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.25",
|
|
4
|
+
"description": "Local Git commands for Waffle runtimes, backed by isomorphic-git",
|
|
5
|
+
"license": "Apache-2.0 AND BSD-3-Clause AND ISC AND MIT AND Zlib",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "https://github.com/ShaulLavo/waffle.git",
|
|
9
|
+
"directory": "packages/git"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"dist",
|
|
13
|
+
"src",
|
|
14
|
+
"docs",
|
|
15
|
+
"third-party",
|
|
16
|
+
"LICENSE",
|
|
17
|
+
"README.md",
|
|
18
|
+
"provenance",
|
|
19
|
+
"package-artifacts.json"
|
|
20
|
+
],
|
|
21
|
+
"type": "module",
|
|
22
|
+
"exports": {
|
|
23
|
+
".": "./src/git.ts",
|
|
24
|
+
"./program": "./src/program.ts"
|
|
25
|
+
},
|
|
26
|
+
"dependencies": {
|
|
27
|
+
"buffer": "6.0.3",
|
|
28
|
+
"diff": "8.0.2",
|
|
29
|
+
"isomorphic-git": "1.44.5"
|
|
30
|
+
},
|
|
31
|
+
"peerDependencies": {
|
|
32
|
+
"@waffle-os/runtime": "*"
|
|
33
|
+
},
|
|
34
|
+
"engines": {
|
|
35
|
+
"node": ">=26.12.1"
|
|
36
|
+
},
|
|
37
|
+
"trustedDependencies": [
|
|
38
|
+
"@waffle-os/runtime",
|
|
39
|
+
"bun-wasm",
|
|
40
|
+
"esbuild"
|
|
41
|
+
],
|
|
42
|
+
"waffleHostInterface": 4,
|
|
43
|
+
"gitHead": "6b27558d10a1870b9ae76fad99dbafd69222c62b",
|
|
44
|
+
"waffleCorrespondingSource": {
|
|
45
|
+
"schema": "waffle-corresponding-source/1",
|
|
46
|
+
"filename": "waffle-os-git-source-0c5c2ef0b89d767fc2a7c060c06dde7ae9e4ec682fa73194a2f092fcf79a3899.tar.gz",
|
|
47
|
+
"url": "https://github.com/ShaulLavo/waffle/releases/download/programs-v0.0.25/waffle-os-git-source-0c5c2ef0b89d767fc2a7c060c06dde7ae9e4ec682fa73194a2f092fcf79a3899.tar.gz",
|
|
48
|
+
"bytes": 2292285,
|
|
49
|
+
"sha256": "0c5c2ef0b89d767fc2a7c060c06dde7ae9e4ec682fa73194a2f092fcf79a3899",
|
|
50
|
+
"manifestSha256": "5afd17aedf2bc2e690834d8e3cafdb70329d472cfb6423f0264f93a649d7d8ea"
|
|
51
|
+
},
|
|
52
|
+
"publishConfig": {
|
|
53
|
+
"access": "public",
|
|
54
|
+
"provenance": true,
|
|
55
|
+
"registry": "https://registry.npmjs.org"
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
{
|
|
2
|
+
"schema": "waffle-program-transfer/v1",
|
|
3
|
+
"family": "git",
|
|
4
|
+
"sourceCheckout": "/work/tmp/waffle-programs-git-20261027/packages/git",
|
|
5
|
+
"sourceCommit": "dc6c0f92573ace9620e02691e6c268144908ec74",
|
|
6
|
+
"sourcePaths": ["."],
|
|
7
|
+
"targetPaths": ["packages/git"],
|
|
8
|
+
"installerContract": "waffle filesystem and shebang admission; no WASM fallback or runtime worker"
|
|
9
|
+
}
|
package/src/cli.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { runGit } from "./git-command";
|
|
2
|
+
import { nodeGitFilesystem } from "./node-filesystem";
|
|
3
|
+
|
|
4
|
+
/** The `git` program: the same backend as `installGit`, driven by process argv/cwd/env/stdio. */
|
|
5
|
+
const writer = (stream: NodeJS.WriteStream) => (bytes: Uint8Array) =>
|
|
6
|
+
new Promise<void>((resolve, reject) =>
|
|
7
|
+
stream.write(bytes, (error) => (error ? reject(error) : resolve())),
|
|
8
|
+
);
|
|
9
|
+
const env: Record<string, string> = {};
|
|
10
|
+
for (const [name, value] of Object.entries(process.env)) if (value !== undefined) env[name] = value;
|
|
11
|
+
process.exitCode = await runGit(nodeGitFilesystem, {
|
|
12
|
+
argv: process.argv.slice(2),
|
|
13
|
+
cwd: process.cwd(),
|
|
14
|
+
env,
|
|
15
|
+
stdout: writer(process.stdout),
|
|
16
|
+
stderr: writer(process.stderr),
|
|
17
|
+
});
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import * as git from "isomorphic-git";
|
|
2
|
+
import type { GitFilesystem, GitInvocation } from "./git-types";
|
|
3
|
+
import {
|
|
4
|
+
absolute,
|
|
5
|
+
arity,
|
|
6
|
+
GitFailure,
|
|
7
|
+
options,
|
|
8
|
+
output,
|
|
9
|
+
pathspec,
|
|
10
|
+
selected,
|
|
11
|
+
porcelain,
|
|
12
|
+
type GitContext,
|
|
13
|
+
} from "./git-context";
|
|
14
|
+
import { gitBranch, gitCheckout, gitCommit, gitLog, gitSwitch } from "./git-history";
|
|
15
|
+
import { gitDiff } from "./git-diff";
|
|
16
|
+
import { gitMerge } from "./git-merge";
|
|
17
|
+
import { gitStash } from "./git-stash";
|
|
18
|
+
import { conflictStatus } from "./git-index";
|
|
19
|
+
import { gitRevParse } from "./git-revision";
|
|
20
|
+
|
|
21
|
+
export async function runGit(fs: GitFilesystem, invocation: GitInvocation): Promise<number> {
|
|
22
|
+
try {
|
|
23
|
+
if (!invocation.cwd.startsWith("/")) throw new GitFailure("cwd must be absolute", 129);
|
|
24
|
+
const [command, ...args] = invocation.argv;
|
|
25
|
+
if (command === "--version") {
|
|
26
|
+
await invocation.stdout(
|
|
27
|
+
new TextEncoder().encode(`git version isomorphic-git ${git.version()}\n`),
|
|
28
|
+
);
|
|
29
|
+
return 0;
|
|
30
|
+
}
|
|
31
|
+
if (command === "init") return await gitInit(fs, invocation, args);
|
|
32
|
+
if (command === "rev-parse") return await gitRevParse(fs, invocation, args);
|
|
33
|
+
if (
|
|
34
|
+
![
|
|
35
|
+
"add",
|
|
36
|
+
"commit",
|
|
37
|
+
"status",
|
|
38
|
+
"log",
|
|
39
|
+
"diff",
|
|
40
|
+
"branch",
|
|
41
|
+
"checkout",
|
|
42
|
+
"switch",
|
|
43
|
+
"merge",
|
|
44
|
+
"stash",
|
|
45
|
+
"config",
|
|
46
|
+
].includes(command)
|
|
47
|
+
)
|
|
48
|
+
throw new GitFailure(`unsupported local command '${command ?? ""}'`, 129);
|
|
49
|
+
const dir = await git.findRoot({ fs, filepath: invocation.cwd });
|
|
50
|
+
const context = { fs, dir, invocation };
|
|
51
|
+
const status = await dispatch(context, command, args);
|
|
52
|
+
return typeof status === "number" ? status : 0;
|
|
53
|
+
} catch (error) {
|
|
54
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
55
|
+
await invocation.stderr(new TextEncoder().encode(`git: ${message}\n`));
|
|
56
|
+
return error instanceof GitFailure ? error.status : 128;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async function dispatch(context: GitContext, command: string, args: readonly string[]) {
|
|
61
|
+
switch (command) {
|
|
62
|
+
case "add":
|
|
63
|
+
return gitAdd(context, args);
|
|
64
|
+
case "commit":
|
|
65
|
+
return gitCommit(context, args);
|
|
66
|
+
case "status":
|
|
67
|
+
return gitStatus(context, args);
|
|
68
|
+
case "log":
|
|
69
|
+
return gitLog(context, args);
|
|
70
|
+
case "diff":
|
|
71
|
+
return gitDiff(context, args);
|
|
72
|
+
case "branch":
|
|
73
|
+
return gitBranch(context, args);
|
|
74
|
+
case "checkout":
|
|
75
|
+
return gitCheckout(context, args);
|
|
76
|
+
case "switch":
|
|
77
|
+
return gitSwitch(context, args);
|
|
78
|
+
case "merge":
|
|
79
|
+
return gitMerge(context, args);
|
|
80
|
+
case "stash":
|
|
81
|
+
return gitStash(context, args);
|
|
82
|
+
case "config":
|
|
83
|
+
return gitConfig(context, args);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function gitInit(fs: GitFilesystem, invocation: GitInvocation, args: readonly string[]) {
|
|
88
|
+
const parsed = options(
|
|
89
|
+
args,
|
|
90
|
+
["-q", "--quiet"],
|
|
91
|
+
["-b", "--initial-branch", "--object-format", "--template"],
|
|
92
|
+
);
|
|
93
|
+
arity(parsed.paths, 0, 1);
|
|
94
|
+
if ((parsed.named.get("--object-format") ?? "sha1") !== "sha1")
|
|
95
|
+
throw new GitFailure("only SHA-1 repositories are supported", 129);
|
|
96
|
+
if (parsed.named.get("--template")) throw new GitFailure("templates are unsupported", 129);
|
|
97
|
+
const dir = absolute(invocation.cwd, parsed.paths[0] ?? ".");
|
|
98
|
+
await git.init({
|
|
99
|
+
fs,
|
|
100
|
+
dir,
|
|
101
|
+
defaultBranch: parsed.named.get("-b") ?? parsed.named.get("--initial-branch") ?? "main",
|
|
102
|
+
});
|
|
103
|
+
return 0;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async function gitAdd(context: GitContext, args: readonly string[]) {
|
|
107
|
+
const { flags, paths } = options(args, ["-A", "--all", "-u", "--update", "-f", "--force"]);
|
|
108
|
+
const update = flags.has("-u") || flags.has("--update");
|
|
109
|
+
if (!paths.length && !update && !flags.has("-A") && !flags.has("--all"))
|
|
110
|
+
throw new GitFailure("nothing specified to add", 129);
|
|
111
|
+
const specs = paths.map((path) => pathspec(context, path));
|
|
112
|
+
const force = flags.has("-f") || flags.has("--force");
|
|
113
|
+
const rows = await git.statusMatrix({ ...context, ignored: force });
|
|
114
|
+
for (const spec of specs) await requirePath(context, spec, rows);
|
|
115
|
+
for (const [filepath, head, work, stage] of rows) {
|
|
116
|
+
if (!selected(filepath, specs) || (update && head === 0 && stage === 0)) continue;
|
|
117
|
+
if (work === 0) await git.remove({ ...context, filepath });
|
|
118
|
+
else await git.add({ ...context, filepath, force });
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async function requirePath(context: GitContext, spec: string, rows: git.StatusRow[]) {
|
|
123
|
+
if (spec === "." || rows.some(([path]) => selected(path, [spec]))) return;
|
|
124
|
+
if (await git.isIgnored({ ...context, filepath: spec }))
|
|
125
|
+
throw new GitFailure(`'${spec}' is ignored`, 1);
|
|
126
|
+
throw new GitFailure(`pathspec '${spec}' did not match any files`);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
async function gitStatus(context: GitContext, args: readonly string[]) {
|
|
130
|
+
const parsed = options(
|
|
131
|
+
args,
|
|
132
|
+
["--porcelain", "--short", "-s"],
|
|
133
|
+
["--porcelain", "--untracked-files"],
|
|
134
|
+
);
|
|
135
|
+
if (parsed.named.has("--porcelain") && parsed.named.get("--porcelain") !== "v1")
|
|
136
|
+
throw new GitFailure("only porcelain v1 is supported", 129);
|
|
137
|
+
if (parsed.named.has("--untracked-files") && parsed.named.get("--untracked-files") !== "all")
|
|
138
|
+
throw new GitFailure("only --untracked-files=all is supported", 129);
|
|
139
|
+
const specs = parsed.paths.map((path) => pathspec(context, path));
|
|
140
|
+
const rows = await git.statusMatrix(context);
|
|
141
|
+
await output(
|
|
142
|
+
context,
|
|
143
|
+
porcelain(
|
|
144
|
+
rows.filter(([path]) => selected(path, specs)),
|
|
145
|
+
await conflictStatus(context),
|
|
146
|
+
),
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
async function gitConfig(context: GitContext, args: readonly string[]) {
|
|
151
|
+
const { paths } = options(args, ["--local"]);
|
|
152
|
+
arity(paths, 1, 2);
|
|
153
|
+
if (!["user.name", "user.email"].includes(paths[0]))
|
|
154
|
+
throw new GitFailure("only repository user.name and user.email config are supported", 129);
|
|
155
|
+
if (paths.length === 2) return git.setConfig({ ...context, path: paths[0], value: paths[1] });
|
|
156
|
+
const value = await git.getConfig({ ...context, path: paths[0] });
|
|
157
|
+
if (value === undefined) throw new GitFailure("config entry not found", 1);
|
|
158
|
+
await output(context, `${value}\n`);
|
|
159
|
+
}
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import * as git from "isomorphic-git";
|
|
2
|
+
import type { GitFilesystem, GitInvocation } from "./git-types";
|
|
3
|
+
import { conflictStatus } from "./git-index";
|
|
4
|
+
|
|
5
|
+
export class GitFailure extends Error {
|
|
6
|
+
constructor(
|
|
7
|
+
message: string,
|
|
8
|
+
readonly status = 128,
|
|
9
|
+
) {
|
|
10
|
+
super(message);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface GitContext {
|
|
15
|
+
readonly fs: GitFilesystem;
|
|
16
|
+
readonly dir: string;
|
|
17
|
+
readonly invocation: GitInvocation;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function options(
|
|
21
|
+
args: readonly string[],
|
|
22
|
+
switches: readonly string[],
|
|
23
|
+
values: readonly string[] = [],
|
|
24
|
+
) {
|
|
25
|
+
const flags = new Set<string>();
|
|
26
|
+
const named = new Map<string, string>();
|
|
27
|
+
const paths: string[] = [];
|
|
28
|
+
let literal = false;
|
|
29
|
+
for (let index = 0; index < args.length; index++) {
|
|
30
|
+
const arg = args[index];
|
|
31
|
+
if (literal || !arg.startsWith("-") || arg === "-") {
|
|
32
|
+
paths.push(arg);
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
if (arg === "--") {
|
|
36
|
+
literal = true;
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
if (switches.includes(arg)) {
|
|
40
|
+
flags.add(arg);
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
index = readOption(args, index, named, values);
|
|
44
|
+
}
|
|
45
|
+
return { flags, named, paths };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function readOption(
|
|
49
|
+
args: readonly string[],
|
|
50
|
+
index: number,
|
|
51
|
+
named: Map<string, string>,
|
|
52
|
+
values: readonly string[],
|
|
53
|
+
) {
|
|
54
|
+
const arg = args[index];
|
|
55
|
+
const equals = arg.indexOf("=");
|
|
56
|
+
const key = equals < 0 ? arg : arg.slice(0, equals);
|
|
57
|
+
if (!values.includes(key)) throw new GitFailure(`unsupported option '${arg}'`, 129);
|
|
58
|
+
const value = equals < 0 ? args[index + 1] : arg.slice(equals + 1);
|
|
59
|
+
if (value === undefined) throw new GitFailure(`option '${key}' needs a value`, 129);
|
|
60
|
+
named.set(key, value);
|
|
61
|
+
return equals < 0 ? index + 1 : index;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function arity(paths: readonly string[], minimum: number, maximum = minimum) {
|
|
65
|
+
if (paths.length < minimum || paths.length > maximum)
|
|
66
|
+
throw new GitFailure("unexpected arguments", 129);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function absolute(base: string, path: string): string {
|
|
70
|
+
const parts = (path.startsWith("/") ? path : `${base}/${path}`).split("/");
|
|
71
|
+
const result: string[] = [];
|
|
72
|
+
for (const part of parts) {
|
|
73
|
+
if (!part || part === ".") continue;
|
|
74
|
+
if (part === "..") result.pop();
|
|
75
|
+
else result.push(part);
|
|
76
|
+
}
|
|
77
|
+
return `/${result.join("/")}`;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function pathspec(context: GitContext, path: string): string {
|
|
81
|
+
const resolved = absolute(context.invocation.cwd, path);
|
|
82
|
+
if (resolved === context.dir) return ".";
|
|
83
|
+
const prefix = context.dir === "/" ? "/" : `${context.dir}/`;
|
|
84
|
+
if (!resolved.startsWith(prefix)) throw new GitFailure(`'${path}' is outside the repository`);
|
|
85
|
+
const relative = resolved.slice(prefix.length);
|
|
86
|
+
if (relative === ".git" || relative.startsWith(".git/"))
|
|
87
|
+
throw new GitFailure("cannot add Git metadata");
|
|
88
|
+
if (/[*?[\]:]/.test(relative))
|
|
89
|
+
throw new GitFailure("wildcard and magic pathspecs are unsupported", 129);
|
|
90
|
+
return relative;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function selected(path: string, specs: readonly string[]) {
|
|
94
|
+
return (
|
|
95
|
+
specs.length === 0 ||
|
|
96
|
+
specs.some((spec) => spec === "." || path === spec || path.startsWith(`${spec}/`))
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export async function text(fs: GitFilesystem, path: string): Promise<string> {
|
|
101
|
+
const contents = await fs.promises.readFile(path, "utf8");
|
|
102
|
+
return typeof contents === "string" ? contents : new TextDecoder().decode(contents);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export async function exists(fs: GitFilesystem, path: string): Promise<boolean> {
|
|
106
|
+
try {
|
|
107
|
+
await fs.promises.stat(path);
|
|
108
|
+
return true;
|
|
109
|
+
} catch (error) {
|
|
110
|
+
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT")
|
|
111
|
+
return false;
|
|
112
|
+
throw error;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export async function output(context: GitContext, value: string) {
|
|
117
|
+
if (value) await context.invocation.stdout(new TextEncoder().encode(value));
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export async function identity(context: GitContext, kind: "AUTHOR" | "COMMITTER") {
|
|
121
|
+
const env = context.invocation.env ?? {};
|
|
122
|
+
const name = env[`GIT_${kind}_NAME`] ?? (await git.getConfig({ ...context, path: "user.name" }));
|
|
123
|
+
const email =
|
|
124
|
+
env[`GIT_${kind}_EMAIL`] ?? (await git.getConfig({ ...context, path: "user.email" }));
|
|
125
|
+
if (!name || !email)
|
|
126
|
+
throw new GitFailure(
|
|
127
|
+
"identity unknown; set GIT_AUTHOR_NAME/GIT_AUTHOR_EMAIL or repository user config",
|
|
128
|
+
);
|
|
129
|
+
const rawDate = env[`GIT_${kind}_DATE`];
|
|
130
|
+
if (!rawDate) return { name, email };
|
|
131
|
+
const raw = /^@?(\d+) ([+-])(\d{2})(\d{2})$/.exec(rawDate);
|
|
132
|
+
if (raw)
|
|
133
|
+
return {
|
|
134
|
+
name,
|
|
135
|
+
email,
|
|
136
|
+
timestamp: Number(raw[1]),
|
|
137
|
+
timezoneOffset: timezoneOffset(raw[2], Number(raw[3]), Number(raw[4])),
|
|
138
|
+
};
|
|
139
|
+
const timestamp = Date.parse(rawDate);
|
|
140
|
+
const zone = /([+-])(\d{2}):?(\d{2})$/.exec(rawDate);
|
|
141
|
+
if (!Number.isFinite(timestamp) || !zone) throw new GitFailure(`invalid date '${rawDate}'`);
|
|
142
|
+
return {
|
|
143
|
+
name,
|
|
144
|
+
email,
|
|
145
|
+
timestamp: Math.floor(timestamp / 1000),
|
|
146
|
+
timezoneOffset: timezoneOffset(zone[1], Number(zone[2]), Number(zone[3])),
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function timezoneOffset(sign: string, hours: number, minutes: number): number {
|
|
151
|
+
const offset = (sign === "+" ? -1 : 1) * (hours * 60 + minutes);
|
|
152
|
+
return Object.is(offset, -0) ? 0 : offset;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export async function clean(context: GitContext) {
|
|
156
|
+
if ((await conflictStatus(context)).size) throw new GitFailure("unresolved merge conflicts", 1);
|
|
157
|
+
const rows = await git.statusMatrix(context);
|
|
158
|
+
if (
|
|
159
|
+
rows.some(
|
|
160
|
+
([, head, work, stage]) => (head !== 0 || stage !== 0) && (head !== work || head !== stage),
|
|
161
|
+
)
|
|
162
|
+
)
|
|
163
|
+
throw new GitFailure("local changes would be overwritten", 1);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function statusLine([path, head, work, stage]: git.StatusRow): string {
|
|
167
|
+
if (head === 0 && stage === 0) return work === 0 ? "" : `?? ${quote(path)}\n`;
|
|
168
|
+
const index = stage === head ? " " : stage === 0 ? "D" : head === 0 ? "A" : "M";
|
|
169
|
+
const working = work === stage ? " " : work === 0 ? "D" : "M";
|
|
170
|
+
return index === " " && working === " " ? "" : `${index}${working} ${quote(path)}\n`;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export function porcelain(
|
|
174
|
+
rows: git.StatusRow[],
|
|
175
|
+
conflicts: ReadonlyMap<string, string> = new Map(),
|
|
176
|
+
) {
|
|
177
|
+
const tracked = rows.filter(([, head, , stage]) => head !== 0 || stage !== 0);
|
|
178
|
+
const untracked = rows.filter(([, head, , stage]) => head === 0 && stage === 0);
|
|
179
|
+
return tracked
|
|
180
|
+
.concat(untracked)
|
|
181
|
+
.map((row) =>
|
|
182
|
+
conflicts.has(row[0]) ? `${conflicts.get(row[0])} ${quote(row[0])}\n` : statusLine(row),
|
|
183
|
+
)
|
|
184
|
+
.join("");
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function quote(path: string): string {
|
|
188
|
+
return /[\s"\\]/.test(path) ? JSON.stringify(path) : path;
|
|
189
|
+
}
|