mirror of
https://github.com/YuJunZhiXue/dsh-purge.git
synced 2026-11-28 10:10:22 +08:00
fix: 发布 1.1.30,切换版本改为自行下载,并去掉提示词死循环
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
df25a90b0d
commit
181fe141e3
5 files changed
+403
-271
No files matched your search
+172
-48
@@ -1,6 +1,8 @@
|
||||
import { execFileSync, spawnSync } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import { promises as fsp } from "node:fs";
|
||||
import http from "node:http";
|
||||
import https from "node:https";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
@@ -62,6 +64,33 @@ function stampPath() {
|
||||
return path.join(findDshHome(), "dsh-purge", "installed-rev");
|
||||
}
|
||||
|
||||
function autoUpdateGuardPath() {
|
||||
return path.join(findDshHome(), "dsh-purge", "auto-update-guard.json");
|
||||
}
|
||||
|
||||
function autoUpdateGuardBlocks(ref) {
|
||||
try {
|
||||
const raw = JSON.parse(fs.readFileSync(autoUpdateGuardPath(), "utf8"));
|
||||
const at = Date.parse(String(raw?.at || "")) || 0;
|
||||
if (!at || Date.now() - at > 15 * 60 * 1000) return false;
|
||||
const target = String(raw?.ref || "");
|
||||
if (target && ref && target !== String(ref)) return false;
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function markAutoUpdateGuard(ref, sha = "") {
|
||||
const fp = autoUpdateGuardPath();
|
||||
fs.mkdirSync(path.dirname(fp), { recursive: true });
|
||||
fs.writeFileSync(fp, `${JSON.stringify({
|
||||
ref: String(ref || ""),
|
||||
sha: String(sha || ""),
|
||||
at: new Date().toISOString(),
|
||||
}, null, 2)}\n`, "utf8");
|
||||
}
|
||||
|
||||
export function normalizeChannel(value) {
|
||||
return String(value || "").toLowerCase() === "beta" ? "beta" : "stable";
|
||||
}
|
||||
@@ -363,6 +392,32 @@ function dshReinstall(profile, spec, ref = currentChannelRef()) {
|
||||
}
|
||||
}
|
||||
|
||||
/** 把 profile 里的安装地址改成 codeload。github.com/archive 会 302,pnpm 的 fetch 接着失败。 */
|
||||
function pinInstalledSpec(profileDir, ref) {
|
||||
if (!profileDir) return;
|
||||
const url = archiveTarballUrl(ref);
|
||||
const pkgPath = path.join(profileDir, "package.json");
|
||||
const pkg = readJson(pkgPath);
|
||||
if (pkg) {
|
||||
let changed = false;
|
||||
for (const key of ["dependencies", "devDependencies", "optionalDependencies"]) {
|
||||
if (pkg[key] && Object.prototype.hasOwnProperty.call(pkg[key], "dsh-purge") && pkg[key]["dsh-purge"] !== url) {
|
||||
pkg[key]["dsh-purge"] = url;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (changed) fs.writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}\n`, "utf8");
|
||||
}
|
||||
const lockPath = path.join(profileDir, "pnpm-lock.yaml");
|
||||
if (!fs.existsSync(lockPath)) return;
|
||||
const text = fs.readFileSync(lockPath, "utf8");
|
||||
const next = text.replace(
|
||||
/(^|\n)([ \t]*dsh-purge:\r?\n[ \t]+specifier:[ \t]*)\S+([ \t]*\r?\n[ \t]+version:[ \t]*)\S+/g,
|
||||
`$1$2${url}$3${url}`,
|
||||
);
|
||||
if (next !== text) fs.writeFileSync(lockPath, next, "utf8");
|
||||
}
|
||||
|
||||
function planUpdates() {
|
||||
const profiles = findPurgeProfiles();
|
||||
const jobs = [];
|
||||
@@ -382,7 +437,7 @@ function planUpdates() {
|
||||
continue;
|
||||
}
|
||||
const dir = profilePluginDir(p.dir) || PLUGIN_ROOT;
|
||||
jobs.push({ kind: "dsh", profile: p.name, spec: p.spec, dir });
|
||||
jobs.push({ kind: "dsh", profile: p.name, spec: p.spec, dir, profileDir: p.dir });
|
||||
remember(dir);
|
||||
}
|
||||
|
||||
@@ -408,43 +463,95 @@ function detectVia() {
|
||||
|
||||
function isAbortError(e) {
|
||||
const msg = String((e && e.message) || e || "");
|
||||
return (e && (e.name === "AbortError" || e.name === "TimeoutError")) || /aborted|abort/i.test(msg);
|
||||
return (e && (e.name === "AbortError" || e.name === "TimeoutError")) || /aborted|abort|超时/i.test(msg);
|
||||
}
|
||||
|
||||
function rewriteDownloadUrl(url) {
|
||||
const value = String(url || "");
|
||||
let match = value.match(/^https:\/\/github\.com\/([^/]+\/[^/]+)\/archive\/refs\/(tags|heads)\/(.+)\.(zip|tar\.gz)$/i);
|
||||
if (match) {
|
||||
const kind = match[4].toLowerCase() === "zip" ? "zip" : "tar.gz";
|
||||
return `https://codeload.github.com/${match[1]}/${kind}/refs/${match[2]}/${decodeURIComponent(match[3])}`;
|
||||
}
|
||||
match = value.match(/^https:\/\/github\.com\/([^/]+\/[^/]+)\/archive\/([0-9a-f]{7,40})\.(zip|tar\.gz)$/i);
|
||||
if (match) {
|
||||
const kind = match[3].toLowerCase() === "zip" ? "zip" : "tar.gz";
|
||||
return `https://codeload.github.com/${match[1]}/${kind}/${match[2]}`;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function requestBuffer(url, ms, headers, redirectsLeft = 5) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = new URL(url);
|
||||
} catch (e) {
|
||||
reject(e);
|
||||
return;
|
||||
}
|
||||
const lib = parsed.protocol === "http:" ? http : https;
|
||||
const req = lib.request(parsed, {
|
||||
method: "GET",
|
||||
headers: { "user-agent": "dsh-purge-update", accept: "*/*", ...headers },
|
||||
}, (res) => {
|
||||
const status = res.statusCode || 0;
|
||||
if ([301, 302, 303, 307, 308].includes(status)) {
|
||||
res.resume();
|
||||
if (redirectsLeft <= 0) {
|
||||
reject(new Error("http redirect loop"));
|
||||
return;
|
||||
}
|
||||
const loc = Array.isArray(res.headers.location) ? res.headers.location[0] : res.headers.location;
|
||||
const next = loc ? new URL(loc, url).href : rewriteDownloadUrl(url);
|
||||
if (!next || next === url) {
|
||||
reject(new Error(`http ${status}`));
|
||||
return;
|
||||
}
|
||||
requestBuffer(next, ms, headers, redirectsLeft - 1).then(resolve, reject);
|
||||
return;
|
||||
}
|
||||
if (status < 200 || status >= 300) {
|
||||
res.resume();
|
||||
const rewritten = rewriteDownloadUrl(url);
|
||||
if (rewritten && rewritten !== url && redirectsLeft > 0) {
|
||||
requestBuffer(rewritten, ms, headers, redirectsLeft - 1).then(resolve, reject);
|
||||
return;
|
||||
}
|
||||
reject(new Error(`http ${status}`));
|
||||
return;
|
||||
}
|
||||
const chunks = [];
|
||||
res.on("data", (chunk) => chunks.push(chunk));
|
||||
res.on("end", () => resolve({ status, body: Buffer.concat(chunks) }));
|
||||
res.on("error", reject);
|
||||
});
|
||||
req.on("error", reject);
|
||||
req.setTimeout(ms, () => {
|
||||
req.destroy(new Error("GitHub 超时"));
|
||||
});
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
async function fetchRes(url, ms = 20000, headers = {}) {
|
||||
const ctrl = new AbortController();
|
||||
const timer = setTimeout(() => {
|
||||
try {
|
||||
ctrl.abort("timeout");
|
||||
} catch {
|
||||
ctrl.abort();
|
||||
}
|
||||
}, ms);
|
||||
const started = rewriteDownloadUrl(url) || url;
|
||||
try {
|
||||
let current = String(url || "");
|
||||
for (let hop = 0; hop < 6; hop += 1) {
|
||||
const res = await fetch(current, {
|
||||
headers: { "user-agent": "dsh-purge-update", accept: "*/*", ...headers },
|
||||
// 手动跟跳转:部分宿主对 github.com → codeload 跨域 302 不会自动 follow,会直接抛 http 302。
|
||||
redirect: "manual",
|
||||
cache: "no-store",
|
||||
signal: ctrl.signal,
|
||||
});
|
||||
if ([301, 302, 303, 307, 308].includes(res.status)) {
|
||||
const loc = res.headers.get("location");
|
||||
if (!loc) throw new Error(`http ${res.status}`);
|
||||
current = new URL(loc, current).href;
|
||||
continue;
|
||||
}
|
||||
if (!res.ok) throw new Error(`http ${res.status}`);
|
||||
return res;
|
||||
}
|
||||
throw new Error("http redirect loop");
|
||||
const result = await requestBuffer(started, ms, headers);
|
||||
return {
|
||||
ok: true,
|
||||
status: result.status,
|
||||
async text() {
|
||||
return result.body.toString("utf8");
|
||||
},
|
||||
async arrayBuffer() {
|
||||
const copy = Buffer.from(result.body);
|
||||
return copy.buffer.slice(copy.byteOffset, copy.byteOffset + copy.byteLength);
|
||||
},
|
||||
};
|
||||
} catch (e) {
|
||||
if (isAbortError(e)) throw new Error("GitHub 超时");
|
||||
if (isAbortError(e) || /GitHub 超时/.test(String(e && e.message))) throw new Error("GitHub 超时");
|
||||
throw e;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -541,7 +648,7 @@ export function markCurrent(versions, state, localVer, localSha) {
|
||||
&& String(item.version || "").replace(/^v/i, "") === ver
|
||||
));
|
||||
return rows.map((item) => {
|
||||
const shaHit = Boolean(localSha && item.sha && sameRev(localSha, item.sha));
|
||||
const shaHit = Boolean(!pin && localSha && item.sha && sameRev(localSha, item.sha));
|
||||
const pinHit = Boolean(pin && item.ref === pin);
|
||||
// 提交号对不上时,只把本通道里和本机版本号相同的那一条标成当前。
|
||||
const headHit = Boolean(
|
||||
@@ -555,7 +662,7 @@ export function markCurrent(versions, state, localVer, localSha) {
|
||||
return {
|
||||
...item,
|
||||
shaShort: item.shaShort || (item.sha ? String(item.sha).slice(0, 7) : ""),
|
||||
current: shaHit || pinHit || headHit,
|
||||
current: pinHit || shaHit || headHit,
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -714,9 +821,10 @@ function describeLane(id, listed, state, localVer, localRev) {
|
||||
let hasUpdate = false;
|
||||
if (onLane && state.pin) {
|
||||
hasUpdate = Boolean(sha && localRev && !sameRev(localRev, sha));
|
||||
} else if (onLane && sha && localRev) {
|
||||
hasUpdate = !sameRev(localRev, sha) || versionIsNewer(version, localVer);
|
||||
} else if (onLane && versionIsNewer(version, localVer)) {
|
||||
// 只跟版本号。提交号对不上就再 add --force,会在 dsh 杀掉宿主后形成无限重启。
|
||||
hasUpdate = true;
|
||||
} else if (onLane && !localVer && sha && localRev && !sameRev(localRev, sha)) {
|
||||
hasUpdate = true;
|
||||
}
|
||||
return {
|
||||
@@ -953,7 +1061,10 @@ export async function applyUpdate(jobs = planUpdates(), options = {}) {
|
||||
const ref = safeUpdateRef(options.ref || currentChannelRef(state) || STABLE_REF);
|
||||
if (!ref) throw new Error("未知版本");
|
||||
const force = options.force !== false;
|
||||
const pin = options.pin === false ? "" : (options.pin || state.pin || "");
|
||||
const channel = normalizeChannel(options.channel || state.channel);
|
||||
const zipDirs = [];
|
||||
const specProfiles = [];
|
||||
const vias = new Set();
|
||||
for (const job of jobs) {
|
||||
if (job.kind === "git") {
|
||||
@@ -968,26 +1079,23 @@ export async function applyUpdate(jobs = planUpdates(), options = {}) {
|
||||
continue;
|
||||
}
|
||||
if (job.kind === "dsh") {
|
||||
try {
|
||||
dshReinstall(job.profile, job.spec, ref);
|
||||
vias.add("dsh");
|
||||
continue;
|
||||
} catch {
|
||||
zipDirs.push(job.dir);
|
||||
}
|
||||
} else {
|
||||
zipDirs.push(job.dir);
|
||||
// exe 和 web 都走 dsh plugin add → pnpm。pnpm 拉 GitHub 包会 302 或 fetch failed,
|
||||
// 而且 add --force 会先杀掉宿主。这里改为自己下载再覆盖。
|
||||
if (job.dir) zipDirs.push(job.dir);
|
||||
if (job.profileDir) specProfiles.push(job.profileDir);
|
||||
continue;
|
||||
}
|
||||
zipDirs.push(job.dir);
|
||||
}
|
||||
if (zipDirs.length) {
|
||||
await overlayFromZip(zipDirs, ref);
|
||||
vias.add("zip");
|
||||
}
|
||||
for (const dir of specProfiles) pinInstalledSpec(dir, ref);
|
||||
const sha = (gitOk() ? gitHead(PLUGIN_ROOT) : "") || (await remoteHeadSha(ref).catch(() => ""));
|
||||
if (sha) markAutoUpdateGuard(ref, sha);
|
||||
if (sha) writeStamp(sha);
|
||||
const via = vias.size > 1 ? "mixed" : [...vias][0] || detectVia();
|
||||
const pin = options.pin === false ? "" : (options.pin || state.pin || "");
|
||||
const channel = normalizeChannel(options.channel || state.channel);
|
||||
const saved = writeChannelState({ channel, pin });
|
||||
const localVer = localVersion();
|
||||
pushHistory({
|
||||
@@ -1103,10 +1211,25 @@ export async function autoUpdateIfNeeded() {
|
||||
try {
|
||||
const check = await checkUpdate();
|
||||
if (check.pinned) return rememberUpdate({ ...check, auto: true, skipped: "pinned" });
|
||||
const lane = check.lanes?.[check.channel] || check.lanes?.stable || {};
|
||||
const remoteVer = String(lane.version || "").replace(/^v/i, "");
|
||||
const localVer = String(check.localVersion || "").replace(/^v/i, "");
|
||||
if (!versionIsNewer(remoteVer, localVer)) {
|
||||
return rememberUpdate({ ...check, auto: true, hasUpdate: false, skipped: "latest" });
|
||||
}
|
||||
if (!check.hasUpdate) return rememberUpdate({ ...check, auto: true, skipped: "latest" });
|
||||
if (check.updateTarget === BETA_REF && readChannelState().channel !== "beta") {
|
||||
return rememberUpdate({ ...check, auto: true, skipped: "beta" });
|
||||
}
|
||||
const target = currentChannelRef();
|
||||
if (autoUpdateGuardBlocks(target)) {
|
||||
return rememberUpdate({
|
||||
...check,
|
||||
auto: true,
|
||||
skipped: "cooldown",
|
||||
error: "刚刚更新过,跳过本轮以免重启循环",
|
||||
});
|
||||
}
|
||||
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)));
|
||||
@@ -1119,10 +1242,11 @@ export async function autoUpdateIfNeeded() {
|
||||
});
|
||||
}
|
||||
const applied = await applyUpdate(runnable, {
|
||||
ref: currentChannelRef(),
|
||||
ref: target,
|
||||
channel: readChannelState().channel,
|
||||
pin: false,
|
||||
force: false,
|
||||
auto: true,
|
||||
});
|
||||
return rememberUpdate({ ...applied, auto: true });
|
||||
} catch (e) {
|
||||
|
||||
Reference in new issue
Block a user