@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-diff.ts
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import * as git from "isomorphic-git";
|
|
2
|
+
import { structuredPatch } from "diff";
|
|
3
|
+
import { options, output, pathspec, selected, type GitContext } from "./git-context";
|
|
4
|
+
|
|
5
|
+
export async function gitDiff(context: GitContext, args: readonly string[]) {
|
|
6
|
+
const parsed = options(args, [
|
|
7
|
+
"--cached",
|
|
8
|
+
"--staged",
|
|
9
|
+
"--name-only",
|
|
10
|
+
"--no-prefix",
|
|
11
|
+
"--no-color",
|
|
12
|
+
"--no-ext-diff",
|
|
13
|
+
"--exit-code",
|
|
14
|
+
"--quiet",
|
|
15
|
+
]);
|
|
16
|
+
const specs = parsed.paths.map((path) => pathspec(context, path));
|
|
17
|
+
const cached = parsed.flags.has("--cached") || parsed.flags.has("--staged");
|
|
18
|
+
const patches: { path: string; text: string }[] = [];
|
|
19
|
+
await git.walk({
|
|
20
|
+
...context,
|
|
21
|
+
trees: cached ? [git.TREE({ ref: "HEAD" }), git.STAGE()] : [git.STAGE(), git.WORKDIR()],
|
|
22
|
+
async map(path, entries) {
|
|
23
|
+
const [before, after] = entries;
|
|
24
|
+
if (path === "." || !selected(path, specs)) return;
|
|
25
|
+
if ((await before?.type()) === "tree" || (await after?.type()) === "tree") return;
|
|
26
|
+
if (!cached && !before) return;
|
|
27
|
+
const oldOid = await before?.oid();
|
|
28
|
+
const newOid = await after?.oid();
|
|
29
|
+
if (oldOid === newOid) return;
|
|
30
|
+
const patch = parsed.flags.has("--name-only")
|
|
31
|
+
? `${path}\n`
|
|
32
|
+
: await patchFor(context, path, before, after, parsed.flags.has("--no-prefix"));
|
|
33
|
+
patches.push({ path, text: patch });
|
|
34
|
+
},
|
|
35
|
+
});
|
|
36
|
+
patches.sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0));
|
|
37
|
+
if (!parsed.flags.has("--quiet"))
|
|
38
|
+
await output(context, patches.map((patch) => patch.text).join(""));
|
|
39
|
+
return patches.length && (parsed.flags.has("--exit-code") || parsed.flags.has("--quiet")) ? 1 : 0;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
type WalkerEntry = Parameters<NonNullable<Parameters<typeof git.walk>[0]["map"]>>[1][number];
|
|
43
|
+
|
|
44
|
+
async function patchFor(
|
|
45
|
+
context: GitContext,
|
|
46
|
+
path: string,
|
|
47
|
+
before: WalkerEntry,
|
|
48
|
+
after: WalkerEntry,
|
|
49
|
+
noPrefix: boolean,
|
|
50
|
+
) {
|
|
51
|
+
const oldBytes = await content(context, before);
|
|
52
|
+
const newBytes = await content(context, after);
|
|
53
|
+
const oldOid = ((await before?.oid()) ?? "0000000").slice(0, 7);
|
|
54
|
+
const newOid = ((await after?.oid()) ?? "0000000").slice(0, 7);
|
|
55
|
+
const oldPath = `${noPrefix ? "" : "a/"}${path}`;
|
|
56
|
+
const newPath = `${noPrefix ? "" : "b/"}${path}`;
|
|
57
|
+
const headers = [`diff --git ${oldPath} ${newPath}`];
|
|
58
|
+
if (!before) headers.push("new file mode 100644");
|
|
59
|
+
if (!after) headers.push("deleted file mode 100644");
|
|
60
|
+
headers.push(`index ${oldOid}..${newOid}${before && after ? " 100644" : ""}`);
|
|
61
|
+
if (oldBytes.includes(0) || newBytes.includes(0))
|
|
62
|
+
return headers
|
|
63
|
+
.concat([
|
|
64
|
+
`Binary files ${before ? oldPath : "/dev/null"} and ${after ? newPath : "/dev/null"} differ`,
|
|
65
|
+
"",
|
|
66
|
+
])
|
|
67
|
+
.join("\n");
|
|
68
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
69
|
+
const patch = structuredPatch(
|
|
70
|
+
oldPath,
|
|
71
|
+
newPath,
|
|
72
|
+
decoder.decode(oldBytes),
|
|
73
|
+
decoder.decode(newBytes),
|
|
74
|
+
undefined,
|
|
75
|
+
undefined,
|
|
76
|
+
{ context: 3 },
|
|
77
|
+
);
|
|
78
|
+
headers.push(
|
|
79
|
+
`--- ${before ? headerPath(oldPath) : "/dev/null"}`,
|
|
80
|
+
`+++ ${after ? headerPath(newPath) : "/dev/null"}`,
|
|
81
|
+
);
|
|
82
|
+
return headers
|
|
83
|
+
.concat(
|
|
84
|
+
patch.hunks.flatMap((hunk) =>
|
|
85
|
+
[
|
|
86
|
+
`@@ -${range(hunk.oldStart, hunk.oldLines)} +${range(hunk.newStart, hunk.newLines)} @@`,
|
|
87
|
+
].concat(hunk.lines),
|
|
88
|
+
),
|
|
89
|
+
[""],
|
|
90
|
+
)
|
|
91
|
+
.join("\n");
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async function content(context: GitContext, entry: WalkerEntry) {
|
|
95
|
+
if (!entry) return new Uint8Array();
|
|
96
|
+
const bytes = await entry.content();
|
|
97
|
+
if (bytes) return bytes;
|
|
98
|
+
const oid = await entry.oid();
|
|
99
|
+
if (!oid) return new Uint8Array();
|
|
100
|
+
return (await git.readBlob({ ...context, oid })).blob;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function headerPath(path: string) {
|
|
104
|
+
return path.includes(" ") ? `${path}\t` : path;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function range(start: number, length: number) {
|
|
108
|
+
if (length === 0) return `${start - 1},0`;
|
|
109
|
+
return length === 1 ? String(start) : `${start},${length}`;
|
|
110
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import type { Runtime } from "@waffle-os/runtime";
|
|
2
|
+
import type { GitFilesystem, GitStat } from "./git-types";
|
|
3
|
+
|
|
4
|
+
class GitFilesystemError extends Error {
|
|
5
|
+
readonly code: string;
|
|
6
|
+
constructor(code: string, path: string) {
|
|
7
|
+
super(`${code}: ${path}`);
|
|
8
|
+
this.code = code;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Adapt only the caller's public Waffle filesystem capability, never its owner. */
|
|
13
|
+
export function gitFilesystem(filesystem: Runtime["filesystem"]): GitFilesystem {
|
|
14
|
+
const entry = async (path: string) => {
|
|
15
|
+
const found = await filesystem.lookup(path);
|
|
16
|
+
if (!found) throw new GitFilesystemError("ENOENT", path);
|
|
17
|
+
if (found.kind === "symlink") throw new GitFilesystemError("ENOTSUP", path);
|
|
18
|
+
return found;
|
|
19
|
+
};
|
|
20
|
+
const directory = async (path: string) => {
|
|
21
|
+
const found = await entry(path);
|
|
22
|
+
if (found.kind !== "dir") throw new GitFilesystemError("ENOTDIR", path);
|
|
23
|
+
return found;
|
|
24
|
+
};
|
|
25
|
+
const stat = async (path: string): Promise<GitStat> => {
|
|
26
|
+
const found = await entry(path);
|
|
27
|
+
const bytes = found.kind === "file" ? await filesystem.readFile(path) : undefined;
|
|
28
|
+
return {
|
|
29
|
+
mode: found.kind === "file" ? 0o100644 : 0o040755,
|
|
30
|
+
size: bytes?.byteLength ?? 0,
|
|
31
|
+
ino: found.ino,
|
|
32
|
+
mtimeMs: found.mtime,
|
|
33
|
+
ctimeMs: found.ctime,
|
|
34
|
+
uid: 0,
|
|
35
|
+
gid: 0,
|
|
36
|
+
dev: 0,
|
|
37
|
+
isFile: () => found.kind === "file",
|
|
38
|
+
isDirectory: () => found.kind === "dir",
|
|
39
|
+
isSymbolicLink: () => false,
|
|
40
|
+
};
|
|
41
|
+
};
|
|
42
|
+
return {
|
|
43
|
+
promises: {
|
|
44
|
+
async readFile(path, encoding) {
|
|
45
|
+
const found = await entry(path);
|
|
46
|
+
if (found.kind !== "file") throw new GitFilesystemError("EISDIR", path);
|
|
47
|
+
const bytes = await filesystem.readFile(path);
|
|
48
|
+
if (!bytes) throw new GitFilesystemError("ENOENT", path);
|
|
49
|
+
const format = typeof encoding === "string" ? encoding : encoding?.encoding;
|
|
50
|
+
return format ? new TextDecoder().decode(bytes) : bytes;
|
|
51
|
+
},
|
|
52
|
+
async writeFile(path, data) {
|
|
53
|
+
const existing = await filesystem.lookup(path);
|
|
54
|
+
if (existing && existing.kind !== "file") throw new GitFilesystemError("ENOTSUP", path);
|
|
55
|
+
await directory(path.slice(0, path.lastIndexOf("/")) || "/");
|
|
56
|
+
await filesystem.writeFile(path, data);
|
|
57
|
+
},
|
|
58
|
+
async unlink(path) {
|
|
59
|
+
const found = await entry(path);
|
|
60
|
+
if (found.kind !== "file") throw new GitFilesystemError("EISDIR", path);
|
|
61
|
+
await filesystem.remove(path);
|
|
62
|
+
},
|
|
63
|
+
async readdir(path) {
|
|
64
|
+
return Array.from((await directory(path)).children.keys());
|
|
65
|
+
},
|
|
66
|
+
async mkdir(path) {
|
|
67
|
+
if (await filesystem.lookup(path)) throw new GitFilesystemError("EEXIST", path);
|
|
68
|
+
await directory(path.slice(0, path.lastIndexOf("/")) || "/");
|
|
69
|
+
await filesystem.mkdirp(path);
|
|
70
|
+
},
|
|
71
|
+
async rmdir(path) {
|
|
72
|
+
if ((await directory(path)).children.size) throw new GitFilesystemError("ENOTEMPTY", path);
|
|
73
|
+
await filesystem.remove(path);
|
|
74
|
+
},
|
|
75
|
+
stat,
|
|
76
|
+
lstat: stat,
|
|
77
|
+
async readlink(path) {
|
|
78
|
+
throw new GitFilesystemError("ENOTSUP", path);
|
|
79
|
+
},
|
|
80
|
+
async symlink(_target, path) {
|
|
81
|
+
throw new GitFilesystemError("ENOTSUP", path);
|
|
82
|
+
},
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { clearMerge } from "./git-merge";
|
|
2
|
+
import * as git from "isomorphic-git";
|
|
3
|
+
import {
|
|
4
|
+
arity,
|
|
5
|
+
clean,
|
|
6
|
+
GitFailure,
|
|
7
|
+
identity,
|
|
8
|
+
exists,
|
|
9
|
+
text,
|
|
10
|
+
options,
|
|
11
|
+
output,
|
|
12
|
+
type GitContext,
|
|
13
|
+
} from "./git-context";
|
|
14
|
+
|
|
15
|
+
export async function gitCommit(context: GitContext, args: readonly string[]) {
|
|
16
|
+
const parsed = options(args, ["--allow-empty", "-q", "--quiet"], ["-m", "--message"]);
|
|
17
|
+
arity(parsed.paths, 0);
|
|
18
|
+
const message = parsed.named.get("-m") ?? parsed.named.get("--message");
|
|
19
|
+
if (!message)
|
|
20
|
+
throw new GitFailure(
|
|
21
|
+
"commit requires a nonempty -m message; editors and hooks are unsupported",
|
|
22
|
+
129,
|
|
23
|
+
);
|
|
24
|
+
const mergeHead = `${context.dir}/.git/MERGE_HEAD`;
|
|
25
|
+
const parent = (await exists(context.fs, mergeHead))
|
|
26
|
+
? [
|
|
27
|
+
await git.resolveRef({ ...context, ref: "HEAD" }),
|
|
28
|
+
(await text(context.fs, mergeHead)).trim(),
|
|
29
|
+
]
|
|
30
|
+
: undefined;
|
|
31
|
+
const author = await identity(context, "AUTHOR");
|
|
32
|
+
const committer = await identity(context, "COMMITTER");
|
|
33
|
+
try {
|
|
34
|
+
await git.commit({
|
|
35
|
+
...context,
|
|
36
|
+
message,
|
|
37
|
+
author,
|
|
38
|
+
committer,
|
|
39
|
+
disallowEmpty: parent === undefined && !parsed.flags.has("--allow-empty"),
|
|
40
|
+
parent,
|
|
41
|
+
});
|
|
42
|
+
if (parent) await clearMerge(context);
|
|
43
|
+
} catch (error) {
|
|
44
|
+
if (error && typeof error === "object" && "code" in error && error.code === "EmptyCommitError")
|
|
45
|
+
throw new GitFailure("nothing to commit", 1);
|
|
46
|
+
throw error;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export async function gitLog(context: GitContext, args: readonly string[]) {
|
|
51
|
+
const parsed = options(
|
|
52
|
+
args,
|
|
53
|
+
["--oneline", "--first-parent"],
|
|
54
|
+
["--format", "--pretty", "-n", "--max-count"],
|
|
55
|
+
);
|
|
56
|
+
arity(parsed.paths, 0, 1);
|
|
57
|
+
const format =
|
|
58
|
+
parsed.named.get("--format") ??
|
|
59
|
+
parsed.named.get("--pretty")?.replace(/^format:/, "") ??
|
|
60
|
+
(parsed.flags.has("--oneline") ? "%h %s" : "medium");
|
|
61
|
+
if (!new Set(["medium", "%s", "%H", "%h %s", "%H %s"]).has(format))
|
|
62
|
+
throw new GitFailure("unsupported log format", 129);
|
|
63
|
+
const count = Number(
|
|
64
|
+
parsed.named.get("-n") ?? parsed.named.get("--max-count") ?? Number.MAX_SAFE_INTEGER,
|
|
65
|
+
);
|
|
66
|
+
if (!Number.isSafeInteger(count) || count < 0) throw new GitFailure("invalid log count", 129);
|
|
67
|
+
const ref = parsed.paths[0] ?? "HEAD";
|
|
68
|
+
if (count === 0) return;
|
|
69
|
+
const commits = parsed.flags.has("--first-parent")
|
|
70
|
+
? await firstParent(context, ref, count)
|
|
71
|
+
: await git.log({ ...context, ref, depth: count });
|
|
72
|
+
if (format === "medium") return output(context, commits.map(medium).join("\n"));
|
|
73
|
+
await output(
|
|
74
|
+
context,
|
|
75
|
+
commits
|
|
76
|
+
.map(
|
|
77
|
+
({ oid, commit }) =>
|
|
78
|
+
`${format.replace("%H", oid).replace("%h", oid.slice(0, 7)).replace("%s", commit.message.split("\n")[0])}\n`,
|
|
79
|
+
)
|
|
80
|
+
.join(""),
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Git's default `log` layout: header, author, author date in its own zone, indented message. */
|
|
85
|
+
function medium({ oid, commit }: Awaited<ReturnType<typeof git.log>>[number]) {
|
|
86
|
+
const { name, email, timestamp, timezoneOffset } = commit.author;
|
|
87
|
+
const merge = commit.parent.length > 1 ? `Merge: ${commit.parent.map((parent) => parent.slice(0, 7)).join(" ")}\n` : "";
|
|
88
|
+
const body = commit.message.replace(/\n+$/, "").split("\n").map((line) => ` ${line}`).join("\n");
|
|
89
|
+
return `commit ${oid}\n${merge}Author: ${name} <${email}>\nDate: ${authorDate(timestamp, timezoneOffset)}\n\n${body}\n`;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
|
|
93
|
+
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
|
94
|
+
|
|
95
|
+
/** isomorphic-git stores the zone like Date#getTimezoneOffset: minutes west of UTC. */
|
|
96
|
+
function authorDate(seconds: number, offsetMinutes: number) {
|
|
97
|
+
const east = -offsetMinutes;
|
|
98
|
+
const local = new Date((seconds + east * 60) * 1000);
|
|
99
|
+
const pad = (value: number) => String(value).padStart(2, "0");
|
|
100
|
+
const zone = `${east < 0 ? "-" : "+"}${pad(Math.floor(Math.abs(east) / 60))}${pad(Math.abs(east) % 60)}`;
|
|
101
|
+
const time = `${pad(local.getUTCHours())}:${pad(local.getUTCMinutes())}:${pad(local.getUTCSeconds())}`;
|
|
102
|
+
return `${DAYS[local.getUTCDay()]} ${MONTHS[local.getUTCMonth()]} ${local.getUTCDate()} ${time} ${local.getUTCFullYear()} ${zone}`;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function firstParent(context: GitContext, ref: string, count: number) {
|
|
106
|
+
const commits: Awaited<ReturnType<typeof git.log>> = [];
|
|
107
|
+
let oid: string | undefined = await git.resolveRef({ ...context, ref });
|
|
108
|
+
while (oid && commits.length < count) {
|
|
109
|
+
const result = await git.readCommit({ ...context, oid });
|
|
110
|
+
commits.push(result);
|
|
111
|
+
oid = result.commit.parent[0];
|
|
112
|
+
}
|
|
113
|
+
return commits;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export async function gitBranch(context: GitContext, args: readonly string[]) {
|
|
117
|
+
const parsed = options(args, ["--list", "--show-current", "-d", "-D"]);
|
|
118
|
+
const current = await git.currentBranch(context);
|
|
119
|
+
if (parsed.flags.has("--show-current")) {
|
|
120
|
+
arity(parsed.paths, 0);
|
|
121
|
+
return output(context, current ? `${current}\n` : "");
|
|
122
|
+
}
|
|
123
|
+
if (!parsed.paths.length) {
|
|
124
|
+
const branches = await git.listBranches(context);
|
|
125
|
+
return output(
|
|
126
|
+
context,
|
|
127
|
+
branches.map((branch) => `${branch === current ? "*" : " "} ${branch}\n`).join(""),
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
arity(parsed.paths, 1, parsed.flags.has("-d") || parsed.flags.has("-D") ? 1 : 2);
|
|
131
|
+
if (parsed.flags.has("--list")) throw new GitFailure("branch list patterns are unsupported", 129);
|
|
132
|
+
const ref = parsed.paths[0];
|
|
133
|
+
if (!parsed.flags.has("-d") && !parsed.flags.has("-D"))
|
|
134
|
+
return git.branch({ ...context, ref, object: parsed.paths[1] });
|
|
135
|
+
if (ref === current) throw new GitFailure("cannot delete the checked out branch", 1);
|
|
136
|
+
if (!parsed.flags.has("-D")) await requireMerged(context, ref);
|
|
137
|
+
await git.deleteBranch({ ...context, ref });
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async function requireMerged(context: GitContext, ref: string) {
|
|
141
|
+
const oid = await git.resolveRef({ ...context, ref: "HEAD" });
|
|
142
|
+
const ancestor = await git.resolveRef({ ...context, ref });
|
|
143
|
+
if (oid === ancestor || (await git.isDescendent({ ...context, oid, ancestor }))) return;
|
|
144
|
+
throw new GitFailure(`branch '${ref}' is not fully merged`, 1);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export async function gitCheckout(context: GitContext, args: readonly string[]) {
|
|
148
|
+
const parsed = options(args, [], ["-b"]);
|
|
149
|
+
if (await exists(context.fs, `${context.dir}/.git/MERGE_HEAD`))
|
|
150
|
+
throw new GitFailure("finish or abort the current merge first", 1);
|
|
151
|
+
arity(parsed.paths, parsed.named.has("-b") ? 0 : 1, 1);
|
|
152
|
+
await clean(context);
|
|
153
|
+
const created = parsed.named.get("-b");
|
|
154
|
+
if (created !== undefined) return createAndCheckout(context, created, parsed.paths[0] ?? "HEAD");
|
|
155
|
+
const ref = parsed.paths[0];
|
|
156
|
+
await requireCheckoutRef(context, ref);
|
|
157
|
+
// Like Git, a local branch wins over a same-named tag and keeps HEAD symbolic.
|
|
158
|
+
const local = (await git.listBranches(context)).includes(ref);
|
|
159
|
+
await git.checkout({ ...context, ref: local ? `refs/heads/${ref}` : ref });
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Check the start point can be installed before writing the branch, so a refused
|
|
163
|
+
* create-and-switch leaves refs, HEAD, index and worktree untouched. */
|
|
164
|
+
async function createAndCheckout(context: GitContext, branch: string, start: string) {
|
|
165
|
+
await requireCheckoutRef(context, start);
|
|
166
|
+
const oid = await git.resolveRef({ ...context, ref: start });
|
|
167
|
+
await git.checkout({ ...context, ref: oid, dryRun: true });
|
|
168
|
+
await git.branch({ ...context, ref: branch, object: oid });
|
|
169
|
+
await git.checkout({ ...context, ref: `refs/heads/${branch}` });
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** `switch` is checkout restricted to local branches: `-c` creates, otherwise the branch must exist. */
|
|
173
|
+
export async function gitSwitch(context: GitContext, args: readonly string[]) {
|
|
174
|
+
const parsed = options(args, [], ["-c", "--create"]);
|
|
175
|
+
const created = parsed.named.get("-c") ?? parsed.named.get("--create");
|
|
176
|
+
if (created !== undefined) return gitCheckout(context, ["-b", created].concat(parsed.paths));
|
|
177
|
+
arity(parsed.paths, 1, 1);
|
|
178
|
+
const branches = await git.listBranches(context);
|
|
179
|
+
if (!branches.includes(parsed.paths[0]))
|
|
180
|
+
throw new GitFailure(`invalid reference: ${parsed.paths[0]}`, 128);
|
|
181
|
+
return gitCheckout(context, parsed.paths);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
async function requireCheckoutRef(context: GitContext, ref: string) {
|
|
185
|
+
try {
|
|
186
|
+
await git.resolveRef({ ...context, ref });
|
|
187
|
+
} catch {
|
|
188
|
+
throw new GitFailure(`pathspec '${ref}' did not match a local revision`, 1);
|
|
189
|
+
}
|
|
190
|
+
}
|
package/src/git-index.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { GitIndexManager } from "isomorphic-git/managers";
|
|
2
|
+
import { FileSystem } from "isomorphic-git/models";
|
|
3
|
+
import type { GitContext } from "./git-context";
|
|
4
|
+
|
|
5
|
+
/** Read upstream's parsed conflict stages rather than infer them from worktree text. */
|
|
6
|
+
export async function conflictStatus(context: Pick<GitContext, "fs" | "dir">) {
|
|
7
|
+
const result = new Map<string, string>();
|
|
8
|
+
await GitIndexManager.acquire(
|
|
9
|
+
{ fs: new FileSystem(context.fs), gitdir: `${context.dir}/.git`, cache: {} },
|
|
10
|
+
(index) => {
|
|
11
|
+
for (const entry of index.entries) addConflict(result, entry);
|
|
12
|
+
},
|
|
13
|
+
);
|
|
14
|
+
return result;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function addConflict(result: Map<string, string>, entry: unknown) {
|
|
18
|
+
if (!entry || typeof entry !== "object" || !("path" in entry) || !("stages" in entry))
|
|
19
|
+
throw new Error("Invalid upstream index entry");
|
|
20
|
+
if (typeof entry.path !== "string" || !Array.isArray(entry.stages))
|
|
21
|
+
throw new Error("Invalid upstream index stages");
|
|
22
|
+
const stages = entry.stages;
|
|
23
|
+
if (stages[0]) return;
|
|
24
|
+
const mask = (stages[1] ? 1 : 0) | (stages[2] ? 2 : 0) | (stages[3] ? 4 : 0);
|
|
25
|
+
const status = ["", "DD", "AU", "UD", "UA", "DU", "AA", "UU"][mask];
|
|
26
|
+
if (!status) throw new Error("Invalid upstream conflict stages");
|
|
27
|
+
result.set(entry.path, status);
|
|
28
|
+
}
|
package/src/git-merge.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import * as git from "isomorphic-git";
|
|
2
|
+
import {
|
|
3
|
+
arity,
|
|
4
|
+
clean,
|
|
5
|
+
exists,
|
|
6
|
+
GitFailure,
|
|
7
|
+
identity,
|
|
8
|
+
options,
|
|
9
|
+
type GitContext,
|
|
10
|
+
} from "./git-context";
|
|
11
|
+
|
|
12
|
+
export async function clearMerge(context: GitContext) {
|
|
13
|
+
for (const name of ["MERGE_HEAD", "MERGE_MSG"]) {
|
|
14
|
+
const path = `${context.dir}/.git/${name}`;
|
|
15
|
+
if (await exists(context.fs, path)) await context.fs.promises.unlink(path);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export async function gitMerge(context: GitContext, args: readonly string[]) {
|
|
20
|
+
const parsed = options(args, ["--ff-only", "--no-ff", "--abort"], ["-m", "--message"]);
|
|
21
|
+
const merging = await exists(context.fs, `${context.dir}/.git/MERGE_HEAD`);
|
|
22
|
+
if (parsed.flags.has("--abort")) {
|
|
23
|
+
arity(args, 1);
|
|
24
|
+
if (!merging) throw new GitFailure("no merge to abort");
|
|
25
|
+
await git.abortMerge(context);
|
|
26
|
+
return clearMerge(context);
|
|
27
|
+
}
|
|
28
|
+
arity(parsed.paths, 1);
|
|
29
|
+
if (merging) throw new GitFailure("finish or abort the current merge first", 1);
|
|
30
|
+
if (parsed.flags.has("--ff-only") && parsed.flags.has("--no-ff"))
|
|
31
|
+
throw new GitFailure("incompatible merge flags", 129);
|
|
32
|
+
await clean(context);
|
|
33
|
+
const theirs = parsed.paths[0];
|
|
34
|
+
const ref = await git.currentBranch(context);
|
|
35
|
+
if (!ref) throw new GitFailure("merging in detached HEAD is unsupported", 129);
|
|
36
|
+
const author = await identity(context, "AUTHOR");
|
|
37
|
+
const committer = await identity(context, "COMMITTER");
|
|
38
|
+
const message = parsed.named.get("-m") ?? parsed.named.get("--message");
|
|
39
|
+
const merge = {
|
|
40
|
+
...context,
|
|
41
|
+
theirs,
|
|
42
|
+
author,
|
|
43
|
+
committer,
|
|
44
|
+
fastForward: !parsed.flags.has("--no-ff"),
|
|
45
|
+
fastForwardOnly: parsed.flags.has("--ff-only"),
|
|
46
|
+
message,
|
|
47
|
+
};
|
|
48
|
+
// The checkout preflight prevents an untracked file from being overwritten.
|
|
49
|
+
await git.checkout({ ...context, ref: theirs, dryRun: true, noUpdateHead: true });
|
|
50
|
+
const head = await git.resolveRef({ ...context, ref: "HEAD" });
|
|
51
|
+
const theirHead = await git.resolveRef({ ...context, ref: theirs });
|
|
52
|
+
try {
|
|
53
|
+
await git.merge({ ...merge, abortOnConflict: false });
|
|
54
|
+
await git.checkout({ ...context, ref });
|
|
55
|
+
} catch (error) {
|
|
56
|
+
if (!(error instanceof git.Errors.MergeConflictError)) throw error;
|
|
57
|
+
await context.fs.promises.writeFile(`${context.dir}/.git/ORIG_HEAD`, `${head}\n`);
|
|
58
|
+
await context.fs.promises.writeFile(`${context.dir}/.git/MERGE_HEAD`, `${theirHead}\n`);
|
|
59
|
+
await context.fs.promises.writeFile(
|
|
60
|
+
`${context.dir}/.git/MERGE_MSG`,
|
|
61
|
+
`${message ?? `Merge branch '${theirs}'`}\n`,
|
|
62
|
+
);
|
|
63
|
+
throw new GitFailure(error.message, 1);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import * as git from "isomorphic-git";
|
|
2
|
+
import { absolute, exists, GitFailure, output, type GitContext } from "./git-context";
|
|
3
|
+
import type { GitFilesystem, GitInvocation } from "./git-types";
|
|
4
|
+
|
|
5
|
+
type LocationQuery = "--show-toplevel" | "--show-prefix" | "--is-inside-work-tree";
|
|
6
|
+
|
|
7
|
+
interface RevisionQuery {
|
|
8
|
+
readonly locations: readonly LocationQuery[];
|
|
9
|
+
readonly refs: readonly string[];
|
|
10
|
+
readonly verify: boolean;
|
|
11
|
+
readonly short: number | "default" | null;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export async function gitRevParse(
|
|
15
|
+
fs: GitFilesystem,
|
|
16
|
+
invocation: GitInvocation,
|
|
17
|
+
args: readonly string[],
|
|
18
|
+
): Promise<number> {
|
|
19
|
+
const cwd = absolute("/", invocation.cwd);
|
|
20
|
+
const dir = await findRoot(fs, cwd);
|
|
21
|
+
if (dir === null)
|
|
22
|
+
return fatal(invocation, "not a git repository (or any of the parent directories): .git");
|
|
23
|
+
const context = { fs, dir, invocation };
|
|
24
|
+
const query = parseQuery(args);
|
|
25
|
+
const gitdir = absolute(dir, ".git");
|
|
26
|
+
const metadata = cwd === gitdir || cwd.startsWith(`${gitdir}/`);
|
|
27
|
+
const inside = !metadata && (await git.getConfig({ ...context, path: "core.bare" })) !== true;
|
|
28
|
+
for (const location of query.locations) {
|
|
29
|
+
if (location === "--show-toplevel" && !inside)
|
|
30
|
+
return fatal(invocation, "this operation must be run in a work tree");
|
|
31
|
+
await output(context, locationValue(location, dir, cwd, inside));
|
|
32
|
+
}
|
|
33
|
+
if (query.verify && query.refs.length !== 1) return fatal(invocation, "Needed a single revision");
|
|
34
|
+
const minimum = query.short === "default" ? await defaultShort(context) : query.short;
|
|
35
|
+
for (const ref of query.refs) {
|
|
36
|
+
const oid = await resolveRevision(context, ref);
|
|
37
|
+
if (oid === null) return missingRevision(context, query, ref);
|
|
38
|
+
const value = minimum === null ? oid : await shorten(context, oid, minimum);
|
|
39
|
+
await output(context, `${value}\n`);
|
|
40
|
+
}
|
|
41
|
+
return 0;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function findRoot(fs: GitFilesystem, cwd: string): Promise<string | null> {
|
|
45
|
+
try {
|
|
46
|
+
return await git.findRoot({ fs, filepath: cwd });
|
|
47
|
+
} catch (error) {
|
|
48
|
+
if (error instanceof git.Errors.NotFoundError) return null;
|
|
49
|
+
throw error;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function parseQuery(args: readonly string[]): RevisionQuery {
|
|
54
|
+
const locations: LocationQuery[] = [];
|
|
55
|
+
const refs: string[] = [];
|
|
56
|
+
let verify = false;
|
|
57
|
+
let short: number | "default" | null = null;
|
|
58
|
+
for (const arg of args) {
|
|
59
|
+
if (!arg.startsWith("-")) {
|
|
60
|
+
validateRevision(arg);
|
|
61
|
+
refs.push(arg);
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
if (refs.length) throw new GitFailure("rev-parse options must precede revisions", 129);
|
|
65
|
+
if (arg === "--show-toplevel" || arg === "--show-prefix" || arg === "--is-inside-work-tree") {
|
|
66
|
+
locations.push(arg);
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
if (arg === "--verify") {
|
|
70
|
+
verify = true;
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
if (arg === "--short" || arg.startsWith("--short=")) {
|
|
74
|
+
short = shortLength(arg);
|
|
75
|
+
verify = true;
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
throw new GitFailure(`unsupported rev-parse option '${arg}'`, 129);
|
|
79
|
+
}
|
|
80
|
+
return { locations, refs, verify, short };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function shortLength(arg: string): number | "default" {
|
|
84
|
+
if (arg === "--short") return "default";
|
|
85
|
+
const value = arg.slice("--short=".length);
|
|
86
|
+
if (!/^\d+$/.test(value)) throw new GitFailure("--short needs a nonnegative integer", 129);
|
|
87
|
+
return Math.max(4, Math.min(40, Number(value)));
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function defaultShort(context: GitContext): Promise<number> {
|
|
91
|
+
const value: unknown = await git.getConfig({ ...context, path: "core.abbrev" });
|
|
92
|
+
if (value === undefined) return 7;
|
|
93
|
+
if (value === "no") return 40;
|
|
94
|
+
if (typeof value === "string" && /^\d+$/.test(value) && Number(value) >= 4 && Number(value) <= 40)
|
|
95
|
+
return Number(value);
|
|
96
|
+
throw new GitFailure("rev-parse supports only numeric core.abbrev (4..40) or no", 129);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function validateRevision(ref: string) {
|
|
100
|
+
if (
|
|
101
|
+
!ref ||
|
|
102
|
+
ref === "@" ||
|
|
103
|
+
/[~^:?*[\\]/.test(ref) ||
|
|
104
|
+
Array.from(ref).some(
|
|
105
|
+
(character) => character.charCodeAt(0) <= 32 || character.charCodeAt(0) === 127,
|
|
106
|
+
) ||
|
|
107
|
+
ref.includes("..") ||
|
|
108
|
+
ref.includes("@{") ||
|
|
109
|
+
ref.split("/").some((part) => !part || part.startsWith(".") || part.endsWith(".lock")) ||
|
|
110
|
+
ref.endsWith(".")
|
|
111
|
+
)
|
|
112
|
+
throw new GitFailure(`unsupported revision syntax '${ref}'`, 129);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function locationValue(location: LocationQuery, dir: string, cwd: string, inside: boolean) {
|
|
116
|
+
if (location === "--show-toplevel") return `${dir}\n`;
|
|
117
|
+
if (location === "--is-inside-work-tree") return `${inside}\n`;
|
|
118
|
+
if (!inside || cwd === dir) return "\n";
|
|
119
|
+
return `${cwd.slice(dir === "/" ? 1 : dir.length + 1)}/\n`;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async function resolveRevision(context: GitContext, ref: string): Promise<string | null> {
|
|
123
|
+
if (/^[0-9a-fA-F]{40}$/.test(ref)) return ref.toLowerCase();
|
|
124
|
+
const names = new Set(
|
|
125
|
+
(await git.listRefs({ ...context, filepath: "refs" })).map((name) => `refs/${name}`),
|
|
126
|
+
);
|
|
127
|
+
names.add("HEAD");
|
|
128
|
+
const matches = [
|
|
129
|
+
ref,
|
|
130
|
+
`refs/${ref}`,
|
|
131
|
+
`refs/tags/${ref}`,
|
|
132
|
+
`refs/heads/${ref}`,
|
|
133
|
+
`refs/remotes/${ref}`,
|
|
134
|
+
`refs/remotes/${ref}/HEAD`,
|
|
135
|
+
].filter((name) => names.has(name));
|
|
136
|
+
if (matches.length > 1)
|
|
137
|
+
throw new GitFailure(`ambiguous ref '${ref}'; use its full ref name`, 129);
|
|
138
|
+
try {
|
|
139
|
+
if (matches.length) return await git.resolveRef({ ...context, ref: matches[0] });
|
|
140
|
+
if (/^[0-9a-fA-F]{4,39}$/.test(ref))
|
|
141
|
+
return await git.expandOid({ ...context, oid: ref.toLowerCase() });
|
|
142
|
+
return null;
|
|
143
|
+
} catch (error) {
|
|
144
|
+
if (error instanceof git.Errors.NotFoundError) return null;
|
|
145
|
+
if (error instanceof git.Errors.AmbiguousError)
|
|
146
|
+
throw new GitFailure(`ambiguous object prefix '${ref}'; use a longer object ID`, 128);
|
|
147
|
+
throw error;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async function shorten(context: GitContext, oid: string, minimum: number): Promise<string> {
|
|
152
|
+
for (let length = minimum; length < 40; length++) {
|
|
153
|
+
const prefix = oid.slice(0, length);
|
|
154
|
+
if (await isUniquePrefix(context, oid, prefix)) return prefix;
|
|
155
|
+
}
|
|
156
|
+
return oid;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async function isUniquePrefix(context: GitContext, oid: string, prefix: string): Promise<boolean> {
|
|
160
|
+
try {
|
|
161
|
+
return (await git.expandOid({ ...context, oid: prefix })) === oid;
|
|
162
|
+
} catch (error) {
|
|
163
|
+
if (error instanceof git.Errors.NotFoundError) return true;
|
|
164
|
+
if (error instanceof git.Errors.AmbiguousError) return false;
|
|
165
|
+
throw error;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
async function missingRevision(context: GitContext, query: RevisionQuery, ref: string) {
|
|
170
|
+
if (query.verify) return fatal(context.invocation, "Needed a single revision");
|
|
171
|
+
if (await exists(context.fs, absolute(context.invocation.cwd, ref)))
|
|
172
|
+
throw new GitFailure("rev-parse path operands are unsupported", 129);
|
|
173
|
+
await output(context, `${ref}\n`);
|
|
174
|
+
return fatal(
|
|
175
|
+
context.invocation,
|
|
176
|
+
`ambiguous argument '${ref}': unknown revision or path not in the working tree.\n` +
|
|
177
|
+
"Use '--' to separate paths from revisions, like this:\n" +
|
|
178
|
+
"'git <command> [<revision>...] -- [<file>...]'",
|
|
179
|
+
);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
async function fatal(invocation: GitInvocation, message: string) {
|
|
183
|
+
await invocation.stderr(new TextEncoder().encode(`fatal: ${message}\n`));
|
|
184
|
+
return 128;
|
|
185
|
+
}
|