@catamorphic/git 0.1.0-alpha.39 → 0.1.0-alpha.42
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/NOTICE.txt +7 -0
- package/dist/git-sync.d.ts +2 -0
- package/dist/git-sync.d.ts.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1218 -88
- package/dist/index.js.map +13 -11
- package/dist/network.d.ts +43 -4
- package/dist/network.d.ts.map +1 -1
- package/dist/origin-draft.d.ts +10 -2
- package/dist/origin-draft.d.ts.map +1 -1
- package/dist/origin-objects.d.ts +5 -0
- package/dist/origin-objects.d.ts.map +1 -1
- package/dist/project-manager.d.ts +96 -8
- package/dist/project-manager.d.ts.map +1 -1
- package/dist/project-repo.d.ts.map +1 -1
- package/dist/session-checkpoint.d.ts +75 -0
- package/dist/session-checkpoint.d.ts.map +1 -0
- package/dist/workspace-mirror.d.ts +4 -1
- package/dist/workspace-mirror.d.ts.map +1 -1
- package/dist/workspace-save.d.ts +170 -0
- package/dist/workspace-save.d.ts.map +1 -0
- package/package.json +2 -2
- package/src/git-sync.ts +7 -0
- package/src/index.ts +20 -0
- package/src/network.ts +210 -7
- package/src/origin-draft.ts +42 -13
- package/src/origin-objects.ts +38 -12
- package/src/project-manager.ts +400 -46
- package/src/project-repo.ts +18 -3
- package/src/session-checkpoint.ts +210 -0
- package/src/workspace-mirror.ts +31 -30
- package/src/workspace-save.ts +999 -0
package/dist/index.js
CHANGED
|
@@ -372,12 +372,16 @@ class ProjectRepoImpl {
|
|
|
372
372
|
return readFileSnapshot({
|
|
373
373
|
paths,
|
|
374
374
|
options,
|
|
375
|
-
read: async (file, maxBytes) =>
|
|
375
|
+
read: async (file, maxBytes) => {
|
|
376
|
+
if (!this.followsSymlinks && (await fs3.lstat(path3.join(this.repoPath, file))).isSymbolicLink())
|
|
377
|
+
return null;
|
|
378
|
+
return new TextDecoder().decode(await this.readSnapshotBytes(file, maxBytes));
|
|
379
|
+
}
|
|
376
380
|
});
|
|
377
381
|
}
|
|
378
382
|
async readSnapshotBytes(file, maxBytes) {
|
|
379
383
|
assertSafePath(file);
|
|
380
|
-
const handle = await fs3.open(path3.join(this.repoPath, file),
|
|
384
|
+
const handle = await fs3.open(path3.join(this.repoPath, file), this.followsSymlinks ? nodeFs.constants.O_RDONLY : nodeFs.constants.O_RDONLY | (nodeFs.constants.O_NOFOLLOW ?? 0));
|
|
381
385
|
try {
|
|
382
386
|
const size = (await handle.stat()).size;
|
|
383
387
|
if (size > maxBytes)
|
|
@@ -1632,7 +1636,7 @@ class OriginObjects {
|
|
|
1632
1636
|
return true;
|
|
1633
1637
|
if (!treeOid)
|
|
1634
1638
|
return false;
|
|
1635
|
-
if (await this.entry(treeOid, filePath))
|
|
1639
|
+
if (await this.entry(treeOid, filePath).catch(() => null))
|
|
1636
1640
|
return false;
|
|
1637
1641
|
let ignored = false;
|
|
1638
1642
|
for (let depth = 0;depth < segments.length; depth++) {
|
|
@@ -1655,29 +1659,40 @@ class OriginObjects {
|
|
|
1655
1659
|
return ignored;
|
|
1656
1660
|
}
|
|
1657
1661
|
async writeTree(treeOid, changes, options) {
|
|
1658
|
-
return await this.rewrite(treeOid, changes, "", options
|
|
1662
|
+
return await this.rewrite(treeOid, changes, "", options ?? {}) ?? this.write({ type: "tree", data: new Uint8Array });
|
|
1659
1663
|
}
|
|
1660
|
-
async rewrite(treeOid, changes, base,
|
|
1664
|
+
async rewrite(treeOid, changes, base, options) {
|
|
1665
|
+
const skipMissingDeletes = options.skipMissingDeletes ?? false;
|
|
1661
1666
|
const entries = new Map((treeOid ? await this.tree(treeOid) : []).map((entry) => [
|
|
1662
1667
|
nameKey(entry.nameBytes),
|
|
1663
1668
|
entry
|
|
1664
1669
|
]));
|
|
1665
1670
|
const keyed = (name) => nameKey(new TextEncoder().encode(name));
|
|
1671
|
+
const leaves = new Map;
|
|
1666
1672
|
const nested = new Map;
|
|
1667
1673
|
for (const [filePath, change] of changes) {
|
|
1668
1674
|
const slash = filePath.indexOf("/");
|
|
1669
|
-
if (slash
|
|
1670
|
-
|
|
1671
|
-
const inner = nested.get(directory) ?? new Map;
|
|
1672
|
-
inner.set(filePath.slice(slash + 1), change);
|
|
1673
|
-
nested.set(directory, inner);
|
|
1675
|
+
if (slash < 0) {
|
|
1676
|
+
leaves.set(filePath, change);
|
|
1674
1677
|
continue;
|
|
1675
1678
|
}
|
|
1676
|
-
const
|
|
1679
|
+
const directory = filePath.slice(0, slash);
|
|
1680
|
+
const inner = nested.get(directory) ?? new Map;
|
|
1681
|
+
inner.set(filePath.slice(slash + 1), change);
|
|
1682
|
+
nested.set(directory, inner);
|
|
1683
|
+
}
|
|
1684
|
+
for (const [filePath, change] of leaves) {
|
|
1677
1685
|
const fullPath = `${base}${filePath}`;
|
|
1686
|
+
const inside = nested.get(filePath);
|
|
1687
|
+
const found = entries.get(keyed(filePath));
|
|
1688
|
+
if (found && isTreeMode(found.mode) && change !== null && inside && [...inside.values()].every((entry) => entry === null) && await this.rewrite(found.oid, inside, `${fullPath}/`, options) === null) {
|
|
1689
|
+
entries.delete(keyed(filePath));
|
|
1690
|
+
nested.delete(filePath);
|
|
1691
|
+
}
|
|
1692
|
+
const existing = entries.get(keyed(filePath));
|
|
1678
1693
|
if (existing && isTreeMode(existing.mode))
|
|
1679
1694
|
throw new DraftPathError({ code: "EISDIR", path: fullPath });
|
|
1680
|
-
if (existing?.mode === SYMLINK_MODE)
|
|
1695
|
+
if (existing?.mode === SYMLINK_MODE && !options.replaceLinks)
|
|
1681
1696
|
throw new DraftPathError({ code: "ELOOP", path: fullPath });
|
|
1682
1697
|
if (change === null) {
|
|
1683
1698
|
if (!existing) {
|
|
@@ -1704,7 +1719,7 @@ class OriginObjects {
|
|
|
1704
1719
|
path: `${fullPath}/${[...inner.keys()][0] ?? ""}`
|
|
1705
1720
|
});
|
|
1706
1721
|
}
|
|
1707
|
-
const oid = await this.rewrite(existing?.oid ?? null, inner, `${fullPath}/`,
|
|
1722
|
+
const oid = await this.rewrite(existing?.oid ?? null, inner, `${fullPath}/`, options);
|
|
1708
1723
|
return { directory, oid, keep: false };
|
|
1709
1724
|
}));
|
|
1710
1725
|
for (const child of children) {
|
|
@@ -2055,6 +2070,8 @@ async function push(opts) {
|
|
|
2055
2070
|
if (currentRemote === localSha) {
|
|
2056
2071
|
return { sha: localSha };
|
|
2057
2072
|
}
|
|
2073
|
+
if (opts.expected !== undefined && currentRemote !== opts.expected)
|
|
2074
|
+
throw new Error("The workspace checkpoint changed before it could be published.");
|
|
2058
2075
|
if (currentRemote && !opts.force) {
|
|
2059
2076
|
const fastForward = await isAncestor({
|
|
2060
2077
|
dev: opts.dev,
|
|
@@ -2909,6 +2926,7 @@ init_native_project_repo();
|
|
|
2909
2926
|
|
|
2910
2927
|
// src/network.ts
|
|
2911
2928
|
init_native_git();
|
|
2929
|
+
init_ref_names();
|
|
2912
2930
|
import nodeFs5 from "node:fs";
|
|
2913
2931
|
import { MANAGED_BRANCH_PREFIX } from "@catamorphic/workflow/project-layout";
|
|
2914
2932
|
import git5 from "isomorphic-git";
|
|
@@ -2999,7 +3017,7 @@ function assertPushAllowed(input) {
|
|
|
2999
3017
|
if (!isManagedBranch(input.remoteBranch)) {
|
|
3000
3018
|
throw new RemotePushRefusedError(input.remoteBranch, `this repository is attached, so Work only pushes branches it creates under '${MANAGED_BRANCH_PREFIX}'. Open a pull request instead.`);
|
|
3001
3019
|
}
|
|
3002
|
-
if (input.force) {
|
|
3020
|
+
if (input.force && !input.lease) {
|
|
3003
3021
|
throw new RemotePushRefusedError(input.remoteBranch, "Work never rewrites history in an attached repository.");
|
|
3004
3022
|
}
|
|
3005
3023
|
}
|
|
@@ -3010,7 +3028,26 @@ async function pushToRemote(opts) {
|
|
|
3010
3028
|
throw new RemotePushRefusedError(name, "not a plain branch or ref name.");
|
|
3011
3029
|
}
|
|
3012
3030
|
}
|
|
3013
|
-
assertPushAllowed(
|
|
3031
|
+
assertPushAllowed({
|
|
3032
|
+
ownership: opts.ownership,
|
|
3033
|
+
remoteBranch,
|
|
3034
|
+
force: opts.force ?? opts.lease !== undefined,
|
|
3035
|
+
lease: opts.lease !== undefined
|
|
3036
|
+
});
|
|
3037
|
+
if (opts.lease) {
|
|
3038
|
+
const expected = opts.lease.expected ?? "";
|
|
3039
|
+
if (!opts.native || expected && !/^[0-9a-f]{40,64}$/.test(expected))
|
|
3040
|
+
throw new RemotePushRefusedError(remoteBranch, "a push with a lease names the commit it replaces.");
|
|
3041
|
+
await pushWithLease({
|
|
3042
|
+
repoPath: opts.repoPath,
|
|
3043
|
+
url: opts.url,
|
|
3044
|
+
ref,
|
|
3045
|
+
target: `refs/heads/${remoteBranch}`,
|
|
3046
|
+
expected,
|
|
3047
|
+
auth: opts.credentials ? { ...opts.credentials, url: opts.url } : undefined
|
|
3048
|
+
});
|
|
3049
|
+
return;
|
|
3050
|
+
}
|
|
3014
3051
|
if (opts.native) {
|
|
3015
3052
|
await nativeGit(opts.repoPath, [
|
|
3016
3053
|
"push",
|
|
@@ -3031,6 +3068,90 @@ async function pushToRemote(opts) {
|
|
|
3031
3068
|
onAuth: onAuthFor(opts.credentials)
|
|
3032
3069
|
});
|
|
3033
3070
|
}
|
|
3071
|
+
function pushWithLease(input) {
|
|
3072
|
+
return nativeGit(input.repoPath, [
|
|
3073
|
+
"push",
|
|
3074
|
+
"--porcelain",
|
|
3075
|
+
"--no-follow-tags",
|
|
3076
|
+
`--force-with-lease=${input.target}:${input.expected}`,
|
|
3077
|
+
input.url,
|
|
3078
|
+
`${input.ref}:${input.target}`
|
|
3079
|
+
], input.auth);
|
|
3080
|
+
}
|
|
3081
|
+
async function pushOwnBranch(opts) {
|
|
3082
|
+
const { remoteBranch, commit } = opts;
|
|
3083
|
+
if (!isManagedBranch(remoteBranch) || !isValidRefName(remoteBranch))
|
|
3084
|
+
throw new RemotePushRefusedError(remoteBranch, `a chat pushes only its own branch under '${MANAGED_BRANCH_PREFIX}'.`);
|
|
3085
|
+
if (!/^[0-9a-f]{40}$|^[0-9a-f]{64}$/.test(commit))
|
|
3086
|
+
throw new RemotePushRefusedError(remoteBranch, "not a commit to push.");
|
|
3087
|
+
assertPushAllowed({
|
|
3088
|
+
ownership: opts.ownership,
|
|
3089
|
+
remoteBranch,
|
|
3090
|
+
force: true,
|
|
3091
|
+
lease: true
|
|
3092
|
+
});
|
|
3093
|
+
const auth = opts.credentials ? { ...opts.credentials, url: opts.url } : undefined;
|
|
3094
|
+
const target = `refs/heads/${remoteBranch}`;
|
|
3095
|
+
const listed = await nativeGit(opts.repoPath, ["ls-remote", "--symref", opts.url, "HEAD", target], auth);
|
|
3096
|
+
const refs = new Map;
|
|
3097
|
+
for (const line of listed.split(`
|
|
3098
|
+
`)) {
|
|
3099
|
+
const [value, name] = line.split("\t");
|
|
3100
|
+
if (name && value && /^[0-9a-f]{40}$|^[0-9a-f]{64}$/.test(value))
|
|
3101
|
+
refs.set(name, value);
|
|
3102
|
+
}
|
|
3103
|
+
const defaultRef = listed.match(/^ref: (refs\/heads\/[^\t\n]+)\tHEAD$/m)?.[1];
|
|
3104
|
+
if (!defaultRef || !refs.get("HEAD"))
|
|
3105
|
+
throw new RemotePushRefusedError(remoteBranch, "the remote names no default branch, so Work cannot check this push.");
|
|
3106
|
+
if (target === defaultRef)
|
|
3107
|
+
throw new RemotePushRefusedError(remoteBranch, "Work cannot push a chat to the repository's default branch.");
|
|
3108
|
+
const remote = refs.get(target);
|
|
3109
|
+
const push = async (expected) => {
|
|
3110
|
+
const output = await pushWithLease({
|
|
3111
|
+
repoPath: opts.repoPath,
|
|
3112
|
+
url: opts.url,
|
|
3113
|
+
ref: commit,
|
|
3114
|
+
target,
|
|
3115
|
+
expected,
|
|
3116
|
+
auth
|
|
3117
|
+
}).catch((error) => {
|
|
3118
|
+
throw isStaleLease(error) ? new RemotePushRefusedError(remoteBranch, "the branch changed in the repository while it was being pushed. Try again.") : error;
|
|
3119
|
+
});
|
|
3120
|
+
const status = output.split(`
|
|
3121
|
+
`).find((line) => line.split("\t")[1]?.endsWith(`:${target}`))?.[0];
|
|
3122
|
+
if (status === "=")
|
|
3123
|
+
return false;
|
|
3124
|
+
if (status === "*" || status === "+" || status === " ")
|
|
3125
|
+
return true;
|
|
3126
|
+
throw new Error("Git did not confirm what happened to the pushed branch.");
|
|
3127
|
+
};
|
|
3128
|
+
const unchanged = {
|
|
3129
|
+
outcome: "unchanged",
|
|
3130
|
+
recordOwnership: false
|
|
3131
|
+
};
|
|
3132
|
+
if (!remote)
|
|
3133
|
+
return await push("") ? { outcome: "created", recordOwnership: true } : unchanged;
|
|
3134
|
+
if (remote === commit)
|
|
3135
|
+
return unchanged;
|
|
3136
|
+
const ownsTip = opts.pushed?.branch === remoteBranch && opts.pushed.commit === remote;
|
|
3137
|
+
const forward = await nativeGit(opts.repoPath, [
|
|
3138
|
+
"merge-base",
|
|
3139
|
+
"--is-ancestor",
|
|
3140
|
+
remote,
|
|
3141
|
+
commit
|
|
3142
|
+
]).then(() => true, () => false);
|
|
3143
|
+
if (forward)
|
|
3144
|
+
return await push(remote) ? { outcome: "updated", recordOwnership: ownsTip } : unchanged;
|
|
3145
|
+
if (opts.pushed?.branch !== remoteBranch)
|
|
3146
|
+
throw new RemotePushRefusedError(remoteBranch, "a branch of that name is already in the repository with other commits, and this chat did not create it. Switch to another branch name and try again.");
|
|
3147
|
+
if (!ownsTip)
|
|
3148
|
+
throw new RemotePushRefusedError(remoteBranch, "someone else pushed to this branch since this chat last did, so it was not overwritten. Fetch the branch, rebase or merge onto it, and try again.");
|
|
3149
|
+
return await push(remote) ? { outcome: "replaced", recordOwnership: true } : unchanged;
|
|
3150
|
+
}
|
|
3151
|
+
function isStaleLease(error) {
|
|
3152
|
+
const text = error && typeof error === "object" && "stderr" in error ? String(error.stderr) : error instanceof Error ? error.message : "";
|
|
3153
|
+
return /stale info|\[rejected\]|already exists/i.test(text);
|
|
3154
|
+
}
|
|
3034
3155
|
async function fetchFromRemote(opts) {
|
|
3035
3156
|
const remote = "catamorphic-network";
|
|
3036
3157
|
await git5.addRemote({
|
|
@@ -3709,14 +3830,20 @@ class OriginDraftRepo {
|
|
|
3709
3830
|
async write(input) {
|
|
3710
3831
|
const pending = new Map;
|
|
3711
3832
|
for (const change of input.changes)
|
|
3712
|
-
pending.set(normalizePath(change.path), "delete" in change ? null :
|
|
3833
|
+
pending.set(normalizePath(change.path), "delete" in change ? null : {
|
|
3834
|
+
content: typeof change.content === "string" ? new TextEncoder().encode(change.content) : change.content,
|
|
3835
|
+
...change.mode ? { mode: change.mode } : {}
|
|
3836
|
+
});
|
|
3713
3837
|
const draftRefName = this.draftRefOrThrow();
|
|
3714
3838
|
if (pending.size === 0)
|
|
3715
3839
|
return null;
|
|
3716
3840
|
const message = input.message ?? `Draft: ${[...pending.keys()].slice(0, 3).join(", ")}${pending.size > 3 ? ", ..." : ""}`;
|
|
3717
|
-
const written = [...pending].
|
|
3718
|
-
const oids = await this.withObjects((objects) => objects.writeBlobs(written.map((
|
|
3719
|
-
const blobs = new Map(written.map((
|
|
3841
|
+
const written = [...pending].flatMap(([file, change]) => change ? [{ file, ...change }] : []);
|
|
3842
|
+
const oids = await this.withObjects((objects) => objects.writeBlobs(written.map((change) => change.content)));
|
|
3843
|
+
const blobs = new Map(written.map((change, index) => [
|
|
3844
|
+
change.file,
|
|
3845
|
+
{ oid: oids[index], mode: change.mode }
|
|
3846
|
+
]));
|
|
3720
3847
|
for (let attempt = 0;attempt < MAX_ATTEMPTS; attempt++) {
|
|
3721
3848
|
const outcome = await this.attempt(async (objects) => {
|
|
3722
3849
|
const { draft, main } = await this.tips(objects);
|
|
@@ -3736,15 +3863,16 @@ class OriginDraftRepo {
|
|
|
3736
3863
|
ignored.push(file);
|
|
3737
3864
|
continue;
|
|
3738
3865
|
}
|
|
3739
|
-
const
|
|
3740
|
-
changes.set(file, oid ? { oid } : null);
|
|
3866
|
+
const blob = blobs.get(file);
|
|
3867
|
+
changes.set(file, blob?.oid ? { oid: blob.oid, ...blob.mode ? { mode: blob.mode } : {} } : null);
|
|
3741
3868
|
}
|
|
3742
3869
|
if (ignored.length > 0 && !input.skipIgnored)
|
|
3743
3870
|
throw new DraftIgnoredPathError(ignored);
|
|
3744
3871
|
if (changes.size === 0)
|
|
3745
3872
|
return { sha: parent };
|
|
3746
3873
|
const tree = await objects.writeTree(baseTree, changes, {
|
|
3747
|
-
skipMissingDeletes: input.skipMissingDeletes
|
|
3874
|
+
skipMissingDeletes: input.skipMissingDeletes,
|
|
3875
|
+
replaceLinks: input.replaceLinks
|
|
3748
3876
|
});
|
|
3749
3877
|
if (tree === baseTree)
|
|
3750
3878
|
return { sha: parent };
|
|
@@ -4133,16 +4261,130 @@ init_native_project_repo();
|
|
|
4133
4261
|
init_origin_objects();
|
|
4134
4262
|
init_project_repo();
|
|
4135
4263
|
|
|
4264
|
+
// src/session-checkpoint.ts
|
|
4265
|
+
init_native_git();
|
|
4266
|
+
init_ref_names();
|
|
4267
|
+
import { MANAGED_BRANCH_PREFIX as MANAGED_BRANCH_PREFIX3 } from "@catamorphic/workflow/project-layout";
|
|
4268
|
+
var COMMIT = /^[0-9a-f]{40}$|^[0-9a-f]{64}$/;
|
|
4269
|
+
var BRANCH_TRAILER = "Work-Branch";
|
|
4270
|
+
var HEAD_TRAILER = "Work-Head";
|
|
4271
|
+
var PUSHED_TRAILER = "Work-Pushed";
|
|
4272
|
+
function assertSessionWork(work) {
|
|
4273
|
+
if (!COMMIT.test(work.head))
|
|
4274
|
+
throw new Error("A checkpoint names its agent's HEAD by a full commit id");
|
|
4275
|
+
if (!isSessionBranchName(work.branch))
|
|
4276
|
+
throw new Error(`A checkpoint cannot record the branch ${JSON.stringify(work.branch.slice(0, 200))}`);
|
|
4277
|
+
if (work.pushed && (!COMMIT.test(work.pushed.commit) || !isSessionBranchName(work.pushed.branch)))
|
|
4278
|
+
throw new Error("A checkpoint cannot record that pushed branch");
|
|
4279
|
+
}
|
|
4280
|
+
function isSessionBranchName(name) {
|
|
4281
|
+
return name.length <= 255 && isValidRefName(name) && !name.startsWith("-") && !name.includes("+") && name !== "HEAD";
|
|
4282
|
+
}
|
|
4283
|
+
function sessionBranchName(sessionId) {
|
|
4284
|
+
return `${MANAGED_BRANCH_PREFIX3}${sessionId.replaceAll("-", "").slice(0, 8)}`;
|
|
4285
|
+
}
|
|
4286
|
+
function checkpointMessage(input) {
|
|
4287
|
+
assertSessionWork(input.work);
|
|
4288
|
+
const subject = input.message.split(`
|
|
4289
|
+
`).map((line) => line.trim()).find(Boolean) ?? "Checkpoint";
|
|
4290
|
+
return [
|
|
4291
|
+
subject,
|
|
4292
|
+
"",
|
|
4293
|
+
`${BRANCH_TRAILER}: ${input.work.branch}`,
|
|
4294
|
+
`${HEAD_TRAILER}: ${input.work.head}`,
|
|
4295
|
+
...input.work.pushed ? [
|
|
4296
|
+
`${PUSHED_TRAILER}: ${input.work.pushed.branch} ${input.work.pushed.commit}`
|
|
4297
|
+
] : [],
|
|
4298
|
+
""
|
|
4299
|
+
].join(`
|
|
4300
|
+
`);
|
|
4301
|
+
}
|
|
4302
|
+
function parseCheckpointMessage(message) {
|
|
4303
|
+
const paragraphs = message.trimEnd().split(/\n{2,}/);
|
|
4304
|
+
const last = paragraphs.length > 1 ? paragraphs.at(-1) : undefined;
|
|
4305
|
+
if (!last)
|
|
4306
|
+
return null;
|
|
4307
|
+
const trailers = new Map;
|
|
4308
|
+
for (const line of last.split(`
|
|
4309
|
+
`)) {
|
|
4310
|
+
const separator = line.indexOf(": ");
|
|
4311
|
+
if (separator > 0)
|
|
4312
|
+
trailers.set(line.slice(0, separator), line.slice(separator + 2).trim());
|
|
4313
|
+
}
|
|
4314
|
+
const head = trailers.get(HEAD_TRAILER);
|
|
4315
|
+
const branch = trailers.get(BRANCH_TRAILER);
|
|
4316
|
+
if (!head || !branch || !COMMIT.test(head) || !isSessionBranchName(branch))
|
|
4317
|
+
return null;
|
|
4318
|
+
const [pushedBranch = "", pushedCommit = ""] = (trailers.get(PUSHED_TRAILER) ?? "").split(" ");
|
|
4319
|
+
return {
|
|
4320
|
+
head,
|
|
4321
|
+
branch,
|
|
4322
|
+
...isSessionBranchName(pushedBranch) && COMMIT.test(pushedCommit) ? { pushed: { branch: pushedBranch, commit: pushedCommit } } : {}
|
|
4323
|
+
};
|
|
4324
|
+
}
|
|
4325
|
+
async function readSessionWork(input) {
|
|
4326
|
+
if (!COMMIT.test(input.commit))
|
|
4327
|
+
return null;
|
|
4328
|
+
const message = await nativeGit(input.repoPath, [
|
|
4329
|
+
"log",
|
|
4330
|
+
"-1",
|
|
4331
|
+
"--format=%B",
|
|
4332
|
+
input.commit
|
|
4333
|
+
]).catch(() => "");
|
|
4334
|
+
return parseCheckpointMessage(message);
|
|
4335
|
+
}
|
|
4336
|
+
async function writeCheckpoint(input) {
|
|
4337
|
+
assertSessionWork(input.work);
|
|
4338
|
+
const tree = (await nativeGit(input.repoPath, [
|
|
4339
|
+
"rev-parse",
|
|
4340
|
+
"--verify",
|
|
4341
|
+
`${input.tree}^{tree}`
|
|
4342
|
+
])).trim();
|
|
4343
|
+
await nativeGit(input.repoPath, [
|
|
4344
|
+
"cat-file",
|
|
4345
|
+
"-e",
|
|
4346
|
+
`${input.work.head}^{commit}`
|
|
4347
|
+
]);
|
|
4348
|
+
return (await nativeGit(input.repoPath, [
|
|
4349
|
+
"-c",
|
|
4350
|
+
`user.name=${input.author.name}`,
|
|
4351
|
+
"-c",
|
|
4352
|
+
`user.email=${input.author.email}`,
|
|
4353
|
+
"commit-tree",
|
|
4354
|
+
tree,
|
|
4355
|
+
"-p",
|
|
4356
|
+
input.previous,
|
|
4357
|
+
...input.work.head === input.previous ? [] : ["-p", input.work.head],
|
|
4358
|
+
"-m",
|
|
4359
|
+
checkpointMessage({ message: input.message, work: input.work })
|
|
4360
|
+
])).trim();
|
|
4361
|
+
}
|
|
4362
|
+
async function currentSessionWork(input) {
|
|
4363
|
+
const checkpoint = (await nativeGit(input.repoPath, [
|
|
4364
|
+
"rev-parse",
|
|
4365
|
+
"--verify",
|
|
4366
|
+
"refs/heads/main^{commit}"
|
|
4367
|
+
])).trim();
|
|
4368
|
+
const recorded = checkpoint === input.base ? null : await readSessionWork({ repoPath: input.repoPath, commit: checkpoint });
|
|
4369
|
+
return {
|
|
4370
|
+
checkpoint,
|
|
4371
|
+
...recorded ?? {
|
|
4372
|
+
head: input.base,
|
|
4373
|
+
branch: sessionBranchName(input.sessionId)
|
|
4374
|
+
}
|
|
4375
|
+
};
|
|
4376
|
+
}
|
|
4377
|
+
|
|
4136
4378
|
// src/workspace-mirror.ts
|
|
4137
4379
|
init_native_git();
|
|
4138
4380
|
import { execFile as execFile2 } from "node:child_process";
|
|
4139
4381
|
import fs7 from "node:fs/promises";
|
|
4140
4382
|
import { tmpdir } from "node:os";
|
|
4141
4383
|
import path8 from "node:path";
|
|
4142
|
-
var
|
|
4384
|
+
var COMMIT2 = /^[0-9a-f]{40}$|^[0-9a-f]{64}$/;
|
|
4143
4385
|
function parseWorkspaceRef(value) {
|
|
4144
4386
|
const ref = value.trim();
|
|
4145
|
-
if (
|
|
4387
|
+
if (COMMIT2.test(ref))
|
|
4146
4388
|
return ref;
|
|
4147
4389
|
if (ref.length === 0 || ref.length > 255 || ref.startsWith("-") || ref.startsWith("/") || ref.endsWith("/") || ref.endsWith(".") || ref.endsWith(".lock") || ref.includes("..") || ref.includes("//") || ref.includes("@{") || /[\s:~^?*[\\\u0000-\u001f\u007f+]/.test(ref)) {
|
|
4148
4390
|
throw new Error(`'${value}' is not a branch, tag, commit, or full ref such as refs/pull/42/head`);
|
|
@@ -4150,7 +4392,7 @@ function parseWorkspaceRef(value) {
|
|
|
4150
4392
|
return ref;
|
|
4151
4393
|
}
|
|
4152
4394
|
function isCommitId(ref) {
|
|
4153
|
-
return
|
|
4395
|
+
return COMMIT2.test(ref);
|
|
4154
4396
|
}
|
|
4155
4397
|
var mirrorLocks = new Map;
|
|
4156
4398
|
async function withMirrorLock(mirrorPath, work) {
|
|
@@ -4282,44 +4524,39 @@ async function moveCheckoutBase(opts) {
|
|
|
4282
4524
|
}
|
|
4283
4525
|
}
|
|
4284
4526
|
async function buildSeedPack(opts) {
|
|
4285
|
-
const
|
|
4286
|
-
|
|
4287
|
-
|
|
4288
|
-
|
|
4289
|
-
|
|
4527
|
+
for (const id of [opts.head, opts.base, ...opts.tree ? [opts.tree] : []])
|
|
4528
|
+
if (!COMMIT2.test(id))
|
|
4529
|
+
throw new Error("A seed pack names full object ids");
|
|
4530
|
+
const objects = path8.resolve(opts.repoPath, (await nativeGit(opts.repoPath, ["rev-parse", "--git-path", "objects"])).trim());
|
|
4531
|
+
if (/[\n"]/.test(objects))
|
|
4532
|
+
throw new Error("The repository's path cannot be packed from");
|
|
4290
4533
|
const directory = await fs7.mkdtemp(path8.join(tmpdir(), "work-seed-"));
|
|
4291
4534
|
try {
|
|
4292
|
-
await nativeGit(directory, [
|
|
4293
|
-
|
|
4294
|
-
|
|
4295
|
-
|
|
4296
|
-
|
|
4297
|
-
|
|
4298
|
-
|
|
4299
|
-
|
|
4300
|
-
|
|
4301
|
-
|
|
4302
|
-
`+${pin}:refs/heads/main`
|
|
4303
|
-
]);
|
|
4304
|
-
} finally {
|
|
4305
|
-
await nativeGit(opts.repoPath, ["update-ref", "-d", pin]).catch(() => "");
|
|
4306
|
-
}
|
|
4307
|
-
const shallow = await fs7.readFile(path8.join(directory, "shallow"), "utf8").then((text) => text.split(`
|
|
4308
|
-
`).filter(Boolean)).catch(() => []);
|
|
4535
|
+
await nativeGit(directory, [
|
|
4536
|
+
"init",
|
|
4537
|
+
"--bare",
|
|
4538
|
+
"--quiet",
|
|
4539
|
+
...opts.base.length === 64 ? ["--object-format=sha256"] : []
|
|
4540
|
+
]);
|
|
4541
|
+
await fs7.writeFile(path8.join(directory, "objects", "info", "alternates"), `${objects}
|
|
4542
|
+
`);
|
|
4543
|
+
await fs7.writeFile(path8.join(directory, "shallow"), `${opts.base}
|
|
4544
|
+
`);
|
|
4309
4545
|
const pack = await gitOutput({
|
|
4310
4546
|
cwd: directory,
|
|
4311
4547
|
args: ["pack-objects", "--revs", "--stdout", "--quiet"],
|
|
4312
|
-
input: `${opts.head
|
|
4548
|
+
input: `${[opts.head, opts.base, ...opts.tree ? [opts.tree] : []].join(`
|
|
4549
|
+
`)}
|
|
4313
4550
|
`
|
|
4314
4551
|
});
|
|
4315
|
-
return { pack, shallow };
|
|
4552
|
+
return { pack, shallow: [opts.base] };
|
|
4316
4553
|
} finally {
|
|
4317
4554
|
await fs7.rm(directory, { recursive: true, force: true });
|
|
4318
4555
|
}
|
|
4319
4556
|
}
|
|
4320
4557
|
function seedPackInstallScript(opts) {
|
|
4321
4558
|
for (const commit of opts.shallow) {
|
|
4322
|
-
if (!
|
|
4559
|
+
if (!COMMIT2.test(commit))
|
|
4323
4560
|
throw new Error("Invalid shallow commit");
|
|
4324
4561
|
}
|
|
4325
4562
|
const gitDir = `"$(git rev-parse --git-dir)"`;
|
|
@@ -4377,6 +4614,19 @@ var SYSTEM_AUTHOR2 = {
|
|
|
4377
4614
|
name: "Work",
|
|
4378
4615
|
email: "system@work.software"
|
|
4379
4616
|
};
|
|
4617
|
+
async function resetSessionCheckout(repoPath, commit) {
|
|
4618
|
+
await nativeGit(repoPath, [
|
|
4619
|
+
"-c",
|
|
4620
|
+
"core.symlinks=true",
|
|
4621
|
+
"-c",
|
|
4622
|
+
"core.filemode=true",
|
|
4623
|
+
"-c",
|
|
4624
|
+
"core.autocrlf=false",
|
|
4625
|
+
"reset",
|
|
4626
|
+
"--hard",
|
|
4627
|
+
commit
|
|
4628
|
+
]);
|
|
4629
|
+
}
|
|
4380
4630
|
|
|
4381
4631
|
class ProjectManager {
|
|
4382
4632
|
storage;
|
|
@@ -4525,8 +4775,7 @@ class ProjectManager {
|
|
|
4525
4775
|
if (fetched.sha && fetched.sha !== await repo.resolveRef("HEAD")) {
|
|
4526
4776
|
if ((await repo.status()).dirty)
|
|
4527
4777
|
throw new Error("Session has uncheckpointed work on this machine. Recover it before moving the session.");
|
|
4528
|
-
await repo.
|
|
4529
|
-
await repo.checkout("main");
|
|
4778
|
+
await resetSessionCheckout(repo.repoPath, fetched.sha);
|
|
4530
4779
|
}
|
|
4531
4780
|
}
|
|
4532
4781
|
return repo;
|
|
@@ -4536,30 +4785,146 @@ class ProjectManager {
|
|
|
4536
4785
|
}
|
|
4537
4786
|
}
|
|
4538
4787
|
async checkpointSession(args) {
|
|
4539
|
-
const repo = await this.openSession(args);
|
|
4788
|
+
const repo = await this.openSession({ ...args, refresh: true });
|
|
4540
4789
|
try {
|
|
4541
|
-
const sha =
|
|
4542
|
-
|
|
4543
|
-
|
|
4544
|
-
|
|
4545
|
-
|
|
4546
|
-
|
|
4547
|
-
|
|
4548
|
-
|
|
4549
|
-
|
|
4550
|
-
|
|
4790
|
+
const sha = await this.checkpointCopy({
|
|
4791
|
+
...args,
|
|
4792
|
+
repo,
|
|
4793
|
+
publish: async (head, previous) => {
|
|
4794
|
+
await args.held?.();
|
|
4795
|
+
await this.publishSession({
|
|
4796
|
+
...args,
|
|
4797
|
+
repo,
|
|
4798
|
+
head,
|
|
4799
|
+
force: false,
|
|
4800
|
+
...args.snapshot ? { expected: previous } : {}
|
|
4801
|
+
});
|
|
4802
|
+
}
|
|
4803
|
+
});
|
|
4551
4804
|
return sha;
|
|
4552
4805
|
} finally {
|
|
4553
4806
|
await repo.dispose();
|
|
4554
4807
|
}
|
|
4555
4808
|
}
|
|
4809
|
+
async checkpointCopy(args) {
|
|
4810
|
+
const { repo } = args;
|
|
4811
|
+
const recorded = await currentSessionWork({
|
|
4812
|
+
repoPath: repo.repoPath,
|
|
4813
|
+
sessionId: args.sessionId,
|
|
4814
|
+
base: args.base
|
|
4815
|
+
});
|
|
4816
|
+
const snapshot = await args.snapshot?.({
|
|
4817
|
+
repoPath: repo.repoPath,
|
|
4818
|
+
recorded,
|
|
4819
|
+
containLinks: repo instanceof NativeProjectRepo
|
|
4820
|
+
});
|
|
4821
|
+
const saved = snapshot?.work ?? args.work;
|
|
4822
|
+
const pushed = args.pushed ?? recorded.pushed;
|
|
4823
|
+
const work = {
|
|
4824
|
+
head: saved?.head ?? recorded.head,
|
|
4825
|
+
branch: saved?.branch ?? recorded.branch,
|
|
4826
|
+
...pushed ? { pushed } : {}
|
|
4827
|
+
};
|
|
4828
|
+
const previousTree = (await nativeGit(repo.repoPath, [
|
|
4829
|
+
"rev-parse",
|
|
4830
|
+
`${recorded.checkpoint}^{tree}`
|
|
4831
|
+
])).trim();
|
|
4832
|
+
const dirty = !snapshot && (await repo.status()).dirty;
|
|
4833
|
+
const moved = work.head !== recorded.head || work.branch !== recorded.branch || work.pushed?.branch !== recorded.pushed?.branch || work.pushed?.commit !== recorded.pushed?.commit;
|
|
4834
|
+
if (!dirty && !moved && (!snapshot?.tree || snapshot.tree === previousTree)) {
|
|
4835
|
+
await args.publish?.(recorded.checkpoint, recorded.checkpoint);
|
|
4836
|
+
return recorded.checkpoint;
|
|
4837
|
+
}
|
|
4838
|
+
const tree = snapshot?.tree ?? (dirty ? await repo.commit(args.message, args.author) : previousTree);
|
|
4839
|
+
const sha = await writeCheckpoint({
|
|
4840
|
+
repoPath: repo.repoPath,
|
|
4841
|
+
tree,
|
|
4842
|
+
previous: recorded.checkpoint,
|
|
4843
|
+
message: args.message,
|
|
4844
|
+
author: args.author,
|
|
4845
|
+
work
|
|
4846
|
+
});
|
|
4847
|
+
await args.publish?.(sha, recorded.checkpoint);
|
|
4848
|
+
if (snapshot)
|
|
4849
|
+
await resetSessionCheckout(repo.repoPath, sha);
|
|
4850
|
+
else
|
|
4851
|
+
await repo.moveBranch("main", sha);
|
|
4852
|
+
return sha;
|
|
4853
|
+
}
|
|
4854
|
+
async sessionWork(args) {
|
|
4855
|
+
const repo = await this.openSession(args);
|
|
4856
|
+
try {
|
|
4857
|
+
return await currentSessionWork({
|
|
4858
|
+
repoPath: repo.repoPath,
|
|
4859
|
+
sessionId: args.sessionId,
|
|
4860
|
+
base: args.base
|
|
4861
|
+
});
|
|
4862
|
+
} finally {
|
|
4863
|
+
await repo.dispose();
|
|
4864
|
+
}
|
|
4865
|
+
}
|
|
4556
4866
|
mirrorPath(args) {
|
|
4557
4867
|
return this.storage.mirrorPath?.(args.tenantId, args.projectId) ?? null;
|
|
4558
4868
|
}
|
|
4869
|
+
async mainCommit(args) {
|
|
4870
|
+
if (this.remote && await this.remote.exists(args.tenantId, args.projectId)) {
|
|
4871
|
+
const sha = await this.remote.withOrigin(args.tenantId, args.projectId, (origin) => origin.resolveRef("refs/heads/main"));
|
|
4872
|
+
if (sha)
|
|
4873
|
+
return sha;
|
|
4874
|
+
}
|
|
4875
|
+
const repo = await this.open(args.tenantId, args.projectId);
|
|
4876
|
+
try {
|
|
4877
|
+
return await repo.resolveRef("HEAD");
|
|
4878
|
+
} finally {
|
|
4879
|
+
await repo.dispose();
|
|
4880
|
+
}
|
|
4881
|
+
}
|
|
4882
|
+
async bringBase(args) {
|
|
4883
|
+
const { repo } = args;
|
|
4884
|
+
if (args.pin) {
|
|
4885
|
+
const mirrorPath = this.mirrorPath(args);
|
|
4886
|
+
if (!mirrorPath)
|
|
4887
|
+
throw new Error("This host keeps no project mirror");
|
|
4888
|
+
await copyFromMirror({
|
|
4889
|
+
mirrorPath,
|
|
4890
|
+
pin: args.pin,
|
|
4891
|
+
repoPath: repo.repoPath,
|
|
4892
|
+
into: "refs/work/base"
|
|
4893
|
+
});
|
|
4894
|
+
} else if (this.remote) {
|
|
4895
|
+
await Promise.resolve().then(() => init_git_sync());
|
|
4896
|
+
await fetchRemote({
|
|
4897
|
+
dev: repo,
|
|
4898
|
+
remote: this.remote,
|
|
4899
|
+
tenantId: args.tenantId,
|
|
4900
|
+
projectId: args.projectId,
|
|
4901
|
+
remoteBranch: "main"
|
|
4902
|
+
});
|
|
4903
|
+
} else {
|
|
4904
|
+
const main = await this.open(args.tenantId, args.projectId);
|
|
4905
|
+
try {
|
|
4906
|
+
if (path9.resolve(main.repoPath) !== path9.resolve(repo.repoPath))
|
|
4907
|
+
await nativeGit(repo.repoPath, [
|
|
4908
|
+
"fetch",
|
|
4909
|
+
"--quiet",
|
|
4910
|
+
"--no-tags",
|
|
4911
|
+
"--no-write-fetch-head",
|
|
4912
|
+
main.repoPath,
|
|
4913
|
+
"+HEAD:refs/work/base"
|
|
4914
|
+
]);
|
|
4915
|
+
} finally {
|
|
4916
|
+
await main.dispose();
|
|
4917
|
+
}
|
|
4918
|
+
}
|
|
4919
|
+
await nativeGit(repo.repoPath, [
|
|
4920
|
+
"cat-file",
|
|
4921
|
+
"-e",
|
|
4922
|
+
`${args.commit}^{commit}`
|
|
4923
|
+
]).catch(() => {
|
|
4924
|
+
throw new Error(`The workspace's base ${args.commit.slice(0, 12)} is not in the project's history on this host`);
|
|
4925
|
+
});
|
|
4926
|
+
}
|
|
4559
4927
|
async setSessionBase(args) {
|
|
4560
|
-
const mirrorPath = this.mirrorPath(args);
|
|
4561
|
-
if (!mirrorPath)
|
|
4562
|
-
throw new Error("This host keeps no project mirror");
|
|
4563
4928
|
const repo = await this.openSession({
|
|
4564
4929
|
tenantId: args.tenantId,
|
|
4565
4930
|
projectId: args.projectId,
|
|
@@ -4567,16 +4932,46 @@ class ProjectManager {
|
|
|
4567
4932
|
refresh: true
|
|
4568
4933
|
});
|
|
4569
4934
|
try {
|
|
4570
|
-
await
|
|
4571
|
-
|
|
4572
|
-
pin: args.pin,
|
|
4935
|
+
await this.bringBase({ ...args, repo });
|
|
4936
|
+
const checkpoint = await writeCheckpoint({
|
|
4573
4937
|
repoPath: repo.repoPath,
|
|
4574
|
-
|
|
4938
|
+
tree: args.commit,
|
|
4939
|
+
previous: args.commit,
|
|
4940
|
+
message: "Start the workspace",
|
|
4941
|
+
author: SYSTEM_AUTHOR2,
|
|
4942
|
+
work: { head: args.commit, branch: sessionBranchName(args.sessionId) }
|
|
4575
4943
|
});
|
|
4576
|
-
await
|
|
4577
|
-
await repo.
|
|
4944
|
+
await this.publishSession({ ...args, repo, head: checkpoint });
|
|
4945
|
+
await resetSessionCheckout(repo.repoPath, checkpoint);
|
|
4578
4946
|
await repo.resetWorkingTree();
|
|
4579
|
-
|
|
4947
|
+
} finally {
|
|
4948
|
+
await repo.dispose();
|
|
4949
|
+
}
|
|
4950
|
+
}
|
|
4951
|
+
async adoptSessionBase(args) {
|
|
4952
|
+
const repo = await this.openSession({
|
|
4953
|
+
tenantId: args.tenantId,
|
|
4954
|
+
projectId: args.projectId,
|
|
4955
|
+
sessionId: args.sessionId,
|
|
4956
|
+
refresh: true
|
|
4957
|
+
});
|
|
4958
|
+
try {
|
|
4959
|
+
await this.bringBase({ ...args, repo });
|
|
4960
|
+
const previous = await repo.resolveRef("HEAD");
|
|
4961
|
+
const snapshot = (await repo.status()).dirty ? await repo.commit(args.message, args.author) : previous;
|
|
4962
|
+
const sha = await writeCheckpoint({
|
|
4963
|
+
repoPath: repo.repoPath,
|
|
4964
|
+
tree: snapshot,
|
|
4965
|
+
previous,
|
|
4966
|
+
message: args.message,
|
|
4967
|
+
author: args.author,
|
|
4968
|
+
work: {
|
|
4969
|
+
head: args.commit,
|
|
4970
|
+
branch: sessionBranchName(args.sessionId)
|
|
4971
|
+
}
|
|
4972
|
+
});
|
|
4973
|
+
await repo.moveBranch("main", sha);
|
|
4974
|
+
await this.publishSession({ ...args, repo, head: sha, force: false });
|
|
4580
4975
|
} finally {
|
|
4581
4976
|
await repo.dispose();
|
|
4582
4977
|
}
|
|
@@ -4591,18 +4986,81 @@ class ProjectManager {
|
|
|
4591
4986
|
sessionId: args.sessionId,
|
|
4592
4987
|
refresh: true
|
|
4593
4988
|
});
|
|
4989
|
+
const git = (gitArgs) => nativeGit(repo.repoPath, gitArgs).then((output) => output.trim());
|
|
4594
4990
|
try {
|
|
4595
|
-
|
|
4991
|
+
await this.checkpointCopy({
|
|
4992
|
+
repo,
|
|
4993
|
+
sessionId: args.sessionId,
|
|
4994
|
+
message: "Save the workspace before moving its base",
|
|
4995
|
+
author: args.author,
|
|
4996
|
+
base: args.from
|
|
4997
|
+
});
|
|
4998
|
+
const work = await currentSessionWork({
|
|
4596
4999
|
repoPath: repo.repoPath,
|
|
4597
|
-
|
|
4598
|
-
|
|
4599
|
-
from: args.from,
|
|
4600
|
-
to: args.to,
|
|
4601
|
-
update: args.update
|
|
5000
|
+
sessionId: args.sessionId,
|
|
5001
|
+
base: args.from
|
|
4602
5002
|
});
|
|
4603
|
-
|
|
4604
|
-
|
|
4605
|
-
|
|
5003
|
+
const uncommitted = await git(["rev-parse", `${work.checkpoint}^{tree}`]) !== await git(["rev-parse", `${work.head}^{tree}`]);
|
|
5004
|
+
const marker = `Work: uncommitted changes ${work.checkpoint}`;
|
|
5005
|
+
const start = uncommitted ? await git([
|
|
5006
|
+
"-c",
|
|
5007
|
+
`user.name=${args.author.name}`,
|
|
5008
|
+
"-c",
|
|
5009
|
+
`user.email=${args.author.email}`,
|
|
5010
|
+
"commit-tree",
|
|
5011
|
+
`${work.checkpoint}^{tree}`,
|
|
5012
|
+
"-p",
|
|
5013
|
+
work.head,
|
|
5014
|
+
"-m",
|
|
5015
|
+
marker
|
|
5016
|
+
]) : work.head;
|
|
5017
|
+
const stand = async (commit) => {
|
|
5018
|
+
await git(["update-ref", "--no-deref", "HEAD", commit]);
|
|
5019
|
+
await git(["reset", "--quiet"]);
|
|
5020
|
+
};
|
|
5021
|
+
await stand(start);
|
|
5022
|
+
let outcome;
|
|
5023
|
+
let moved;
|
|
5024
|
+
try {
|
|
5025
|
+
outcome = await moveCheckoutBase({
|
|
5026
|
+
repoPath: repo.repoPath,
|
|
5027
|
+
mirrorPath,
|
|
5028
|
+
pin: args.pin,
|
|
5029
|
+
from: args.from,
|
|
5030
|
+
to: args.to,
|
|
5031
|
+
update: args.update
|
|
5032
|
+
});
|
|
5033
|
+
if (outcome.status === "moved") {
|
|
5034
|
+
const tip = outcome.head;
|
|
5035
|
+
const carried = uncommitted && args.update === "rebase" && await git(["log", "-1", "--format=%s", tip]) === marker;
|
|
5036
|
+
moved = {
|
|
5037
|
+
tip,
|
|
5038
|
+
head: carried ? await git(["rev-parse", `${tip}^`]) : tip
|
|
5039
|
+
};
|
|
5040
|
+
}
|
|
5041
|
+
} finally {
|
|
5042
|
+
await git(["symbolic-ref", "HEAD", "refs/heads/main"]);
|
|
5043
|
+
}
|
|
5044
|
+
if (!moved) {
|
|
5045
|
+
await git(["reset", "--quiet"]);
|
|
5046
|
+
return { ...outcome, head: work.head };
|
|
5047
|
+
}
|
|
5048
|
+
const sha = await writeCheckpoint({
|
|
5049
|
+
repoPath: repo.repoPath,
|
|
5050
|
+
tree: moved.tip,
|
|
5051
|
+
previous: work.checkpoint,
|
|
5052
|
+
message: args.update === "reset" ? "Reset the workspace to a new base" : "Rebase the workspace onto a new base",
|
|
5053
|
+
author: args.author,
|
|
5054
|
+
work: {
|
|
5055
|
+
head: moved.head,
|
|
5056
|
+
branch: work.branch,
|
|
5057
|
+
...work.pushed ? { pushed: work.pushed } : {}
|
|
5058
|
+
}
|
|
5059
|
+
});
|
|
5060
|
+
await repo.moveBranch("main", sha);
|
|
5061
|
+
await git(["reset", "--quiet"]);
|
|
5062
|
+
await this.publishSession({ ...args, repo, head: sha, force: false });
|
|
5063
|
+
return { status: "moved", head: moved.head };
|
|
4606
5064
|
} finally {
|
|
4607
5065
|
await repo.dispose();
|
|
4608
5066
|
}
|
|
@@ -4617,7 +5075,8 @@ class ProjectManager {
|
|
|
4617
5075
|
projectId: args.projectId,
|
|
4618
5076
|
remoteBranch: `sessions/${args.sessionId}`,
|
|
4619
5077
|
localSha: args.head,
|
|
4620
|
-
force: true
|
|
5078
|
+
force: args.force ?? true,
|
|
5079
|
+
...args.expected ? { expected: args.expected } : {}
|
|
4621
5080
|
});
|
|
4622
5081
|
}
|
|
4623
5082
|
async resetSession(args) {
|
|
@@ -4628,10 +5087,9 @@ class ProjectManager {
|
|
|
4628
5087
|
refresh: true
|
|
4629
5088
|
});
|
|
4630
5089
|
try {
|
|
4631
|
-
await repo.moveBranch("main", args.commit);
|
|
4632
|
-
await repo.checkout("main");
|
|
4633
|
-
await repo.resetWorkingTree();
|
|
4634
5090
|
await this.publishSession({ ...args, repo, head: args.commit });
|
|
5091
|
+
await resetSessionCheckout(repo.repoPath, args.commit);
|
|
5092
|
+
await repo.resetWorkingTree();
|
|
4635
5093
|
} finally {
|
|
4636
5094
|
await repo.dispose();
|
|
4637
5095
|
}
|
|
@@ -4770,6 +5228,665 @@ async function seedFromOrigin(opts) {
|
|
|
4770
5228
|
// src/index.ts
|
|
4771
5229
|
init_project_repo();
|
|
4772
5230
|
init_ref_names();
|
|
5231
|
+
|
|
5232
|
+
// src/workspace-save.ts
|
|
5233
|
+
init_native_git();
|
|
5234
|
+
init_personal_files();
|
|
5235
|
+
import {
|
|
5236
|
+
spawn
|
|
5237
|
+
} from "node:child_process";
|
|
5238
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
5239
|
+
import { constants } from "node:fs";
|
|
5240
|
+
import fs9 from "node:fs/promises";
|
|
5241
|
+
import { tmpdir as tmpdir3 } from "node:os";
|
|
5242
|
+
import path10 from "node:path";
|
|
5243
|
+
|
|
5244
|
+
class WorkspaceSaveError extends Error {
|
|
5245
|
+
constructor(message, options) {
|
|
5246
|
+
super(message, options);
|
|
5247
|
+
this.name = "WorkspaceSaveError";
|
|
5248
|
+
}
|
|
5249
|
+
}
|
|
5250
|
+
var OBJECT_ID = /^[0-9a-f]{40}$|^[0-9a-f]{64}$/;
|
|
5251
|
+
var RECORD = /^:([0-7]{6}) ([0-7]{6}) ([0-9a-f]{40}|[0-9a-f]{64}) ([0-9a-f]{40}|[0-9a-f]{64}) ([AMTD])$/;
|
|
5252
|
+
var GITLINK = "160000";
|
|
5253
|
+
var HFS_IGNORED = /[---]/g;
|
|
5254
|
+
var TREE_MODES = new Set(["40000", "100644", "100755", "120000", GITLINK]);
|
|
5255
|
+
var MAX_TREE_BYTES = 64 * 1024 * 1024;
|
|
5256
|
+
var MAX_LINK_BYTES = 4096;
|
|
5257
|
+
var MAX_MANIFEST_BYTES = 64 * 1024 * 1024;
|
|
5258
|
+
function isGitDirectoryName(segment) {
|
|
5259
|
+
const name = (segment.split(":")[0] ?? "").replace(HFS_IGNORED, "").replace(/[. ]+$/, "").toLowerCase();
|
|
5260
|
+
return name === ".git" || name === "git~1";
|
|
5261
|
+
}
|
|
5262
|
+
function assertSavedPath(filePath) {
|
|
5263
|
+
const refuse = (why) => {
|
|
5264
|
+
throw new WorkspaceSaveError(`the workspace names a path that ${why}: ${JSON.stringify(filePath.slice(0, 200))}`);
|
|
5265
|
+
};
|
|
5266
|
+
if (filePath.length === 0 || filePath.includes("\x00"))
|
|
5267
|
+
refuse("is not a path");
|
|
5268
|
+
if (filePath.startsWith("/"))
|
|
5269
|
+
refuse("is absolute");
|
|
5270
|
+
if (path10.sep === "\\" && (filePath.includes("\\") || /^[A-Za-z]:/.test(filePath)))
|
|
5271
|
+
refuse("is not portable");
|
|
5272
|
+
for (const segment of filePath.split("/")) {
|
|
5273
|
+
if (segment === "" || segment === "." || segment === "..")
|
|
5274
|
+
refuse("leaves the checkout");
|
|
5275
|
+
if (isGitDirectoryName(segment))
|
|
5276
|
+
refuse("is inside a Git directory");
|
|
5277
|
+
}
|
|
5278
|
+
}
|
|
5279
|
+
function parseSavedChanges(manifest) {
|
|
5280
|
+
const fields = splitOnNul(manifest);
|
|
5281
|
+
if (fields.length % 2 !== 0)
|
|
5282
|
+
throw new WorkspaceSaveError("the list of changed files was cut short");
|
|
5283
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
5284
|
+
const changes = [];
|
|
5285
|
+
const seen = new Set;
|
|
5286
|
+
for (let index = 0;index < fields.length; index += 2) {
|
|
5287
|
+
const record = RECORD.exec(Buffer.from(fields[index] ?? new Uint8Array).toString("latin1"));
|
|
5288
|
+
if (!record)
|
|
5289
|
+
throw new WorkspaceSaveError("the list of changed files was unreadable");
|
|
5290
|
+
const [, before = "", after = "", , oid = "", status = ""] = record;
|
|
5291
|
+
const name = decodePath(decoder, fields[index + 1] ?? new Uint8Array);
|
|
5292
|
+
assertSavedPath(name);
|
|
5293
|
+
if (seen.has(name))
|
|
5294
|
+
throw new WorkspaceSaveError(`the workspace names ${JSON.stringify(name)} twice`);
|
|
5295
|
+
seen.add(name);
|
|
5296
|
+
if (status === "D" !== (after === "000000"))
|
|
5297
|
+
throw new WorkspaceSaveError("the list of changed files was unreadable");
|
|
5298
|
+
if (after === "000000" || after === GITLINK) {
|
|
5299
|
+
if (before !== GITLINK && before !== "000000")
|
|
5300
|
+
changes.push({ path: name, kind: "deleted" });
|
|
5301
|
+
} else if (after === "100644" || after === "100755") {
|
|
5302
|
+
changes.push({ path: name, kind: "file", mode: after, oid });
|
|
5303
|
+
} else if (after === "120000") {
|
|
5304
|
+
changes.push({ path: name, kind: "link", oid });
|
|
5305
|
+
} else {
|
|
5306
|
+
throw new WorkspaceSaveError(`the workspace holds ${JSON.stringify(name)} with a mode (${after}) that cannot be saved`);
|
|
5307
|
+
}
|
|
5308
|
+
}
|
|
5309
|
+
assertNoFileIsAFolder(changes);
|
|
5310
|
+
return changes;
|
|
5311
|
+
}
|
|
5312
|
+
function splitOnNul(bytes) {
|
|
5313
|
+
const fields = [];
|
|
5314
|
+
let start = 0;
|
|
5315
|
+
for (let index = 0;index < bytes.length; index += 1) {
|
|
5316
|
+
if (bytes[index] !== 0)
|
|
5317
|
+
continue;
|
|
5318
|
+
fields.push(bytes.subarray(start, index));
|
|
5319
|
+
start = index + 1;
|
|
5320
|
+
}
|
|
5321
|
+
if (start !== bytes.length)
|
|
5322
|
+
throw new WorkspaceSaveError("the list of changed files was cut short");
|
|
5323
|
+
return fields;
|
|
5324
|
+
}
|
|
5325
|
+
function decodePath(decoder, bytes) {
|
|
5326
|
+
try {
|
|
5327
|
+
return decoder.decode(bytes);
|
|
5328
|
+
} catch {
|
|
5329
|
+
throw new WorkspaceSaveError("the workspace holds a file whose name is not UTF-8; rename it so the workspace can be saved");
|
|
5330
|
+
}
|
|
5331
|
+
}
|
|
5332
|
+
function assertNoFileIsAFolder(changes) {
|
|
5333
|
+
const written = new Set(changes.flatMap((change) => change.kind === "deleted" ? [] : [change.path]));
|
|
5334
|
+
for (const file of written) {
|
|
5335
|
+
const segments = file.split("/");
|
|
5336
|
+
for (let depth = 1;depth < segments.length; depth += 1)
|
|
5337
|
+
if (written.has(segments.slice(0, depth).join("/")))
|
|
5338
|
+
throw new WorkspaceSaveError(`the workspace names ${JSON.stringify(file)} inside something that is not a folder`);
|
|
5339
|
+
}
|
|
5340
|
+
}
|
|
5341
|
+
function assertSavedTree(input) {
|
|
5342
|
+
const { tree, idBytes } = input;
|
|
5343
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
5344
|
+
let offset = 0;
|
|
5345
|
+
while (offset < tree.length) {
|
|
5346
|
+
const space = tree.indexOf(32, offset);
|
|
5347
|
+
const nul = space < 0 ? -1 : tree.indexOf(0, space + 1);
|
|
5348
|
+
if (space < 0 || nul < 0 || nul + 1 + idBytes > tree.length)
|
|
5349
|
+
throw new WorkspaceSaveError("the branch holds a folder Git cannot read");
|
|
5350
|
+
const mode = Buffer.from(tree.subarray(offset, space)).toString("latin1");
|
|
5351
|
+
const name = decodePath(decoder, tree.subarray(space + 1, nul));
|
|
5352
|
+
if (!TREE_MODES.has(mode))
|
|
5353
|
+
throw new WorkspaceSaveError(`the branch holds ${JSON.stringify(name.slice(0, 200))} with a mode (${mode.slice(0, 12)}) that cannot be saved`);
|
|
5354
|
+
if (name.includes("/"))
|
|
5355
|
+
throw new WorkspaceSaveError(`the branch names a path that is not one name: ${JSON.stringify(name.slice(0, 200))}`);
|
|
5356
|
+
assertSavedPath(name);
|
|
5357
|
+
offset = nul + 1 + idBytes;
|
|
5358
|
+
}
|
|
5359
|
+
}
|
|
5360
|
+
function gitEnvironment() {
|
|
5361
|
+
return { ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_TERMINAL_PROMPT: "0" };
|
|
5362
|
+
}
|
|
5363
|
+
|
|
5364
|
+
class ReceivedPack {
|
|
5365
|
+
directory;
|
|
5366
|
+
idBytes;
|
|
5367
|
+
reader;
|
|
5368
|
+
constructor(directory, idBytes) {
|
|
5369
|
+
this.directory = directory;
|
|
5370
|
+
this.idBytes = idBytes;
|
|
5371
|
+
}
|
|
5372
|
+
static async receive(input) {
|
|
5373
|
+
const directory = await fs9.mkdtemp(path10.join(tmpdir3(), "work-save-"));
|
|
5374
|
+
try {
|
|
5375
|
+
await nativeGit(directory, [
|
|
5376
|
+
"init",
|
|
5377
|
+
"--bare",
|
|
5378
|
+
"--quiet",
|
|
5379
|
+
...input.objectFormat === "sha256" ? ["--object-format=sha256"] : []
|
|
5380
|
+
]);
|
|
5381
|
+
if (input.borrow) {
|
|
5382
|
+
const objects = (await nativeGit(input.borrow, [
|
|
5383
|
+
"rev-parse",
|
|
5384
|
+
"--path-format=absolute",
|
|
5385
|
+
"--git-path",
|
|
5386
|
+
"objects"
|
|
5387
|
+
])).trim();
|
|
5388
|
+
if (/[\n"]/.test(objects))
|
|
5389
|
+
throw new Error("The saved copy's path cannot be borrowed from");
|
|
5390
|
+
await fs9.writeFile(path10.join(directory, "objects", "info", "alternates"), `${objects}
|
|
5391
|
+
`);
|
|
5392
|
+
}
|
|
5393
|
+
await indexPack({ directory, chunks: input.chunks });
|
|
5394
|
+
return new ReceivedPack(directory, input.objectFormat === "sha256" ? 32 : 20);
|
|
5395
|
+
} catch (error) {
|
|
5396
|
+
await fs9.rm(directory, { recursive: true, force: true });
|
|
5397
|
+
throw error;
|
|
5398
|
+
}
|
|
5399
|
+
}
|
|
5400
|
+
async assertBlobs(input) {
|
|
5401
|
+
const oids = [...new Set(input.oids)];
|
|
5402
|
+
if (oids.length === 0)
|
|
5403
|
+
return;
|
|
5404
|
+
for (const oid of oids)
|
|
5405
|
+
if (!OBJECT_ID.test(oid))
|
|
5406
|
+
throw new WorkspaceSaveError("the workspace names an invalid object");
|
|
5407
|
+
const output = Buffer.from(await nativeGitBytes(this.directory, ["cat-file", "--batch-check"], new TextEncoder().encode(`${oids.join(`
|
|
5408
|
+
`)}
|
|
5409
|
+
`))).toString("latin1");
|
|
5410
|
+
const lines = output.split(`
|
|
5411
|
+
`).filter(Boolean);
|
|
5412
|
+
if (lines.length !== oids.length)
|
|
5413
|
+
throw new WorkspaceSaveError("the saved files could not be listed");
|
|
5414
|
+
let total = 0;
|
|
5415
|
+
for (const [index, line] of lines.entries()) {
|
|
5416
|
+
const [oid, type, size] = line.split(" ");
|
|
5417
|
+
if (oid !== oids[index] || type !== "blob" || !/^\d+$/.test(size ?? ""))
|
|
5418
|
+
throw new WorkspaceSaveError("the workspace's pack lacks a file it names");
|
|
5419
|
+
total += Number(size);
|
|
5420
|
+
if (total > input.maxBytes)
|
|
5421
|
+
throw new WorkspaceSaveError(`the workspace changed more than ${Math.floor(input.maxBytes / (1024 * 1024))} MiB of files at once`);
|
|
5422
|
+
}
|
|
5423
|
+
}
|
|
5424
|
+
async assertHistory(input) {
|
|
5425
|
+
for (const oid of [input.head, ...input.known])
|
|
5426
|
+
if (!OBJECT_ID.test(oid))
|
|
5427
|
+
throw new WorkspaceSaveError("the workspace names an invalid commit");
|
|
5428
|
+
const range = [input.head, "--not", ...input.known];
|
|
5429
|
+
const walk = async (args) => {
|
|
5430
|
+
try {
|
|
5431
|
+
return (await nativeGit(this.directory, ["rev-list", ...args, ...range])).split(`
|
|
5432
|
+
`).filter(Boolean);
|
|
5433
|
+
} catch {
|
|
5434
|
+
throw new WorkspaceSaveError("the branch's commits build on history that did not arrive with them; fetch that history (git fetch --unshallow) or go back to a branch that starts from this workspace's base");
|
|
5435
|
+
}
|
|
5436
|
+
};
|
|
5437
|
+
const commits = await walk([
|
|
5438
|
+
"--parents",
|
|
5439
|
+
`--max-count=${input.maxCommits + 1}`
|
|
5440
|
+
]);
|
|
5441
|
+
if (commits.length > input.maxCommits)
|
|
5442
|
+
throw new WorkspaceSaveError(`the branch gained more than ${input.maxCommits} commits at once`);
|
|
5443
|
+
for (const line of commits)
|
|
5444
|
+
if (!line.includes(" "))
|
|
5445
|
+
throw new WorkspaceSaveError("the branch holds a commit with no parent, so its history does not start from this workspace's base");
|
|
5446
|
+
const objects = await walk(["--objects", "--no-object-names"]);
|
|
5447
|
+
if (objects.length === 0)
|
|
5448
|
+
return { commits: [] };
|
|
5449
|
+
const listed = Buffer.from(await nativeGitBytes(this.directory, ["cat-file", "--batch-check"], new TextEncoder().encode(`${objects.join(`
|
|
5450
|
+
`)}
|
|
5451
|
+
`))).toString("latin1").split(`
|
|
5452
|
+
`).filter(Boolean);
|
|
5453
|
+
if (listed.length !== objects.length)
|
|
5454
|
+
throw new WorkspaceSaveError("the branch's commits could not be listed");
|
|
5455
|
+
let total = 0;
|
|
5456
|
+
for (const [index, line] of listed.entries()) {
|
|
5457
|
+
const [oid, type, size] = line.split(" ");
|
|
5458
|
+
if (oid !== objects[index] || !/^\d+$/.test(size ?? ""))
|
|
5459
|
+
throw new WorkspaceSaveError("the branch's commits name an object that did not arrive");
|
|
5460
|
+
total += Number(size);
|
|
5461
|
+
if (total > input.maxBytes)
|
|
5462
|
+
throw new WorkspaceSaveError(`the branch gained more than ${Math.floor(input.maxBytes / (1024 * 1024))} MiB of commits at once`);
|
|
5463
|
+
if (type === "tree")
|
|
5464
|
+
assertSavedTree({
|
|
5465
|
+
tree: await this.readObject({ oid: oid ?? "", type: "tree" }),
|
|
5466
|
+
idBytes: this.idBytes
|
|
5467
|
+
});
|
|
5468
|
+
else if (type !== "commit" && type !== "blob")
|
|
5469
|
+
throw new WorkspaceSaveError("the branch's commits hold something that is not a commit, a folder or a file");
|
|
5470
|
+
}
|
|
5471
|
+
return { commits: commits.map((line) => line.split(" ")[0] ?? "") };
|
|
5472
|
+
}
|
|
5473
|
+
async unpackHistory(input) {
|
|
5474
|
+
for (const oid of [input.head, ...input.known])
|
|
5475
|
+
if (!OBJECT_ID.test(oid))
|
|
5476
|
+
throw new WorkspaceSaveError("the workspace names an invalid commit");
|
|
5477
|
+
await this.unpack({
|
|
5478
|
+
repoPath: input.repoPath,
|
|
5479
|
+
revisions: `${input.head}
|
|
5480
|
+
${input.known.map((oid) => `^${oid}
|
|
5481
|
+
`).join("")}`
|
|
5482
|
+
});
|
|
5483
|
+
}
|
|
5484
|
+
async snapshotTree(input) {
|
|
5485
|
+
const changes = withoutPersonalFiles(input.changes);
|
|
5486
|
+
for (const change of changes) {
|
|
5487
|
+
assertSavedPath(change.path);
|
|
5488
|
+
if (change.kind === "link") {
|
|
5489
|
+
const target = await readLinkTarget(this, change);
|
|
5490
|
+
if (input.containLinks)
|
|
5491
|
+
assertLinkStaysInside(change.path, target);
|
|
5492
|
+
}
|
|
5493
|
+
}
|
|
5494
|
+
const previousTree = (await nativeGit(this.directory, ["rev-parse", `${input.previous}^{tree}`])).trim();
|
|
5495
|
+
await nativeGit(this.directory, ["read-tree", previousTree]);
|
|
5496
|
+
const zeros = "0".repeat(this.idBytes * 2);
|
|
5497
|
+
const deleted = [];
|
|
5498
|
+
const written = [];
|
|
5499
|
+
for (const change of changes) {
|
|
5500
|
+
if (change.kind === "deleted") {
|
|
5501
|
+
deleted.push(`0 ${zeros} ${change.path}\x00`);
|
|
5502
|
+
} else {
|
|
5503
|
+
const mode = change.kind === "link" ? "120000" : change.mode;
|
|
5504
|
+
written.push(`${mode} ${change.oid} ${change.path}\x00`);
|
|
5505
|
+
}
|
|
5506
|
+
}
|
|
5507
|
+
if (deleted.length || written.length) {
|
|
5508
|
+
try {
|
|
5509
|
+
await nativeGitBytes(this.directory, ["update-index", "-z", "--index-info"], Buffer.from(deleted.join("") + written.join("")));
|
|
5510
|
+
} catch (error) {
|
|
5511
|
+
throw new WorkspaceSaveError("the saved paths conflict with the checkpoint's files", { cause: error });
|
|
5512
|
+
}
|
|
5513
|
+
}
|
|
5514
|
+
const tree = (await nativeGit(this.directory, ["write-tree"])).trim();
|
|
5515
|
+
if (tree !== previousTree) {
|
|
5516
|
+
const claimed = new Set(changes.map((change) => change.path));
|
|
5517
|
+
const changed = await nativeGitBytes(this.directory, [
|
|
5518
|
+
"diff-tree",
|
|
5519
|
+
"-r",
|
|
5520
|
+
"-z",
|
|
5521
|
+
"--no-renames",
|
|
5522
|
+
"--name-only",
|
|
5523
|
+
previousTree,
|
|
5524
|
+
tree
|
|
5525
|
+
]);
|
|
5526
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
5527
|
+
for (const name of splitOnNul(changed)) {
|
|
5528
|
+
const filePath = decodePath(decoder, name);
|
|
5529
|
+
if (!claimed.has(filePath))
|
|
5530
|
+
throw new WorkspaceSaveError(`the workspace tried to replace ${JSON.stringify(filePath)} without naming it in the save`);
|
|
5531
|
+
}
|
|
5532
|
+
await this.unpack({
|
|
5533
|
+
repoPath: input.repoPath,
|
|
5534
|
+
revisions: `${tree}
|
|
5535
|
+
^${previousTree}
|
|
5536
|
+
`
|
|
5537
|
+
});
|
|
5538
|
+
}
|
|
5539
|
+
return tree;
|
|
5540
|
+
}
|
|
5541
|
+
async unpack(input) {
|
|
5542
|
+
const packer = spawn("git", ["-C", this.directory, "pack-objects", "--revs", "--stdout", "--quiet"], { env: gitEnvironment(), stdio: ["pipe", "pipe", "ignore"] });
|
|
5543
|
+
const unpacker = spawn("git", ["-C", input.repoPath, "unpack-objects", "--strict", "-q"], { env: gitEnvironment(), stdio: ["pipe", "ignore", "pipe"] });
|
|
5544
|
+
const stderr = [];
|
|
5545
|
+
unpacker.stderr.on("data", (chunk) => {
|
|
5546
|
+
if (stderr.length < 16)
|
|
5547
|
+
stderr.push(chunk);
|
|
5548
|
+
});
|
|
5549
|
+
packer.stdin.on("error", () => {});
|
|
5550
|
+
unpacker.stdin.on("error", () => {});
|
|
5551
|
+
const exit = (child) => new Promise((resolve, reject) => {
|
|
5552
|
+
child.on("error", reject);
|
|
5553
|
+
child.on("close", resolve);
|
|
5554
|
+
});
|
|
5555
|
+
const packed = exit(packer);
|
|
5556
|
+
const unpacked = exit(unpacker);
|
|
5557
|
+
packer.stdout.pipe(unpacker.stdin);
|
|
5558
|
+
packer.stdin.end(input.revisions);
|
|
5559
|
+
const [packCode, unpackCode] = await Promise.all([packed, unpacked]);
|
|
5560
|
+
if (packCode !== 0 || unpackCode !== 0) {
|
|
5561
|
+
const detail = Buffer.concat(stderr).toString("utf8").trim().split(`
|
|
5562
|
+
`)[0];
|
|
5563
|
+
throw new WorkspaceSaveError(`the workspace's objects could not be kept${detail ? ` (${detail.slice(0, 200)})` : ""}`);
|
|
5564
|
+
}
|
|
5565
|
+
}
|
|
5566
|
+
async read(input) {
|
|
5567
|
+
const parts = [];
|
|
5568
|
+
await this.stream({
|
|
5569
|
+
oid: input.oid,
|
|
5570
|
+
maxBytes: input.maxBytes,
|
|
5571
|
+
write: async (chunk) => {
|
|
5572
|
+
parts.push(Uint8Array.from(chunk));
|
|
5573
|
+
}
|
|
5574
|
+
});
|
|
5575
|
+
return new Uint8Array(Buffer.concat(parts));
|
|
5576
|
+
}
|
|
5577
|
+
async readObject(input) {
|
|
5578
|
+
const parts = [];
|
|
5579
|
+
await this.stream({
|
|
5580
|
+
oid: input.oid,
|
|
5581
|
+
type: input.type,
|
|
5582
|
+
maxBytes: MAX_TREE_BYTES,
|
|
5583
|
+
write: async (chunk) => {
|
|
5584
|
+
parts.push(Uint8Array.from(chunk));
|
|
5585
|
+
}
|
|
5586
|
+
});
|
|
5587
|
+
return new Uint8Array(Buffer.concat(parts));
|
|
5588
|
+
}
|
|
5589
|
+
async copy(input) {
|
|
5590
|
+
await this.stream({ ...input, maxBytes: Number.MAX_SAFE_INTEGER });
|
|
5591
|
+
}
|
|
5592
|
+
async stream(input) {
|
|
5593
|
+
this.reader ??= new BlobReader(this.directory);
|
|
5594
|
+
const reader = this.reader;
|
|
5595
|
+
try {
|
|
5596
|
+
await reader.copy(input);
|
|
5597
|
+
} catch (error) {
|
|
5598
|
+
reader.close();
|
|
5599
|
+
if (this.reader === reader)
|
|
5600
|
+
this.reader = undefined;
|
|
5601
|
+
throw error;
|
|
5602
|
+
}
|
|
5603
|
+
}
|
|
5604
|
+
async changes(input) {
|
|
5605
|
+
return parseSavedChanges(await this.read({ oid: input.manifest, maxBytes: MAX_MANIFEST_BYTES }));
|
|
5606
|
+
}
|
|
5607
|
+
async dispose() {
|
|
5608
|
+
this.reader?.close();
|
|
5609
|
+
this.reader = undefined;
|
|
5610
|
+
await fs9.rm(this.directory, { recursive: true, force: true });
|
|
5611
|
+
}
|
|
5612
|
+
}
|
|
5613
|
+
async function indexPack(input) {
|
|
5614
|
+
const child = spawn("git", ["-C", input.directory, "index-pack", "--stdin", "--fsck-objects"], { env: gitEnvironment(), stdio: ["pipe", "ignore", "pipe"] });
|
|
5615
|
+
const stderr = [];
|
|
5616
|
+
child.stderr.on("data", (chunk) => {
|
|
5617
|
+
if (stderr.length < 16)
|
|
5618
|
+
stderr.push(chunk);
|
|
5619
|
+
});
|
|
5620
|
+
child.stdin.on("error", () => {});
|
|
5621
|
+
const exited = new Promise((resolve, reject) => {
|
|
5622
|
+
child.on("error", reject);
|
|
5623
|
+
child.on("close", resolve);
|
|
5624
|
+
});
|
|
5625
|
+
try {
|
|
5626
|
+
for await (const chunk of input.chunks) {
|
|
5627
|
+
if (child.exitCode !== null || child.stdin.destroyed)
|
|
5628
|
+
break;
|
|
5629
|
+
if (!child.stdin.write(chunk))
|
|
5630
|
+
await new Promise((resolve) => {
|
|
5631
|
+
const done = () => {
|
|
5632
|
+
child.stdin.off("drain", done);
|
|
5633
|
+
child.off("close", done);
|
|
5634
|
+
resolve();
|
|
5635
|
+
};
|
|
5636
|
+
child.stdin.once("drain", done);
|
|
5637
|
+
child.once("close", done);
|
|
5638
|
+
});
|
|
5639
|
+
}
|
|
5640
|
+
} catch (error) {
|
|
5641
|
+
child.kill("SIGKILL");
|
|
5642
|
+
await exited.catch(() => null);
|
|
5643
|
+
throw error;
|
|
5644
|
+
}
|
|
5645
|
+
child.stdin.end();
|
|
5646
|
+
const code = await exited;
|
|
5647
|
+
if (code !== 0) {
|
|
5648
|
+
const detail = Buffer.concat(stderr).toString("utf8").trim().split(`
|
|
5649
|
+
`)[0];
|
|
5650
|
+
throw new WorkspaceSaveError(`the workspace's files arrived damaged${detail ? ` (${detail.slice(0, 200)})` : ""}`);
|
|
5651
|
+
}
|
|
5652
|
+
}
|
|
5653
|
+
|
|
5654
|
+
class BlobReader {
|
|
5655
|
+
child;
|
|
5656
|
+
output;
|
|
5657
|
+
pending = Buffer.alloc(0);
|
|
5658
|
+
last = Promise.resolve();
|
|
5659
|
+
constructor(directory) {
|
|
5660
|
+
this.child = spawn("git", ["-C", directory, "cat-file", "--batch"], {
|
|
5661
|
+
env: gitEnvironment(),
|
|
5662
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
5663
|
+
});
|
|
5664
|
+
this.child.on("error", () => {});
|
|
5665
|
+
this.child.stdin.on("error", () => {});
|
|
5666
|
+
this.child.stderr.resume();
|
|
5667
|
+
this.output = this.child.stdout[Symbol.asyncIterator]();
|
|
5668
|
+
}
|
|
5669
|
+
copy(input) {
|
|
5670
|
+
const next = this.last.then(() => this.copyNow(input));
|
|
5671
|
+
this.last = next.catch(() => {});
|
|
5672
|
+
return next;
|
|
5673
|
+
}
|
|
5674
|
+
async copyNow(input) {
|
|
5675
|
+
if (!OBJECT_ID.test(input.oid))
|
|
5676
|
+
throw new WorkspaceSaveError("the workspace names an invalid object");
|
|
5677
|
+
this.child.stdin.write(`${input.oid}
|
|
5678
|
+
`);
|
|
5679
|
+
const [oid, type, size] = (await this.line()).split(" ");
|
|
5680
|
+
if (oid !== input.oid || type !== (input.type ?? "blob") || !/^\d+$/.test(size ?? ""))
|
|
5681
|
+
throw new WorkspaceSaveError("the workspace's pack lacks a file it names");
|
|
5682
|
+
const length = Number(size);
|
|
5683
|
+
if (length > input.maxBytes)
|
|
5684
|
+
throw new WorkspaceSaveError("a saved file is larger than it may be");
|
|
5685
|
+
let left = length;
|
|
5686
|
+
while (left > 0) {
|
|
5687
|
+
if (this.pending.length === 0 && !await this.fill())
|
|
5688
|
+
throw new WorkspaceSaveError("a saved file was cut short");
|
|
5689
|
+
const part = this.pending.subarray(0, Math.min(left, this.pending.length));
|
|
5690
|
+
this.pending = this.pending.subarray(part.length);
|
|
5691
|
+
left -= part.length;
|
|
5692
|
+
await input.write(part);
|
|
5693
|
+
}
|
|
5694
|
+
while (this.pending.length === 0)
|
|
5695
|
+
if (!await this.fill())
|
|
5696
|
+
throw new WorkspaceSaveError("a saved file was cut short");
|
|
5697
|
+
this.pending = this.pending.subarray(1);
|
|
5698
|
+
}
|
|
5699
|
+
async line() {
|
|
5700
|
+
for (;; ) {
|
|
5701
|
+
const end = this.pending.indexOf(10);
|
|
5702
|
+
if (end >= 0) {
|
|
5703
|
+
const line = this.pending.subarray(0, end).toString("latin1");
|
|
5704
|
+
this.pending = this.pending.subarray(end + 1);
|
|
5705
|
+
return line;
|
|
5706
|
+
}
|
|
5707
|
+
if (this.pending.length > 256 || !await this.fill())
|
|
5708
|
+
throw new WorkspaceSaveError("the saved files could not be read");
|
|
5709
|
+
}
|
|
5710
|
+
}
|
|
5711
|
+
async fill() {
|
|
5712
|
+
const next = await this.output.next();
|
|
5713
|
+
if (next.done)
|
|
5714
|
+
return false;
|
|
5715
|
+
this.pending = this.pending.length > 0 ? Buffer.concat([this.pending, next.value]) : next.value;
|
|
5716
|
+
return true;
|
|
5717
|
+
}
|
|
5718
|
+
close() {
|
|
5719
|
+
this.child.stdin.end();
|
|
5720
|
+
this.child.kill("SIGKILL");
|
|
5721
|
+
}
|
|
5722
|
+
}
|
|
5723
|
+
async function lstatOrNull(target) {
|
|
5724
|
+
return fs9.lstat(target).catch((error) => {
|
|
5725
|
+
if (error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR"))
|
|
5726
|
+
return null;
|
|
5727
|
+
throw error;
|
|
5728
|
+
});
|
|
5729
|
+
}
|
|
5730
|
+
async function folderOf2(input) {
|
|
5731
|
+
let current = input.root;
|
|
5732
|
+
for (const segment of input.filePath.split("/").slice(0, -1)) {
|
|
5733
|
+
current = path10.join(current, segment);
|
|
5734
|
+
const stat = await lstatOrNull(current);
|
|
5735
|
+
if (!stat) {
|
|
5736
|
+
if (!input.create)
|
|
5737
|
+
return null;
|
|
5738
|
+
await fs9.mkdir(current);
|
|
5739
|
+
} else if (!stat.isDirectory()) {
|
|
5740
|
+
if (!input.create)
|
|
5741
|
+
return null;
|
|
5742
|
+
throw new WorkspaceSaveError(stat.isSymbolicLink() ? `${JSON.stringify(input.filePath)} would be written through a link, which a save never follows` : `${JSON.stringify(input.filePath)} needs a folder where the saved copy holds a file`);
|
|
5743
|
+
}
|
|
5744
|
+
}
|
|
5745
|
+
return current;
|
|
5746
|
+
}
|
|
5747
|
+
async function removeEmptyFolder(folder) {
|
|
5748
|
+
for (const entry of await fs9.readdir(folder, { withFileTypes: true })) {
|
|
5749
|
+
if (!entry.isDirectory())
|
|
5750
|
+
return false;
|
|
5751
|
+
if (!await removeEmptyFolder(path10.join(folder, entry.name)))
|
|
5752
|
+
return false;
|
|
5753
|
+
}
|
|
5754
|
+
await fs9.rmdir(folder);
|
|
5755
|
+
return true;
|
|
5756
|
+
}
|
|
5757
|
+
async function clearTarget(target, filePath) {
|
|
5758
|
+
const stat = await lstatOrNull(target);
|
|
5759
|
+
if (!stat)
|
|
5760
|
+
return;
|
|
5761
|
+
if (!stat.isDirectory()) {
|
|
5762
|
+
await fs9.unlink(target);
|
|
5763
|
+
return;
|
|
5764
|
+
}
|
|
5765
|
+
if (!await removeEmptyFolder(target))
|
|
5766
|
+
throw new WorkspaceSaveError(`${JSON.stringify(filePath)} is a file in the workspace, and a folder that still holds files in the saved copy`);
|
|
5767
|
+
}
|
|
5768
|
+
function withoutPersonalFiles(changes) {
|
|
5769
|
+
return changes.filter((change) => {
|
|
5770
|
+
if (!isPersonalFile(change.path))
|
|
5771
|
+
return true;
|
|
5772
|
+
if (change.kind === "deleted")
|
|
5773
|
+
return false;
|
|
5774
|
+
throw new WorkspaceSaveError(`${JSON.stringify(change.path)} is a personal file, which is never saved from a workspace`);
|
|
5775
|
+
});
|
|
5776
|
+
}
|
|
5777
|
+
function assertLinkStaysInside(filePath, target) {
|
|
5778
|
+
const refuse = () => {
|
|
5779
|
+
throw new WorkspaceSaveError(`${JSON.stringify(filePath)} is a link that leads outside the project folder; a workspace's links are kept in a person's own folder only when they point inside it`);
|
|
5780
|
+
};
|
|
5781
|
+
const text = (() => {
|
|
5782
|
+
try {
|
|
5783
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(target);
|
|
5784
|
+
} catch {
|
|
5785
|
+
return refuse();
|
|
5786
|
+
}
|
|
5787
|
+
})();
|
|
5788
|
+
if (text.startsWith("/") || text.includes("\\") || /^[A-Za-z]:/.test(text))
|
|
5789
|
+
refuse();
|
|
5790
|
+
const segments = text.split("/").filter((segment) => segment !== "" && segment !== ".");
|
|
5791
|
+
const climbs = segments.findIndex((segment) => segment !== "..");
|
|
5792
|
+
const up = climbs < 0 ? segments.length : climbs;
|
|
5793
|
+
const names = segments.slice(up);
|
|
5794
|
+
const depth = filePath.split("/").length - 1;
|
|
5795
|
+
if (up > depth || names.includes("..") || names.some(isGitDirectoryName))
|
|
5796
|
+
refuse();
|
|
5797
|
+
}
|
|
5798
|
+
async function writeSavedChanges(input) {
|
|
5799
|
+
const changes = withoutPersonalFiles(input.changes);
|
|
5800
|
+
for (const change of changes)
|
|
5801
|
+
assertSavedPath(change.path);
|
|
5802
|
+
for (const change of changes) {
|
|
5803
|
+
if (change.kind !== "deleted")
|
|
5804
|
+
continue;
|
|
5805
|
+
const folder = await folderOf2({
|
|
5806
|
+
root: input.repoPath,
|
|
5807
|
+
filePath: change.path,
|
|
5808
|
+
create: false
|
|
5809
|
+
});
|
|
5810
|
+
if (!folder)
|
|
5811
|
+
continue;
|
|
5812
|
+
const target = path10.join(folder, path10.posix.basename(change.path));
|
|
5813
|
+
const stat = await lstatOrNull(target);
|
|
5814
|
+
if (stat && !stat.isDirectory())
|
|
5815
|
+
await fs9.unlink(target);
|
|
5816
|
+
}
|
|
5817
|
+
for (const change of changes) {
|
|
5818
|
+
if (change.kind === "deleted")
|
|
5819
|
+
continue;
|
|
5820
|
+
const folder = await folderOf2({
|
|
5821
|
+
root: input.repoPath,
|
|
5822
|
+
filePath: change.path,
|
|
5823
|
+
create: true
|
|
5824
|
+
});
|
|
5825
|
+
if (!folder)
|
|
5826
|
+
continue;
|
|
5827
|
+
const target = path10.join(folder, path10.posix.basename(change.path));
|
|
5828
|
+
if (change.kind === "link") {
|
|
5829
|
+
const link = Buffer.from(await readLinkTarget(input.pack, change));
|
|
5830
|
+
if (input.containLinks)
|
|
5831
|
+
assertLinkStaysInside(change.path, link);
|
|
5832
|
+
await clearTarget(target, change.path);
|
|
5833
|
+
await fs9.symlink(link, target);
|
|
5834
|
+
continue;
|
|
5835
|
+
}
|
|
5836
|
+
const partial = path10.join(folder, `.work-save-${randomUUID2()}`);
|
|
5837
|
+
try {
|
|
5838
|
+
const handle = await fs9.open(partial, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), change.mode === "100755" ? 511 : 438);
|
|
5839
|
+
try {
|
|
5840
|
+
await input.pack.copy({
|
|
5841
|
+
oid: change.oid,
|
|
5842
|
+
write: async (chunk) => {
|
|
5843
|
+
await handle.writeFile(chunk);
|
|
5844
|
+
}
|
|
5845
|
+
});
|
|
5846
|
+
} finally {
|
|
5847
|
+
await handle.close();
|
|
5848
|
+
}
|
|
5849
|
+
await clearTarget(target, change.path);
|
|
5850
|
+
await fs9.rename(partial, target);
|
|
5851
|
+
} catch (error) {
|
|
5852
|
+
await fs9.rm(partial, { force: true });
|
|
5853
|
+
throw error;
|
|
5854
|
+
}
|
|
5855
|
+
}
|
|
5856
|
+
}
|
|
5857
|
+
async function readLinkTarget(pack, change) {
|
|
5858
|
+
const target = await pack.read({ oid: change.oid, maxBytes: MAX_LINK_BYTES });
|
|
5859
|
+
if (target.length === 0 || target.includes(0))
|
|
5860
|
+
throw new WorkspaceSaveError(`${JSON.stringify(change.path)} is a link with no usable target`);
|
|
5861
|
+
return target;
|
|
5862
|
+
}
|
|
5863
|
+
async function savedDraftChanges(input) {
|
|
5864
|
+
const changes = withoutPersonalFiles(input.changes);
|
|
5865
|
+
for (const change of changes)
|
|
5866
|
+
assertSavedPath(change.path);
|
|
5867
|
+
const draft = [];
|
|
5868
|
+
for (const change of changes) {
|
|
5869
|
+
if (change.kind === "deleted") {
|
|
5870
|
+
draft.push({ path: change.path, delete: true });
|
|
5871
|
+
} else if (change.kind === "link") {
|
|
5872
|
+
draft.push({
|
|
5873
|
+
path: change.path,
|
|
5874
|
+
content: await readLinkTarget(input.pack, change),
|
|
5875
|
+
mode: "120000"
|
|
5876
|
+
});
|
|
5877
|
+
} else {
|
|
5878
|
+
draft.push({
|
|
5879
|
+
path: change.path,
|
|
5880
|
+
content: await input.pack.read({
|
|
5881
|
+
oid: change.oid,
|
|
5882
|
+
maxBytes: Number.MAX_SAFE_INTEGER
|
|
5883
|
+
}),
|
|
5884
|
+
mode: change.mode
|
|
5885
|
+
});
|
|
5886
|
+
}
|
|
5887
|
+
}
|
|
5888
|
+
return draft;
|
|
5889
|
+
}
|
|
4773
5890
|
export {
|
|
4774
5891
|
CheckoutRemoteBackend,
|
|
4775
5892
|
DraftBinaryResolutionError,
|
|
@@ -4798,13 +5915,18 @@ export {
|
|
|
4798
5915
|
ProjectManager,
|
|
4799
5916
|
ProjectRepoImpl,
|
|
4800
5917
|
PushNotFastForwardError,
|
|
5918
|
+
ReceivedPack,
|
|
4801
5919
|
RefMovedError,
|
|
4802
5920
|
RemotePushRefusedError,
|
|
5921
|
+
WorkspaceSaveError,
|
|
4803
5922
|
assertPushAllowed,
|
|
5923
|
+
assertSavedPath,
|
|
5924
|
+
assertSavedTree,
|
|
4804
5925
|
assertValidRefName,
|
|
4805
5926
|
buildSeedPack,
|
|
4806
5927
|
cloneFromRemote,
|
|
4807
5928
|
copyFromMirror,
|
|
5929
|
+
currentSessionWork,
|
|
4808
5930
|
discoverLocalFolder,
|
|
4809
5931
|
ensurePersonalFilesExcluded,
|
|
4810
5932
|
fetchFromRemote,
|
|
@@ -4814,23 +5936,31 @@ export {
|
|
|
4814
5936
|
isCommitId,
|
|
4815
5937
|
isManagedBranch,
|
|
4816
5938
|
isPersonalFile,
|
|
5939
|
+
isSessionBranchName,
|
|
4817
5940
|
isValidRefName,
|
|
4818
5941
|
migrateWorkflowToProject,
|
|
4819
5942
|
mirrorChangedFiles,
|
|
4820
5943
|
moveCheckoutBase,
|
|
4821
5944
|
nativeGit,
|
|
5945
|
+
parseCheckpointMessage,
|
|
5946
|
+
parseSavedChanges,
|
|
4822
5947
|
parseWorkspaceRef,
|
|
4823
5948
|
probeConditionalWrites,
|
|
4824
5949
|
pull,
|
|
4825
5950
|
push,
|
|
5951
|
+
pushOwnBranch,
|
|
4826
5952
|
pushToRemote,
|
|
4827
5953
|
readFileSnapshot,
|
|
5954
|
+
readSessionWork,
|
|
4828
5955
|
refreshPublished,
|
|
5956
|
+
savedDraftChanges,
|
|
4829
5957
|
seedPackInstallScript,
|
|
5958
|
+
sessionBranchName,
|
|
4830
5959
|
shellQuote,
|
|
4831
5960
|
syncWithNetworkRemote,
|
|
4832
|
-
unpinMirrorRef
|
|
5961
|
+
unpinMirrorRef,
|
|
5962
|
+
writeSavedChanges
|
|
4833
5963
|
};
|
|
4834
5964
|
|
|
4835
|
-
//# debugId=
|
|
5965
|
+
//# debugId=38CC731FCD866E5064756E2164756E21
|
|
4836
5966
|
//# sourceMappingURL=index.js.map
|