openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
187 lines (186 loc) • 6.56 kB
JavaScript
import { t as hasNodeErrorCode } from "./path-guards-TIjxtj6H.mjs";
import { n as mergeProcessEnv } from "./process-env-DVJdcOcM.mjs";
import { d as normalizeGitPathForFilesystem, f as quoteGitConfig, l as gitNullConfigPath, m as requireGitCommandOutput, r as createGitCommandError } from "./git-exec-DHBL622T.mjs";
import { d as runGitBuffered, f as runGitBytes, n as gitEnvironment, o as requireGit, u as runGit } from "./git-BBx5S0aA.mjs";
import path from "node:path";
import fs from "node:fs/promises";
import os from "node:os";
//#region src/agents/worktrees/checkout-git-config.ts
const native = {
sourceOnly: false,
run: runGit,
require: requireGit,
worker: {
text: runGitBytes,
buffered: runGitBuffered
},
withContentEnvironment: async (e) => await e(gitEnvironment())
};
const sharedDirectories = [
"objects",
"refs",
"logs",
"worktrees",
"reftable"
];
const sharedFiles = [
"packed-refs",
"shallow",
"info/exclude"
];
/** Only content operations borrow this view. Ref authority remains with the real repository. */
function usesCanonicalMetadata(e) {
let t = 0;
while (e[t] === "-c") t += 2;
return [
"rev-parse",
"show-ref",
"update-ref",
"branch",
"fetch",
"worktree"
].includes(e[t] ?? "") && !(e[t] === "worktree" && e[t + 1] === "remove" && !e.includes("--force") && !e.includes("-f"));
}
/**
* Git reads repository config from GIT_COMMON_DIR, and config.worktree only when
* that config enables extensions.worktreeConfig (Git config.c). Keep the actual
* Git dir/index/HEAD and shared object/ref storage; substitute only trusted config
* for this operation. No repository or operator config is changed or locked.
*/
async function withWorktreeGitConfig(e, t, n, r) {
if (!t) return await r(native);
const check = () => {
n.signal?.throwIfAborted();
n.beforeRun?.();
};
check();
const i = {
...n,
operation: "worktree.config"
};
const a = path.resolve(e, normalizeGitPathForFilesystem(await requireGit(e, ["rev-parse", "--git-common-dir"], i)));
const o = await requireGit(e, ["rev-parse", "--show-object-format"], i);
if (o !== "sha1" && o !== "sha256") throw new Error("Unsupported Git object format");
const s = await runGit(e, [
"config",
"--local",
"--get",
"extensions.refStorage"
], i);
if (s.code !== 0 && s.code !== 1) throw createGitCommandError("git config refStorage", s);
const c = s.code === 1 ? "files" : s.stdout.trim();
if (c !== "files" && c !== "reftable") throw new Error("Unsupported Git ref storage");
const l = await runGit(e, [
"config",
"--includes",
"--null",
"--get-regexp",
"^core\\.(symlinks|ignorecase|precomposeunicode|excludesfile|autocrlf|eol|sparsecheckout|sparsecheckoutcone)$"
], i);
if (l.code !== 0 && l.code !== 1) throw createGitCommandError("git config layout", l);
const u = /* @__PURE__ */ new Map([["core.symlinks", String(process.platform !== "win32")]]);
for (const e of l.stdout.split("\0").filter(Boolean)) {
const t = e.indexOf("\n");
u.set(t < 0 ? e : e.slice(0, t), t < 0 ? "true" : e.slice(t + 1));
}
check();
const d = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-git-config-"));
let f = true;
const p = /* @__PURE__ */ new Set();
const assertActive = () => {
check();
if (!f) throw new Error("Git configuration scope closed");
};
const prepareMetadata = async (e) => {
for (const t of sharedDirectories) {
assertActive();
const n = path.join(a, t);
if (process.platform === "win32" && !await fs.stat(n).catch(() => void 0)) continue;
await fs.symlink(n, path.join(e, t), process.platform === "win32" ? "junction" : "dir");
}
await fs.mkdir(path.join(e, "info"));
for (const t of sharedFiles) {
assertActive();
const n = path.join(a, t);
const r = path.join(e, t);
if (process.platform === "win32") await fs.copyFile(n, r).catch((e) => {
if (!hasNodeErrorCode(e, "ENOENT")) throw e;
});
else await fs.symlink(n, r, "file");
}
};
try {
await prepareMetadata(d);
await fs.writeFile(path.join(d, "config"), `[core]\nrepositoryformatversion=${o === "sha256" || c === "reftable" ? 1 : 0}\nbare=false\nfilemode=${process.platform !== "win32"}\n${[...u].map(([e, t]) => `${e.slice(5)}=${quoteGitConfig(t)}\n`).join("")}[gc]\nauto=0\n[maintenance]\nauto=false\n[extensions]\n${o === "sha256" ? "objectFormat=sha256\n" : ""}${c === "reftable" ? "refStorage=reftable\n" : ""}`);
assertActive();
const optionsFor = async (e, t) => {
assertActive();
const n = {
...t,
refMutationDirectory: a,
beforeRun: () => {
assertActive();
t.beforeRun?.();
}
};
if (usesCanonicalMetadata(e)) return n;
let r = d;
if (process.platform === "win32") {
r = await fs.mkdtemp(path.join(d, "command-"));
await prepareMetadata(r);
await fs.copyFile(path.join(d, "config"), path.join(r, "config"));
}
const i = mergeProcessEnv([t.baseEnv ?? process.env, t.env]);
const o = Object.fromEntries(Object.entries(i).filter(([e]) => !e.toUpperCase().startsWith("GIT_")));
for (const [e, n] of Object.entries(t.env ?? {})) if (n !== void 0 && /^(?:GIT_INDEX_FILE|GIT_(?:AUTHOR|COMMITTER)_(?:NAME|EMAIL|DATE))$/u.test(e)) o[e] = n;
Object.assign(o, {
GIT_COMMON_DIR: r,
GIT_CONFIG_GLOBAL: gitNullConfigPath(),
GIT_CONFIG_SYSTEM: gitNullConfigPath(),
GIT_CONFIG_NOSYSTEM: "1",
GIT_ATTR_NOSYSTEM: "1",
GIT_NO_REPLACE_OBJECTS: "1",
GIT_NO_LAZY_FETCH: "1"
});
return {
...n,
baseEnv: o,
env: o
};
};
const track = (e) => {
assertActive();
const t = e();
p.add(t);
t.then(() => p.delete(t), () => p.delete(t));
return t;
};
const scopedRun = (e, t, n) => track(async () => await runGit(e, t, await optionsFor(t, { ...n })));
const scopedRequire = async (e, t, n = {}) => {
const r = await scopedRun(e, t, n);
return requireGitCommandOutput(`git ${t.join(" ")}`, r).trim();
};
return await r({
sourceOnly: true,
withContentEnvironment: (e) => track(async () => {
const t = await optionsFor(["pack-objects"], { env: {} });
return await e(gitEnvironment(t.env));
}),
run: scopedRun,
require: scopedRequire,
worker: {
text: (e, t, n = {}) => track(async () => await runGitBytes(e, t, await optionsFor(t, n))),
buffered: (e, t, n) => track(async () => await runGitBuffered(e, t, await optionsFor(t, { ...n })))
}
});
} finally {
f = false;
await Promise.allSettled(p);
await fs.rm(d, {
recursive: true,
force: true
});
}
}
//#endregion
export { withWorktreeGitConfig as t };