feat: 发布 1.1.0,自动更新并修复 #14 #15 #16

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
叫我小杨同学andCursor committed 2026-09-17 22:36:04 +08:00
1 parent 4dce6689a8
commit e8567a8d34
8 files changed
+564 -114

No files matched your search

+115 -19
View File
@@ -1164,7 +1164,31 @@ export function findDshHome(options = {}) {
const prefix = options.prefix !== undefined ? options.prefix : findNpmPrefix();
const portable = portableHomeFromLauncher(shimDir, prefix);
if (portable) return portable;
return path.join(os.homedir(), ".dsh");
const unix = path.join(os.homedir(), ".dsh");
if (isDir(unix)) return unix;
const wslWin = findWslWindowsDshHome(env);
if (wslWin) return wslWin;
return unix;
}
function findWslWindowsDshHome(env = process.env) {
if (process.platform !== "linux") return "";
const rel = env.WSL_DISTRO_NAME || env.WSLENV;
if (!rel && !isDir("/mnt/c/Users")) return "";
const users = "/mnt/c/Users";
if (!isDir(users)) return "";
let names = [];
try {
names = fs.readdirSync(users);
} catch {
return "";
}
for (const name of names) {
if (name === "Public" || name === "Default" || name === "Default User" || name === "All Users") continue;
const cand = path.join(users, name, ".dsh");
if (isDir(cand)) return path.normalize(cand);
}
return "";
}
export function findNpmPrefix() {
@@ -2095,14 +2119,12 @@ const NEW_TOOL_PATCHES = [
replace: 'prefix: ""',
},
{
// 1.3.6 把无缩进 identity+\n\n 抽掉后,行首 6 空格和下一段拼成 12 空格。
// 0.1.5 cordis:连同行首 6 空格删身份段,plane 说明缩进保持 6。
pattern:
" prefix: |-\n You can read and modify the harness you run on.",
replace:
" prefix: |-\n You can read and modify the harness you run on.",
" You are a coding agent powered by the {{model}} model, running on the DeepSeek Harness. Your working directory is {{cwd}}.\n\n",
replace: IDENTITY_STRIP,
},
{
// 0.1.5 cordis:连同行首 6 空格删身份段,plane 说明缩进保持 6。
pattern:
" You are a coding agent powered by the {{model}} model, running on the DeepSeek Harness.\n\n",
replace: IDENTITY_STRIP,
@@ -2158,6 +2180,13 @@ const NEW_TOOL_PATCHES = [
pattern: "Start every reply with the deliverable. - id: agent-instructions",
replace: "Start every reply with the deliverable.\n\n- id: agent-instructions",
},
{
// 1.3.6 无缩进 identity+\n\n 留下的 12 空格首行;sanitize 也会修。
pattern:
" prefix: |-\n You can read and modify the harness you run on.",
replace:
" prefix: |-\n You can read and modify the harness you run on.",
},
],
markersAny: true,
markers: [
@@ -2721,6 +2750,37 @@ const NEW_TOOL_PATCHES = [
],
markers: ["[dsh-purge] mnemon summary off-notice"],
},
{
// 0.1.5 assemble 在 waterfall 之后若有 complete:true,会丢掉全部 section,提示词写了也进不去。
id: 41, name: "COMPLETE_PROMPT_KEEP_INJECT", layer: "0.1.5 兼容", layer_en: "0.1.5",
desc: "complete 预设仍保留 dsh-purge 注入 / keep inject after complete prompt",
file: ["system-prompt", "system-prompt-nested"],
replacements: [
{
pattern:
"\t\treturn {\n" +
"\t\t\t...transformed,\n" +
"\t\t\tsections: completeSection === void 0 ? transformed.sections : [completeSection],\n" +
"\t\t\tcontexts: runtimeContextSuppressed ? [] : transformed.contexts\n" +
"\t\t};",
replace:
"\t\treturn {\n" +
"\t\t\t...transformed,\n" +
"\t\t\tsections: completeSection === void 0 ? transformed.sections : (function (complete, assembled) {\n" +
"\t\t\t\tconst sections = assembled.sections || [];\n" +
"\t\t\t\tconst inject = sections.filter((s) => String(s && s.name || \"\").startsWith(\"dsh-purge\")).map((s) => String(s.text || \"\").trim()).filter(Boolean).join(\"\\n\\n\");\n" +
"\t\t\t\tconst folded = sections.find((s) => s && s.name === complete.name);\n" +
"\t\t\t\tconst base = folded && typeof folded.text === \"string\" ? { ...complete, text: folded.text } : { ...complete };\n" +
"\t\t\t\tif (!inject) return [base];\n" +
"\t\t\t\tif (String(base.text || \"\").includes(inject.slice(0, Math.min(80, inject.length)))) return [base];\n" +
"\t\t\t\treturn [{ ...base, text: inject + \"\\n\\n\" + base.text }]; // [dsh-purge] complete prompt keeps inject\n" +
"\t\t\t})(completeSection, transformed),\n" +
"\t\t\tcontexts: runtimeContextSuppressed ? [] : transformed.contexts\n" +
"\t\t};",
},
],
markers: ["[dsh-purge] complete prompt keeps inject"],
},
];
export const ALL_PATCHES = [...PATCHES, ...CODE_PATCHES, ...ENGINE_PATCHES, ...NEW_TOOL_PATCHES];
@@ -3101,22 +3161,50 @@ function isDisposableYamlFoldParagraph(para) {
return false;
}
function yamlDropPaddingOnlyLines(bodyLines) {
return bodyLines.filter((line) => String(line).trim() !== "" || line === "");
}
function yamlMinContentIndent(bodyLines, keyIndent) {
let min = Infinity;
for (const line of bodyLines) {
if (!String(line).trim()) continue;
const n = yamlIndentOf(line);
if (n > keyIndent && n < min) min = n;
}
return Number.isFinite(min) ? min : keyIndent + 2;
}
function yamlReindentBody(bodyLines, indent) {
const pad = " ".repeat(Math.max(0, indent));
const out = [];
for (const line of bodyLines) {
if (!String(line).trim()) {
out.push("");
continue;
}
out.push(pad + String(line).replace(/^[ \t]+/, ""));
}
return out;
}
function yamlStripDisposableFoldParas(bodyLines) {
const raw = yamlFoldBodyText(bodyLines);
if (!raw) return [];
const kept = raw.split(/\n\s*\n/).filter((para) => !isDisposableYamlFoldParagraph(para));
if (kept.length === 0) return [];
const indent = (bodyLines.find((line) => String(line).trim()) || " ").match(/^[ \t]*/)[0] || " ";
const indent = yamlMinContentIndent(bodyLines, 0);
const pad = " ".repeat(indent || 6);
const out = [];
for (let i = 0; i < kept.length; i += 1) {
if (i > 0) out.push("");
for (const line of kept[i].split("\n")) out.push(indent + line);
for (const line of kept[i].split("\n")) out.push(pad + line);
}
return out;
}
function emptyDisposableFoldedYaml(text) {
const headerRe = /^(\s*)(personaPrefix|prefix|persona):\s*[>|][-+]?\s*$/;
const headerRe = /^(\s*)(personaPrefix|prefix|persona|text|suffix):\s*[>|][-+]?\s*$/;
const lines = String(text).split("\n");
const out = [];
for (let i = 0; i < lines.length; i += 1) {
@@ -3127,14 +3215,13 @@ function emptyDisposableFoldedYaml(text) {
}
const keyIndent = m[1].length;
const end = yamlConsumeFoldBody(lines, i, keyIndent);
const body = lines.slice(i + 1, end);
let body = yamlDropPaddingOnlyLines(lines.slice(i + 1, end));
const kept = yamlStripDisposableFoldParas(body);
if (kept.length === 0) out.push(`${m[1]}${m[2]}: ""`);
else if (kept.length === body.length && kept.every((line, idx) => line === body[idx])) {
out.push(lines[i], ...body);
} else {
else {
const indent = yamlMinContentIndent(kept, keyIndent);
out.push(`${m[1]}${m[2]}: |-`);
out.push(...kept);
out.push(...yamlReindentBody(kept, indent));
}
i = end - 1;
}
@@ -3142,7 +3229,7 @@ function emptyDisposableFoldedYaml(text) {
}
function stripOrphanYamlAfterEmptyScalars(text) {
const headerRe = /^(\s*)(personaPrefix|prefix|persona):\s*(""|'')\s*$/;
const headerRe = /^(\s*)(personaPrefix|prefix|persona|text|suffix):\s*(""|'')\s*$/;
const lines = String(text).split("\n");
const out = [];
for (let i = 0; i < lines.length; i += 1) {
@@ -3215,16 +3302,26 @@ function patchReplacements(p) {
return (p.patterns ?? []).map((pat) => ({ pattern: pat, replace: p.replace }));
}
function applyReplacementsToText(text, patch) {
function isBareIdentityNeedle(pattern) {
const needle = asLf(pattern);
if (!needle) return false;
if (/^[ \t]/.test(needle)) return false;
return /^You are a coding agent powered by\b/.test(needle);
}
function applyReplacementsToText(text, patch, fp = "") {
// 插入型补丁锚点仍在,已有标记则不再 replaceAll。
if (patch.skipIfMarked && patchApplied(text, patch)) {
return { text, changed: false };
}
const crlf = typeof text === "string" && text.includes("\r\n");
const yaml = isYamlPath(fp);
let out = asLf(text);
let changed = false;
for (const { pattern, replace } of patchReplacements(patch)) {
if (!pattern || typeof replace !== "string") continue;
// YAML 块标量行首有缩进;无缩进 identity+\n\n 会留下 6 空格,再和下一段拼成 12 空格。
if (yaml && isBareIdentityNeedle(pattern)) continue;
const needle = asLf(pattern);
if (!out.includes(needle)) continue;
out = out.split(needle).join(asLf(replace));
@@ -3321,7 +3418,7 @@ export async function applyPatches(aiBase, patches = ALL_PATCHES) {
lastError = "read_error";
continue;
}
const appliedText = applyReplacementsToText(text, p);
const appliedText = applyReplacementsToText(text, p, fp);
let textOut = appliedText.text;
let changed = appliedText.changed;
if (isYamlPath(fp)) {
@@ -3849,10 +3946,9 @@ export async function installOverride(dshHome, force = false) {
await fsp.mkdir(dshHome, { recursive: true });
if (fs.existsSync(fp) && !force) {
const existing = await loadText(fp);
// 非空保留用户内容;空文件视为故意清空。
// 空文件就是空:不注入、不改写。
return existing.trim().length > 0 ? "exists" : "empty";
}
// 文件不存在或 force 时写入默认稿。
await fsp.writeFile(fp, defaultOverrideText(), "utf8");
return "wrote";
}
+12 -1
View File
@@ -18,6 +18,7 @@ export const inject = ["systemPrompt", "tools"];
const DEFAULTS = {
enabled: true,
autoApplyOnStart: true,
autoUpdateOnStart: true,
autoRevertOnMissing: false,
postPrompt: "",
postPromptOrder: 5100,
@@ -474,6 +475,11 @@ export function apply(ctx, config) {
rules.ensureInitialState(core.findDshHome())
.then((r) => log(cfg, "rules init:", JSON.stringify(r)))
.catch((e) => console.warn("[dsh-purge] rules init error:", String(e)));
if (cfg.autoUpdateOnStart !== false) {
updater.autoUpdateIfNeeded()
.then((r) => log(cfg, "auto-update:", JSON.stringify(r)))
.catch((e) => console.warn("[dsh-purge] auto-update error:", String(e)));
}
});
installIdentityOverride(ctx);
@@ -686,6 +692,7 @@ function installWebServer(ctx, cfg) {
override_path: state.override_path,
dsh_home: state.dsh_home,
plugin_version: updater.localVersion(),
update: updater.lastUpdateResult(),
});
} catch (e) {
sendJson(response, 500, { ok: false, error: String(e) });
@@ -706,7 +713,11 @@ function installWebServer(ctx, cfg) {
}
if (request.method === "POST") {
try {
sendJson(response, 200, await updater.applyUpdate());
const body = await readJsonBody(request);
const result = body && body.auto
? await updater.autoUpdateIfNeeded()
: await updater.applyUpdate();
sendJson(response, 200, result);
} catch (e) {
sendJson(response, 500, { ok: false, error: String(e) });
}
+330 -48
View File
@@ -8,6 +8,8 @@ import { findDshHome } from "./core.js";
const REPO = "YuJunZhiXue/dsh-purge";
const BRANCH = "master";
const ZIP_URL = `https://github.com/${REPO}/archive/refs/heads/${BRANCH}.zip`;
const GITHUB_SPEC = `github:${REPO}#${BRANCH}`;
const PLUGIN_ROOT = path.resolve(fileURLToPath(new URL(".", import.meta.url)), "..");
const COPY_NAMES = [
"lib",
@@ -65,10 +67,40 @@ function sameRev(a, b) {
return a === b || a.startsWith(b) || b.startsWith(a);
}
function realPath(dir) {
try {
return fs.realpathSync(dir);
} catch {
return path.resolve(dir);
}
}
function readJson(fp) {
try {
return JSON.parse(fs.readFileSync(fp, "utf8"));
} catch {
return null;
}
}
function isGitCheckout(dir) {
return fs.existsSync(path.join(dir, ".git"));
}
function canGit(dir) {
if (!isGitCheckout(dir)) return false;
try {
execFileSync("git", ["-C", dir, "rev-parse", "--is-inside-work-tree"], HIDDEN);
return true;
} catch {
return false;
}
}
function gitOk() {
return canGit(PLUGIN_ROOT);
}
function gitHead(dir) {
try {
return execFileSync("git", ["-C", dir, "rev-parse", "HEAD"], HIDDEN).trim();
@@ -77,9 +109,157 @@ function gitHead(dir) {
}
}
async function fetchText(url, ms = 10000) {
function isLinkSpec(spec) {
const s = String(spec || "");
return /^(link|file):/i.test(s) || s === "." || /^\.\.?(?:[/\\]|$)/.test(s);
}
function resolveLinkDir(profileDir, spec) {
const raw = String(spec).replace(/^(link|file):/i, "");
return path.resolve(profileDir, raw);
}
function findPurgeProfiles() {
const root = path.join(findDshHome(), "profiles");
if (!fs.existsSync(root)) return [];
let names = [];
try {
names = fs.readdirSync(root);
} catch {
return [];
}
const out = [];
for (const name of names) {
const dir = path.join(root, name);
const pkg = readJson(path.join(dir, "package.json"));
const spec = pkg?.dependencies?.["dsh-purge"] || pkg?.devDependencies?.["dsh-purge"];
if (!spec) continue;
out.push({ name, dir, spec: String(spec) });
}
return out;
}
function profilePluginDir(profileDir) {
const nm = path.join(profileDir, "node_modules", "dsh-purge");
return fs.existsSync(nm) ? realPath(nm) : "";
}
function resolveDshBin() {
try {
execFileSync(process.platform === "win32" ? "where" : "which", ["dsh"], HIDDEN);
return "dsh";
} catch {
// 桌面进程 PATH 里经常没有 dsh,再到启动器旁找。
}
const home = findDshHome();
const names = process.platform === "win32" ? ["dsh.cmd", "dsh.exe", "dsh"] : ["dsh"];
const dirs = [
path.join(home, "..", "npm-global"),
path.join(home, "..", "npm-global-0.1.5-rc.1"),
path.join(home, "bin"),
];
for (const dir of dirs) {
for (const name of names) {
const fp = path.join(dir, name);
if (fs.existsSync(fp)) return fp;
}
}
return "";
}
function runDshPlugin(profile, args) {
const bin = resolveDshBin();
if (!bin) throw new Error("找不到 dsh");
execFileSync(bin, ["plugin", "--profile", profile, ...args], {
encoding: "utf8",
stdio: ["ignore", "pipe", "pipe"],
windowsHide: true,
timeout: 120000,
env: {
...process.env,
DSH_HOME: findDshHome(),
CI: "1",
},
});
}
function addSpecFor(spec) {
const s = String(spec || "");
if (/\.zip(\b|$)/i.test(s) || /^https?:\/\//i.test(s)) return ZIP_URL;
if (/^github:/i.test(s) || /github\.com\/.+\.git/i.test(s)) return GITHUB_SPEC;
return "";
}
function dshReinstall(profile, spec) {
const addSpec = addSpecFor(spec);
if (addSpec) {
runDshPlugin(profile, ["add", "--force", addSpec]);
return;
}
try {
runDshPlugin(profile, ["update", "dsh-purge"]);
} catch {
runDshPlugin(profile, ["add", "--force", ZIP_URL]);
}
}
function planUpdates() {
const profiles = findPurgeProfiles();
const jobs = [];
const seen = new Set();
const remember = (dir) => {
const key = realPath(dir).toLowerCase();
if (seen.has(key)) return false;
seen.add(key);
return true;
};
for (const p of profiles) {
if (isLinkSpec(p.spec)) {
const dir = resolveLinkDir(p.dir, p.spec);
if (!remember(dir)) continue;
jobs.push(canGit(dir) ? { kind: "git", dir, profile: p.name } : { kind: "zip", dir, profile: p.name });
continue;
}
const dir = profilePluginDir(p.dir) || PLUGIN_ROOT;
jobs.push({ kind: "dsh", profile: p.name, spec: p.spec, dir });
remember(dir);
}
if (!jobs.length) {
jobs.push(canGit(PLUGIN_ROOT) ? { kind: "git", dir: PLUGIN_ROOT } : { kind: "zip", dir: PLUGIN_ROOT });
return jobs;
}
if (remember(PLUGIN_ROOT)) {
jobs.push(canGit(PLUGIN_ROOT) ? { kind: "git", dir: PLUGIN_ROOT } : { kind: "zip", dir: PLUGIN_ROOT });
}
return jobs;
}
function detectVia() {
if (gitOk()) {
const extra = findPurgeProfiles().some((p) => !isLinkSpec(p.spec));
return extra ? "mixed" : "git";
}
if (findPurgeProfiles().some((p) => !isLinkSpec(p.spec))) return "dsh";
if (findPurgeProfiles().length) return "dsh";
return "zip";
}
function isAbortError(e) {
const msg = String((e && e.message) || e || "");
return (e && (e.name === "AbortError" || e.name === "TimeoutError")) || /aborted|abort/i.test(msg);
}
async function fetchRes(url, ms = 20000) {
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), ms);
const timer = setTimeout(() => {
try {
ctrl.abort("timeout");
} catch {
ctrl.abort();
}
}, ms);
try {
const res = await fetch(url, {
headers: { "user-agent": "dsh-purge-update", accept: "*/*" },
@@ -87,50 +267,58 @@ async function fetchText(url, ms = 10000) {
signal: ctrl.signal,
});
if (!res.ok) throw new Error(`http ${res.status}`);
return res.text();
return res;
} catch (e) {
if (e && e.name === "AbortError") throw new Error("GitHub 超时");
if (isAbortError(e)) throw new Error("GitHub 超时");
throw e;
} finally {
clearTimeout(timer);
}
}
async function fetchText(url, ms = 20000) {
return (await fetchRes(url, ms)).text();
}
async function fetchJson(url) {
return JSON.parse(await fetchText(url));
}
async function remotePackageVersion() {
try {
const pkg = await fetchJson(`https://raw.githubusercontent.com/${REPO}/${BRANCH}/package.json`);
return String(pkg.version || "");
} catch {
return "";
const urls = [
`https://raw.githubusercontent.com/${REPO}/${BRANCH}/package.json`,
`https://cdn.jsdelivr.net/gh/${REPO}@${BRANCH}/package.json`,
];
for (const url of urls) {
try {
const pkg = await fetchJson(url);
if (pkg && pkg.version) return String(pkg.version);
} catch {
// 换下一个源。
}
}
return "";
}
async function remoteHeadSha() {
try {
const data = await fetchJson(`https://api.github.com/repos/${REPO}/commits/${BRANCH}`);
if (data?.sha) return String(data.sha);
} catch {
// GitHub API 失败时改走 atom。
}
try {
const atom = await fetchText(`https://github.com/${REPO}/commits/${BRANCH}.atom`);
const hit = atom.match(/<id>tag:github\.com,2008:Grit::Commit\/([0-9a-f]{40})<\/id>/);
if (hit) return hit[1];
} catch {
// 只剩版本号对比。
}
return "";
const fromApi = fetchJson(`https://api.github.com/repos/${REPO}/commits/${BRANCH}`)
.then((data) => (data?.sha ? String(data.sha) : ""))
.catch(() => "");
const fromAtom = fetchText(`https://github.com/${REPO}/commits/${BRANCH}.atom`)
.then((atom) => {
const hit = atom.match(/<id>tag:github\.com,2008:Grit::Commit\/([0-9a-f]{40})<\/id>/);
return hit ? hit[1] : "";
})
.catch(() => "");
const [apiSha, atomSha] = await Promise.all([fromApi, fromAtom]);
return apiSha || atomSha || "";
}
export async function checkUpdate() {
const localVer = localVersion();
const [remoteSha, remoteVer] = await Promise.all([remoteHeadSha(), remotePackageVersion()]);
if (!remoteSha && !remoteVer) throw new Error("无法读取 GitHub master");
const gitSha = isGitCheckout(PLUGIN_ROOT) ? gitHead(PLUGIN_ROOT) : "";
const gitSha = gitOk() ? gitHead(PLUGIN_ROOT) : "";
const stamp = readStamp();
const localRev = gitSha || stamp;
let hasUpdate = false;
@@ -139,47 +327,90 @@ export async function checkUpdate() {
} else if (remoteVer && localVer && remoteVer !== localVer) {
hasUpdate = true;
} else if (remoteSha && !localRev) {
writeStamp(remoteSha);
hasUpdate = false;
// zip / dsh 安装没有 stamp,按有更新处理,拉一次与 master 对齐。
hasUpdate = true;
}
return {
const result = {
ok: true,
hasUpdate,
localVersion: localVer,
remoteVersion: remoteVer || localVer,
localSha: localRev ? localRev.slice(0, 7) : "",
remoteSha: remoteSha ? remoteSha.slice(0, 7) : "",
via: gitSha ? "git" : "zip",
via: detectVia(),
};
rememberUpdate(result);
return result;
}
function gitPull() {
execFileSync("git", ["-C", PLUGIN_ROOT, "pull", "--ff-only", "origin", BRANCH], {
function gitTrackedDirty(dir) {
try {
const out = execFileSync(
"git",
["-C", dir, "status", "--porcelain", "--untracked-files=no", "--", ...COPY_NAMES],
HIDDEN,
).trim();
return Boolean(out);
} catch {
return true;
}
}
let lastUpdate = null;
function rememberUpdate(result) {
lastUpdate = result && typeof result === "object" ? result : lastUpdate;
return lastUpdate;
}
export function lastUpdateResult() {
return lastUpdate;
}
function gitPull(dir) {
execFileSync("git", ["-C", dir, "pull", "--ff-only", "origin", BRANCH], {
...HIDDEN,
timeout: 60000,
});
}
async function installFromZip() {
function extractZip(zip, dest) {
try {
execFileSync("tar", ["-xf", zip, "-C", dest], { ...HIDDEN, timeout: 60000 });
return;
} catch {
// Windows 10+ 自带 tar;没有或失败时改 PowerShell。
}
execFileSync(
"powershell",
["-NoProfile", "-Command", "Expand-Archive -LiteralPath $env:DSH_UPD_ZIP -DestinationPath $env:DSH_UPD_DIR -Force"],
{
...HIDDEN,
timeout: 60000,
env: { ...process.env, DSH_UPD_ZIP: zip, DSH_UPD_DIR: dest },
},
);
}
async function overlayFromZip(dests) {
const unique = [...new Set(dests.filter(Boolean).map((d) => realPath(d)))];
if (!unique.length) return;
const tmp = await fsp.mkdtemp(path.join(os.tmpdir(), "dsh-purge-upd-"));
const zip = path.join(tmp, "master.zip");
const res = await fetch(`https://github.com/${REPO}/archive/refs/heads/${BRANCH}.zip`, {
headers: { "user-agent": "dsh-purge-update" },
redirect: "follow",
});
if (!res.ok) throw new Error(`zip http ${res.status}`);
const res = await fetchRes(ZIP_URL, 45000);
await fsp.writeFile(zip, Buffer.from(await res.arrayBuffer()));
execFileSync("tar", ["-xf", zip, "-C", tmp], { ...HIDDEN, timeout: 60000 });
extractZip(zip, tmp);
const names = await fsp.readdir(tmp);
const unpacked = names
.map((n) => path.join(tmp, n))
.find((p) => fs.existsSync(path.join(p, "package.json")));
if (!unpacked) throw new Error("zip 里没有 package.json");
for (const name of COPY_NAMES) {
const from = path.join(unpacked, name);
if (!fs.existsSync(from)) continue;
const to = path.join(PLUGIN_ROOT, name);
await fsp.cp(from, to, { recursive: true, force: true });
for (const dest of unique) {
for (const name of COPY_NAMES) {
const from = path.join(unpacked, name);
if (!fs.existsSync(from)) continue;
await fsp.cp(from, path.join(dest, name), { recursive: true, force: true });
}
}
try {
await fsp.rm(tmp, { recursive: true, force: true });
@@ -188,12 +419,35 @@ async function installFromZip() {
}
}
export async function applyUpdate() {
if (isGitCheckout(PLUGIN_ROOT)) gitPull();
else await installFromZip();
const sha = (await remoteHeadSha()) || gitHead(PLUGIN_ROOT);
export async function applyUpdate(jobs = planUpdates()) {
const zipDirs = [];
const vias = new Set();
for (const job of jobs) {
if (job.kind === "git") {
gitPull(job.dir);
vias.add("git");
continue;
}
if (job.kind === "dsh") {
try {
dshReinstall(job.profile, job.spec);
vias.add("dsh");
continue;
} catch {
zipDirs.push(job.dir);
}
} else {
zipDirs.push(job.dir);
}
}
if (zipDirs.length) {
await overlayFromZip(zipDirs);
vias.add("zip");
}
const sha = (await remoteHeadSha()) || (gitOk() ? gitHead(PLUGIN_ROOT) : "");
if (sha) writeStamp(sha);
return {
const via = vias.size > 1 ? "mixed" : [...vias][0] || detectVia();
return rememberUpdate({
ok: true,
applied: true,
hasUpdate: false,
@@ -202,5 +456,33 @@ export async function applyUpdate() {
localSha: sha ? String(sha).slice(0, 7) : "",
remoteSha: sha ? String(sha).slice(0, 7) : "",
needRestart: true,
};
via,
});
}
export async function autoUpdateIfNeeded() {
try {
const check = await checkUpdate();
if (!check.hasUpdate) return rememberUpdate({ ...check, auto: true, skipped: "latest" });
const jobs = planUpdates();
const dirtyGit = jobs.filter((j) => j.kind === "git" && gitTrackedDirty(j.dir));
const runnable = jobs.filter((j) => !(j.kind === "git" && gitTrackedDirty(j.dir)));
if (!runnable.length && dirtyGit.length) {
return rememberUpdate({
...check,
auto: true,
skipped: "dirty",
error: "本地插件文件有未提交改动,未自动覆盖",
});
}
const applied = await applyUpdate(runnable);
return rememberUpdate({ ...applied, auto: true });
} catch (e) {
return rememberUpdate({
ok: false,
auto: true,
hasUpdate: false,
error: String(e && e.message ? e.message : e),
});
}
}