@catamorphic/git 0.1.0-alpha.38 → 0.1.0-alpha.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -280,7 +280,7 @@ async function walkDirectory(dir, base, options) {
280
280
  const entries = await fs3.readdir(dir, { withFileTypes: true });
281
281
  const results = [];
282
282
  for (const entry of entries) {
283
- if (IGNORED_DIRS.has(entry.name))
283
+ if (WALK_SKIPPED_DIRS.has(entry.name))
284
284
  continue;
285
285
  if (!options?.includeHidden && entry.name.startsWith(".") && !ALLOWED_DOT_DIRS.has(entry.name) && !ALLOWED_DOT_FILES.has(entry.name))
286
286
  continue;
@@ -372,12 +372,16 @@ class ProjectRepoImpl {
372
372
  return readFileSnapshot({
373
373
  paths,
374
374
  options,
375
- read: async (file, maxBytes) => new TextDecoder().decode(await this.readSnapshotBytes(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), "r");
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)
@@ -830,12 +834,17 @@ async function commitSet(dir, ref) {
830
834
  return new Set;
831
835
  }
832
836
  }
833
- var IGNORED_DIRS, STAGING_BATCH_SIZE = 128, ALLOWED_DOT_DIRS, ALLOWED_DOT_FILES;
837
+ var WALK_SKIPPED_DIRS, STAGING_BATCH_SIZE = 128, ALLOWED_DOT_DIRS, ALLOWED_DOT_FILES;
834
838
  var init_project_repo = __esm(() => {
835
839
  init_file_reads();
836
840
  init_personal_files();
837
841
  init_ref_names();
838
- IGNORED_DIRS = new Set(["node_modules", ".git", "dist", ".turbo"]);
842
+ WALK_SKIPPED_DIRS = new Set([
843
+ "node_modules",
844
+ ".git",
845
+ "dist",
846
+ ".turbo"
847
+ ]);
839
848
  ALLOWED_DOT_DIRS = new Set([".agents", PROJECT_WORKSPACE_ROOT]);
840
849
  ALLOWED_DOT_FILES = new Set([".gitignore"]);
841
850
  });
@@ -848,12 +857,99 @@ import {
848
857
  PROJECT_PERSONAL_DIR as PROJECT_PERSONAL_DIR2,
849
858
  publishedRef as publishedRef2
850
859
  } from "@catamorphic/workflow/project-layout";
851
- var NativeProjectRepo;
860
+ import ignore2 from "ignore";
861
+ function walkUnversioned(root, folder) {
862
+ const key = `${root}\x00${folder}`;
863
+ const current = unversionedWalks.get(key);
864
+ if (!current)
865
+ return startWalk(key, root, folder);
866
+ current.queued ??= current.running.catch(() => {}).then(() => startWalk(key, root, folder));
867
+ return current.queued;
868
+ }
869
+ function startWalk(key, root, folder) {
870
+ const entry = {
871
+ running: walkFolder(root, folder),
872
+ queued: null
873
+ };
874
+ unversionedWalks.set(key, entry);
875
+ entry.running.finally(() => {
876
+ if (unversionedWalks.get(key) === entry)
877
+ unversionedWalks.delete(key);
878
+ }).catch(() => {});
879
+ return entry.running;
880
+ }
881
+ async function walkFolder(root, folder) {
882
+ const rules = [];
883
+ const options = {
884
+ includeHidden: true,
885
+ excludeNestedRepositories: true,
886
+ tracked: new Set,
887
+ trackedDirectories: new Set,
888
+ rules
889
+ };
890
+ if (!folder || !(await fs4.stat(root)).isDirectory())
891
+ return walkDirectory(root, root, options);
892
+ let current = root;
893
+ for (const segment of folder.slice(0, -1).split("/")) {
894
+ if (!segment || segment === "." || segment === "..")
895
+ return [];
896
+ const content = await fs4.readFile(path4.join(current, ".gitignore"), "utf8").catch(() => "");
897
+ if (content)
898
+ rules.push({ base: current, matcher: ignore2().add(content) });
899
+ const next = path4.join(current, segment);
900
+ if (WALK_SKIPPED_DIRS.has(segment) || isPersonalFile(path4.relative(root, next)) || isIgnoredDirectory(rules, next))
901
+ return [];
902
+ const stat = await fs4.lstat(next).catch(() => {
903
+ return;
904
+ });
905
+ if (!stat?.isDirectory())
906
+ return [];
907
+ current = next;
908
+ if (await fs4.stat(path4.join(current, ".git")).then(() => true, () => false))
909
+ return [];
910
+ }
911
+ return walkDirectory(current, root, options);
912
+ }
913
+ function isIgnoredDirectory(rules, directory) {
914
+ let ignored = false;
915
+ for (const rule of rules) {
916
+ const result = rule.matcher.test(`${path4.relative(rule.base, directory)}/`);
917
+ if (result.ignored)
918
+ ignored = true;
919
+ if (result.unignored)
920
+ ignored = false;
921
+ }
922
+ return ignored;
923
+ }
924
+ function folderOf(prefix) {
925
+ const cut = prefix.lastIndexOf("/");
926
+ return cut < 0 ? "" : prefix.slice(0, cut + 1);
927
+ }
928
+ function literalFolder(globs) {
929
+ const folders = globs.map((glob) => {
930
+ const wild = glob.search(/[*?[{]/);
931
+ return folderOf(wild < 0 ? glob : glob.slice(0, wild));
932
+ });
933
+ if (folders.length === 0)
934
+ return "";
935
+ return folders.reduce((common, folder) => {
936
+ let end = 0;
937
+ for (let i = 0;i < Math.min(common.length, folder.length); i++) {
938
+ if (common[i] !== folder[i])
939
+ break;
940
+ if (common[i] === "/")
941
+ end = i + 1;
942
+ }
943
+ return common.slice(0, end);
944
+ });
945
+ }
946
+ var unversionedWalks, NativeProjectRepo;
852
947
  var init_native_project_repo = __esm(() => {
853
948
  init_file_reads();
854
949
  init_native_git();
855
950
  init_personal_files();
856
951
  init_project_repo();
952
+ unversionedWalks = new Map;
857
953
  NativeProjectRepo = class NativeProjectRepo extends ProjectRepoImpl {
858
954
  followsSymlinks = true;
859
955
  async readFileBytes(filePath) {
@@ -875,8 +971,11 @@ var init_native_project_repo = __esm(() => {
875
971
  return this.readSnapshotBytes(filePath, 64 * 1024 * 1024);
876
972
  }
877
973
  async readAllFiles(options = {}) {
974
+ return this.readSnapshot(await this.listFiles(), options);
975
+ }
976
+ readSnapshot(paths, options) {
878
977
  return readFileSnapshot({
879
- paths: await this.listFiles(),
978
+ paths,
880
979
  options: { maxFileBytes: 2 * 1024 * 1024, ...options },
881
980
  read: async (file, maxBytes) => {
882
981
  const stat = await fs4.lstat(path4.join(this.repoPath, file));
@@ -897,14 +996,9 @@ var init_native_project_repo = __esm(() => {
897
996
  if (!await hasLocalGit({ path: this.repoPath })) {
898
997
  if (opts?.prefix)
899
998
  assertSafePath(opts.prefix);
900
- const files = await walkDirectory(this.repoPath, this.repoPath, {
901
- includeHidden: true,
902
- excludeNestedRepositories: true,
903
- tracked: new Set,
904
- trackedDirectories: new Set,
905
- rules: []
906
- });
907
- return files.filter((file) => !opts?.prefix || file.startsWith(opts.prefix)).sort();
999
+ const prefix = opts?.prefix ?? "";
1000
+ const files = await walkUnversioned(this.repoPath, folderOf(prefix));
1001
+ return files.filter((file) => file.startsWith(prefix)).sort();
908
1002
  }
909
1003
  const pathspec = opts?.prefix ? ["--", opts.prefix] : [];
910
1004
  const [output, removed] = await Promise.all([
@@ -935,7 +1029,7 @@ var init_native_project_repo = __esm(() => {
935
1029
  const matches = (file, glob) => path4.matchesGlob(file, glob) || !glob.includes("/") && path4.matchesGlob(path4.basename(file), glob);
936
1030
  const includes = input.globs.filter((glob) => !glob.startsWith(":!"));
937
1031
  const excludes = input.globs.filter((glob) => glob.startsWith(":!")).map((glob) => glob.slice(2));
938
- const files = await this.readAllFiles({
1032
+ const files = await this.readSnapshot(await this.listFiles({ prefix: literalFolder(includes) }), {
939
1033
  filter: (file) => includes.some((glob) => matches(file, glob)) && !excludes.some((glob) => matches(file, glob))
940
1034
  });
941
1035
  return Object.entries(files).filter(([, content]) => content.includes(input.text)).map(([file]) => file);
@@ -1318,7 +1412,7 @@ var init_git_object_codec = __esm(() => {
1318
1412
 
1319
1413
  // src/origin-objects.ts
1320
1414
  import diff3Merge from "diff3";
1321
- import ignore2 from "ignore";
1415
+ import ignore3 from "ignore";
1322
1416
  function isTreeMode(mode) {
1323
1417
  return mode === "40000" || mode === "040000";
1324
1418
  }
@@ -1542,7 +1636,7 @@ class OriginObjects {
1542
1636
  return true;
1543
1637
  if (!treeOid)
1544
1638
  return false;
1545
- if (await this.entry(treeOid, filePath))
1639
+ if (await this.entry(treeOid, filePath).catch(() => null))
1546
1640
  return false;
1547
1641
  let ignored = false;
1548
1642
  for (let depth = 0;depth < segments.length; depth++) {
@@ -1551,7 +1645,7 @@ class OriginObjects {
1551
1645
  let matcher = rules.get(directory);
1552
1646
  if (matcher === undefined) {
1553
1647
  const entry = await this.entry(treeOid, `${base}.gitignore`).catch(() => null);
1554
- matcher = entry && !isTreeMode(entry.mode) ? ignore2().add(new TextDecoder().decode(await this.blob(entry.oid))) : null;
1648
+ matcher = entry && !isTreeMode(entry.mode) ? ignore3().add(new TextDecoder().decode(await this.blob(entry.oid))) : null;
1555
1649
  rules.set(directory, matcher);
1556
1650
  }
1557
1651
  if (!matcher)
@@ -1565,29 +1659,40 @@ class OriginObjects {
1565
1659
  return ignored;
1566
1660
  }
1567
1661
  async writeTree(treeOid, changes, options) {
1568
- return await this.rewrite(treeOid, changes, "", options?.skipMissingDeletes) ?? this.write({ type: "tree", data: new Uint8Array });
1662
+ return await this.rewrite(treeOid, changes, "", options ?? {}) ?? this.write({ type: "tree", data: new Uint8Array });
1569
1663
  }
1570
- async rewrite(treeOid, changes, base, skipMissingDeletes = false) {
1664
+ async rewrite(treeOid, changes, base, options) {
1665
+ const skipMissingDeletes = options.skipMissingDeletes ?? false;
1571
1666
  const entries = new Map((treeOid ? await this.tree(treeOid) : []).map((entry) => [
1572
1667
  nameKey(entry.nameBytes),
1573
1668
  entry
1574
1669
  ]));
1575
1670
  const keyed = (name) => nameKey(new TextEncoder().encode(name));
1671
+ const leaves = new Map;
1576
1672
  const nested = new Map;
1577
1673
  for (const [filePath, change] of changes) {
1578
1674
  const slash = filePath.indexOf("/");
1579
- if (slash >= 0) {
1580
- const directory = filePath.slice(0, slash);
1581
- const inner = nested.get(directory) ?? new Map;
1582
- inner.set(filePath.slice(slash + 1), change);
1583
- nested.set(directory, inner);
1675
+ if (slash < 0) {
1676
+ leaves.set(filePath, change);
1584
1677
  continue;
1585
1678
  }
1586
- const existing = entries.get(keyed(filePath));
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) {
1587
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));
1588
1693
  if (existing && isTreeMode(existing.mode))
1589
1694
  throw new DraftPathError({ code: "EISDIR", path: fullPath });
1590
- if (existing?.mode === SYMLINK_MODE)
1695
+ if (existing?.mode === SYMLINK_MODE && !options.replaceLinks)
1591
1696
  throw new DraftPathError({ code: "ELOOP", path: fullPath });
1592
1697
  if (change === null) {
1593
1698
  if (!existing) {
@@ -1614,7 +1719,7 @@ class OriginObjects {
1614
1719
  path: `${fullPath}/${[...inner.keys()][0] ?? ""}`
1615
1720
  });
1616
1721
  }
1617
- const oid = await this.rewrite(existing?.oid ?? null, inner, `${fullPath}/`, skipMissingDeletes);
1722
+ const oid = await this.rewrite(existing?.oid ?? null, inner, `${fullPath}/`, options);
1618
1723
  return { directory, oid, keep: false };
1619
1724
  }));
1620
1725
  for (const child of children) {
@@ -1965,6 +2070,8 @@ async function push(opts) {
1965
2070
  if (currentRemote === localSha) {
1966
2071
  return { sha: localSha };
1967
2072
  }
2073
+ if (opts.expected !== undefined && currentRemote !== opts.expected)
2074
+ throw new Error("The workspace checkpoint changed before it could be published.");
1968
2075
  if (currentRemote && !opts.force) {
1969
2076
  const fastForward = await isAncestor({
1970
2077
  dev: opts.dev,
@@ -2819,6 +2926,7 @@ init_native_project_repo();
2819
2926
 
2820
2927
  // src/network.ts
2821
2928
  init_native_git();
2929
+ init_ref_names();
2822
2930
  import nodeFs5 from "node:fs";
2823
2931
  import { MANAGED_BRANCH_PREFIX } from "@catamorphic/workflow/project-layout";
2824
2932
  import git5 from "isomorphic-git";
@@ -2909,7 +3017,7 @@ function assertPushAllowed(input) {
2909
3017
  if (!isManagedBranch(input.remoteBranch)) {
2910
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.`);
2911
3019
  }
2912
- if (input.force) {
3020
+ if (input.force && !input.lease) {
2913
3021
  throw new RemotePushRefusedError(input.remoteBranch, "Work never rewrites history in an attached repository.");
2914
3022
  }
2915
3023
  }
@@ -2920,7 +3028,26 @@ async function pushToRemote(opts) {
2920
3028
  throw new RemotePushRefusedError(name, "not a plain branch or ref name.");
2921
3029
  }
2922
3030
  }
2923
- assertPushAllowed(opts);
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
+ }
2924
3051
  if (opts.native) {
2925
3052
  await nativeGit(opts.repoPath, [
2926
3053
  "push",
@@ -2941,6 +3068,90 @@ async function pushToRemote(opts) {
2941
3068
  onAuth: onAuthFor(opts.credentials)
2942
3069
  });
2943
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
+ }
2944
3155
  async function fetchFromRemote(opts) {
2945
3156
  const remote = "catamorphic-network";
2946
3157
  await git5.addRemote({
@@ -3619,14 +3830,20 @@ class OriginDraftRepo {
3619
3830
  async write(input) {
3620
3831
  const pending = new Map;
3621
3832
  for (const change of input.changes)
3622
- pending.set(normalizePath(change.path), "delete" in change ? null : typeof change.content === "string" ? new TextEncoder().encode(change.content) : change.content);
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
+ });
3623
3837
  const draftRefName = this.draftRefOrThrow();
3624
3838
  if (pending.size === 0)
3625
3839
  return null;
3626
3840
  const message = input.message ?? `Draft: ${[...pending.keys()].slice(0, 3).join(", ")}${pending.size > 3 ? ", ..." : ""}`;
3627
- const written = [...pending].filter((entry) => entry[1] !== null);
3628
- const oids = await this.withObjects((objects) => objects.writeBlobs(written.map(([, content]) => content)));
3629
- const blobs = new Map(written.map(([file], index) => [file, oids[index]]));
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
+ ]));
3630
3847
  for (let attempt = 0;attempt < MAX_ATTEMPTS; attempt++) {
3631
3848
  const outcome = await this.attempt(async (objects) => {
3632
3849
  const { draft, main } = await this.tips(objects);
@@ -3646,15 +3863,16 @@ class OriginDraftRepo {
3646
3863
  ignored.push(file);
3647
3864
  continue;
3648
3865
  }
3649
- const oid = blobs.get(file);
3650
- 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);
3651
3868
  }
3652
3869
  if (ignored.length > 0 && !input.skipIgnored)
3653
3870
  throw new DraftIgnoredPathError(ignored);
3654
3871
  if (changes.size === 0)
3655
3872
  return { sha: parent };
3656
3873
  const tree = await objects.writeTree(baseTree, changes, {
3657
- skipMissingDeletes: input.skipMissingDeletes
3874
+ skipMissingDeletes: input.skipMissingDeletes,
3875
+ replaceLinks: input.replaceLinks
3658
3876
  });
3659
3877
  if (tree === baseTree)
3660
3878
  return { sha: parent };
@@ -4043,16 +4261,130 @@ init_native_project_repo();
4043
4261
  init_origin_objects();
4044
4262
  init_project_repo();
4045
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
+
4046
4378
  // src/workspace-mirror.ts
4047
4379
  init_native_git();
4048
4380
  import { execFile as execFile2 } from "node:child_process";
4049
4381
  import fs7 from "node:fs/promises";
4050
4382
  import { tmpdir } from "node:os";
4051
4383
  import path8 from "node:path";
4052
- var COMMIT = /^[0-9a-f]{40}$|^[0-9a-f]{64}$/;
4384
+ var COMMIT2 = /^[0-9a-f]{40}$|^[0-9a-f]{64}$/;
4053
4385
  function parseWorkspaceRef(value) {
4054
4386
  const ref = value.trim();
4055
- if (COMMIT.test(ref))
4387
+ if (COMMIT2.test(ref))
4056
4388
  return ref;
4057
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)) {
4058
4390
  throw new Error(`'${value}' is not a branch, tag, commit, or full ref such as refs/pull/42/head`);
@@ -4060,7 +4392,7 @@ function parseWorkspaceRef(value) {
4060
4392
  return ref;
4061
4393
  }
4062
4394
  function isCommitId(ref) {
4063
- return COMMIT.test(ref);
4395
+ return COMMIT2.test(ref);
4064
4396
  }
4065
4397
  var mirrorLocks = new Map;
4066
4398
  async function withMirrorLock(mirrorPath, work) {
@@ -4192,44 +4524,39 @@ async function moveCheckoutBase(opts) {
4192
4524
  }
4193
4525
  }
4194
4526
  async function buildSeedPack(opts) {
4195
- const depth = await nativeGit(opts.repoPath, [
4196
- "rev-list",
4197
- "--count",
4198
- `${opts.base}..${opts.head}`
4199
- ]).then((count) => Number.parseInt(count.trim(), 10) + 1).catch(() => 1);
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");
4200
4533
  const directory = await fs7.mkdtemp(path8.join(tmpdir(), "work-seed-"));
4201
4534
  try {
4202
- await nativeGit(directory, ["init", "--bare", "--quiet"]);
4203
- const pin = `refs/work/seed/${process.pid}-${Date.now()}`;
4204
- await nativeGit(opts.repoPath, ["update-ref", pin, opts.head]);
4205
- try {
4206
- await nativeGit(directory, [
4207
- "fetch",
4208
- "--quiet",
4209
- "--no-tags",
4210
- `--depth=${depth}`,
4211
- `file://${path8.resolve(opts.repoPath)}`,
4212
- `+${pin}:refs/heads/main`
4213
- ]);
4214
- } finally {
4215
- await nativeGit(opts.repoPath, ["update-ref", "-d", pin]).catch(() => "");
4216
- }
4217
- const shallow = await fs7.readFile(path8.join(directory, "shallow"), "utf8").then((text) => text.split(`
4218
- `).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
+ `);
4219
4545
  const pack = await gitOutput({
4220
4546
  cwd: directory,
4221
4547
  args: ["pack-objects", "--revs", "--stdout", "--quiet"],
4222
- input: `${opts.head}
4548
+ input: `${[opts.head, opts.base, ...opts.tree ? [opts.tree] : []].join(`
4549
+ `)}
4223
4550
  `
4224
4551
  });
4225
- return { pack, shallow };
4552
+ return { pack, shallow: [opts.base] };
4226
4553
  } finally {
4227
4554
  await fs7.rm(directory, { recursive: true, force: true });
4228
4555
  }
4229
4556
  }
4230
4557
  function seedPackInstallScript(opts) {
4231
4558
  for (const commit of opts.shallow) {
4232
- if (!COMMIT.test(commit))
4559
+ if (!COMMIT2.test(commit))
4233
4560
  throw new Error("Invalid shallow commit");
4234
4561
  }
4235
4562
  const gitDir = `"$(git rev-parse --git-dir)"`;
@@ -4287,6 +4614,19 @@ var SYSTEM_AUTHOR2 = {
4287
4614
  name: "Work",
4288
4615
  email: "system@work.software"
4289
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
+ }
4290
4630
 
4291
4631
  class ProjectManager {
4292
4632
  storage;
@@ -4435,8 +4775,7 @@ class ProjectManager {
4435
4775
  if (fetched.sha && fetched.sha !== await repo.resolveRef("HEAD")) {
4436
4776
  if ((await repo.status()).dirty)
4437
4777
  throw new Error("Session has uncheckpointed work on this machine. Recover it before moving the session.");
4438
- await repo.moveBranch("main", fetched.sha);
4439
- await repo.checkout("main");
4778
+ await resetSessionCheckout(repo.repoPath, fetched.sha);
4440
4779
  }
4441
4780
  }
4442
4781
  return repo;
@@ -4446,30 +4785,146 @@ class ProjectManager {
4446
4785
  }
4447
4786
  }
4448
4787
  async checkpointSession(args) {
4449
- const repo = await this.openSession(args);
4788
+ const repo = await this.openSession({ ...args, refresh: true });
4450
4789
  try {
4451
- const sha = (await repo.status()).dirty ? await repo.commit(args.message, args.author) : await repo.resolveRef("HEAD");
4452
- if (this.remote)
4453
- await push({
4454
- dev: repo,
4455
- remote: this.remote,
4456
- tenantId: args.tenantId,
4457
- projectId: args.projectId,
4458
- remoteBranch: `sessions/${args.sessionId}`,
4459
- localSha: sha
4460
- });
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
+ });
4461
4804
  return sha;
4462
4805
  } finally {
4463
4806
  await repo.dispose();
4464
4807
  }
4465
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
+ }
4466
4866
  mirrorPath(args) {
4467
4867
  return this.storage.mirrorPath?.(args.tenantId, args.projectId) ?? null;
4468
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
+ }
4469
4927
  async setSessionBase(args) {
4470
- const mirrorPath = this.mirrorPath(args);
4471
- if (!mirrorPath)
4472
- throw new Error("This host keeps no project mirror");
4473
4928
  const repo = await this.openSession({
4474
4929
  tenantId: args.tenantId,
4475
4930
  projectId: args.projectId,
@@ -4477,16 +4932,46 @@ class ProjectManager {
4477
4932
  refresh: true
4478
4933
  });
4479
4934
  try {
4480
- await copyFromMirror({
4481
- mirrorPath,
4482
- pin: args.pin,
4935
+ await this.bringBase({ ...args, repo });
4936
+ const checkpoint = await writeCheckpoint({
4483
4937
  repoPath: repo.repoPath,
4484
- into: "refs/work/base"
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) }
4485
4943
  });
4486
- await repo.moveBranch("main", args.commit);
4487
- await repo.checkout("main");
4944
+ await this.publishSession({ ...args, repo, head: checkpoint });
4945
+ await resetSessionCheckout(repo.repoPath, checkpoint);
4488
4946
  await repo.resetWorkingTree();
4489
- await this.publishSession({ ...args, repo, head: args.commit });
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 });
4490
4975
  } finally {
4491
4976
  await repo.dispose();
4492
4977
  }
@@ -4501,18 +4986,81 @@ class ProjectManager {
4501
4986
  sessionId: args.sessionId,
4502
4987
  refresh: true
4503
4988
  });
4989
+ const git = (gitArgs) => nativeGit(repo.repoPath, gitArgs).then((output) => output.trim());
4504
4990
  try {
4505
- const outcome = await moveCheckoutBase({
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({
4506
4999
  repoPath: repo.repoPath,
4507
- mirrorPath,
4508
- pin: args.pin,
4509
- from: args.from,
4510
- to: args.to,
4511
- update: args.update
5000
+ sessionId: args.sessionId,
5001
+ base: args.from
5002
+ });
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
+ }
4512
5059
  });
4513
- if (outcome.status === "moved")
4514
- await this.publishSession({ ...args, repo, head: outcome.head });
4515
- return outcome;
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 };
4516
5064
  } finally {
4517
5065
  await repo.dispose();
4518
5066
  }
@@ -4527,7 +5075,8 @@ class ProjectManager {
4527
5075
  projectId: args.projectId,
4528
5076
  remoteBranch: `sessions/${args.sessionId}`,
4529
5077
  localSha: args.head,
4530
- force: true
5078
+ force: args.force ?? true,
5079
+ ...args.expected ? { expected: args.expected } : {}
4531
5080
  });
4532
5081
  }
4533
5082
  async resetSession(args) {
@@ -4538,10 +5087,9 @@ class ProjectManager {
4538
5087
  refresh: true
4539
5088
  });
4540
5089
  try {
4541
- await repo.moveBranch("main", args.commit);
4542
- await repo.checkout("main");
4543
- await repo.resetWorkingTree();
4544
5090
  await this.publishSession({ ...args, repo, head: args.commit });
5091
+ await resetSessionCheckout(repo.repoPath, args.commit);
5092
+ await repo.resetWorkingTree();
4545
5093
  } finally {
4546
5094
  await repo.dispose();
4547
5095
  }
@@ -4680,6 +5228,665 @@ async function seedFromOrigin(opts) {
4680
5228
  // src/index.ts
4681
5229
  init_project_repo();
4682
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
+ }
4683
5890
  export {
4684
5891
  CheckoutRemoteBackend,
4685
5892
  DraftBinaryResolutionError,
@@ -4708,13 +5915,18 @@ export {
4708
5915
  ProjectManager,
4709
5916
  ProjectRepoImpl,
4710
5917
  PushNotFastForwardError,
5918
+ ReceivedPack,
4711
5919
  RefMovedError,
4712
5920
  RemotePushRefusedError,
5921
+ WorkspaceSaveError,
4713
5922
  assertPushAllowed,
5923
+ assertSavedPath,
5924
+ assertSavedTree,
4714
5925
  assertValidRefName,
4715
5926
  buildSeedPack,
4716
5927
  cloneFromRemote,
4717
5928
  copyFromMirror,
5929
+ currentSessionWork,
4718
5930
  discoverLocalFolder,
4719
5931
  ensurePersonalFilesExcluded,
4720
5932
  fetchFromRemote,
@@ -4724,23 +5936,31 @@ export {
4724
5936
  isCommitId,
4725
5937
  isManagedBranch,
4726
5938
  isPersonalFile,
5939
+ isSessionBranchName,
4727
5940
  isValidRefName,
4728
5941
  migrateWorkflowToProject,
4729
5942
  mirrorChangedFiles,
4730
5943
  moveCheckoutBase,
4731
5944
  nativeGit,
5945
+ parseCheckpointMessage,
5946
+ parseSavedChanges,
4732
5947
  parseWorkspaceRef,
4733
5948
  probeConditionalWrites,
4734
5949
  pull,
4735
5950
  push,
5951
+ pushOwnBranch,
4736
5952
  pushToRemote,
4737
5953
  readFileSnapshot,
5954
+ readSessionWork,
4738
5955
  refreshPublished,
5956
+ savedDraftChanges,
4739
5957
  seedPackInstallScript,
5958
+ sessionBranchName,
4740
5959
  shellQuote,
4741
5960
  syncWithNetworkRemote,
4742
- unpinMirrorRef
5961
+ unpinMirrorRef,
5962
+ writeSavedChanges
4743
5963
  };
4744
5964
 
4745
- //# debugId=F09D854298D138D564756E2164756E21
5965
+ //# debugId=38CC731FCD866E5064756E2164756E21
4746
5966
  //# sourceMappingURL=index.js.map