mirror of
https://github.com/YuJunZhiXue/dsh-purge.git
synced 2026-11-28 08:10:22 +08:00
feat: 设置页可卸载,AI 安装说明只跑官方 add
This commit is contained in:
1 parent
bea3877f4d
commit
fbd17e277e
13 files changed
+810
-124
No files matched your search
+135
@@ -10,6 +10,7 @@ import {
|
||||
installHideConsole,
|
||||
installHideConsoleIntoBin,
|
||||
resolveDshBinRoot,
|
||||
revertHideConsoleFromBin,
|
||||
} from "./hide-console.js";
|
||||
|
||||
const isWindows = process.platform === "win32";
|
||||
@@ -334,6 +335,140 @@ export function silenceCmdFlash(aiBase = findAiBase()) {
|
||||
};
|
||||
}
|
||||
|
||||
function rewriteFiles(files, rewrite) {
|
||||
let hit = "missing";
|
||||
for (const fp of files) {
|
||||
let text;
|
||||
try {
|
||||
text = fs.readFileSync(fp, "utf8");
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
const next = rewrite(text);
|
||||
if (next == null || next === text) {
|
||||
if (hit === "missing") hit = "absent";
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
fs.writeFileSync(fp, next, "utf8");
|
||||
hit = "reverted";
|
||||
} catch (e) {
|
||||
hit = `error:${e}`;
|
||||
}
|
||||
}
|
||||
return hit;
|
||||
}
|
||||
|
||||
export function revertCmdFlash(aiBase = findAiBase(), dshHome = findDshHome()) {
|
||||
const hide = revertHideConsoleFromBin(aiBase);
|
||||
const subprocess = rewriteFiles(listSubprocessLocalFiles(dshHome), (text) => {
|
||||
const marker = "[dsh-purge] subprocess-local windowsHide";
|
||||
if (!text.includes(marker)) return text;
|
||||
return text
|
||||
.replace(/\n\t\t\/\/ \[dsh-purge\] subprocess-local windowsHide\n\t\twindowsHide: true/, "")
|
||||
.replace(",\n\t\t// [dsh-purge] subprocess-local windowsHide\n\t\twindowsHide: true", "");
|
||||
});
|
||||
const customBash = rewriteFiles(listLiangshenCustomBashFiles(dshHome), (text) => {
|
||||
const marker = "[dsh-purge] never fall back to WSL System32 bash";
|
||||
if (!text.includes(marker)) return text;
|
||||
const needle =
|
||||
" try {\n" +
|
||||
" return await ctx.subprocess.resolveExecutable('bash', undefined, signal)\n" +
|
||||
" } catch (error) {\n";
|
||||
const replacement =
|
||||
" // " +
|
||||
marker +
|
||||
"\n" +
|
||||
" try {\n" +
|
||||
" const resolved = await ctx.subprocess.resolveExecutable('bash', undefined, signal)\n" +
|
||||
" if (/[\\\\/](System32|SysWOW64|WindowsApps)[\\\\/]bash\\.exe$/i.test(resolved)) {\n" +
|
||||
" throw new Error('WSL bash launcher is not Git Bash')\n" +
|
||||
" }\n" +
|
||||
" return resolved\n" +
|
||||
" } catch (error) {\n";
|
||||
return text.includes(replacement) ? text.replace(replacement, needle) : text;
|
||||
});
|
||||
const phase1 = rewriteFiles(listLiangshenBootstrapFiles(dshHome), (text) => {
|
||||
if (!text.includes("[dsh-purge]") && !text.includes("dsh-purge:")) return text;
|
||||
let next = text.replace(/\r\n/g, "\n");
|
||||
const origSet = "const PERSONA_SECTION_NAMES = new Set(['deployment:persona', 'persona'])";
|
||||
next = next.replace(
|
||||
/const PERSONA_SECTION_NAMES = new Set\(\[[^\]]*dsh-purge[^\]]*\]\)/,
|
||||
origSet,
|
||||
);
|
||||
const officialFilter =
|
||||
" const sections = Array.isArray(assembled.sections)\n" +
|
||||
" ? assembled.sections.filter(section => PERSONA_SECTION_NAMES.has(section?.name))\n" +
|
||||
" : undefined";
|
||||
const wideFilter =
|
||||
" const sections = Array.isArray(assembled.sections)\n" +
|
||||
' ? assembled.sections.filter(section => PERSONA_SECTION_NAMES.has(section?.name) || String(section?.name || "").startsWith("dsh-purge"))\n' +
|
||||
" : undefined";
|
||||
next = next.replace(wideFilter, officialFilter);
|
||||
next = next.replace(/\n \/\/ \[dsh-purge\] phase-1 keep persona\+inject sections/g, "");
|
||||
next = next.replace(/\n \/\/ \[dsh-purge\] phase-1 keep full system-prompt sections/g, "");
|
||||
return next;
|
||||
});
|
||||
const doctorSpawn = rewriteFiles(listDoctorCliFiles(dshHome), (text) => {
|
||||
if (!text.includes("[dsh-purge]")) return text;
|
||||
let next = text;
|
||||
const spawnNeedle = 'import { spawn } from "node:child_process";';
|
||||
next = next.replace(
|
||||
/import \{ spawn as __dshPurgeSpawnOrig \} from "node:child_process";\n\/\/ \[dsh-purge\] doctor spawn windowsHide\nfunction spawn\(file, args, options\) \{[\s\S]*?\n\}\n/,
|
||||
spawnNeedle + "\n",
|
||||
);
|
||||
const specNeedle =
|
||||
'function dshSpawnSpec(binary, args, platform = process.platform) {\n' +
|
||||
'\tif (platform === "win32") {\n' +
|
||||
'\t\tif (binary.toLowerCase().endsWith(".cmd") || binary.toLowerCase().endsWith(".bat")) return {\n' +
|
||||
'\t\t\tcommand: "cmd.exe",\n' +
|
||||
'\t\t\targs: windowsCmdShimArgs(binary, args),\n' +
|
||||
'\t\t\twindowsVerbatimArguments: true\n' +
|
||||
'\t\t};';
|
||||
if (next.includes("[dsh-purge] dsh.cmd → node bin.js (no cmd.exe)")) {
|
||||
next = next.replace(
|
||||
/function dshSpawnSpec\(binary, args, platform = process\.platform\) \{\n\tif \(platform === "win32"\) \{\n\t\tif \(binary\.toLowerCase\(\)\.endsWith\("\.cmd"\) \|\| binary\.toLowerCase\(\)\.endsWith\("\.bat"\)\) \{[\s\S]*?\t\t\}/,
|
||||
specNeedle,
|
||||
);
|
||||
}
|
||||
const stdioNeedle =
|
||||
'const child = spawnDsh(realDsh, options.argv, {\n' +
|
||||
'\t\tstdio: [\n' +
|
||||
'\t\t\t"inherit",\n' +
|
||||
'\t\t\t"inherit",\n' +
|
||||
'\t\t\t"pipe"\n' +
|
||||
'\t\t],';
|
||||
if (next.includes("[dsh-purge] doctor launch stdio no-inherit")) {
|
||||
next = next.replace(
|
||||
/const child = spawnDsh\(realDsh, options\.argv, \{\n\t\t\/\/ \[dsh-purge\] doctor launch stdio no-inherit\n\t\tstdio: \[\n\t\t\t"ignore",\n\t\t\t"ignore",\n\t\t\t"pipe"\n\t\t\],\n\t\twindowsHide: true,/,
|
||||
stdioNeedle,
|
||||
);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
const market = rewriteFiles(listDshmarketRestartFiles(dshHome), (text) => {
|
||||
const marker = "[dsh-purge] market restart → node bin.js (no powershell/dsh.cmd)";
|
||||
if (!text.includes(marker)) return text;
|
||||
const needle =
|
||||
"export function respawnInvocation(launch, platform = process.platform) {\n" +
|
||||
" if (platform !== 'win32') {\n" +
|
||||
" return { file: launch.file, args: launch.args, viaShell: launch.viaShell, detached: true };\n" +
|
||||
" }\n";
|
||||
let next = text.replace(
|
||||
/export function respawnInvocation\(launch, platform = process\.platform\) \{\n if \(platform !== 'win32'\) \{\n return \{ file: launch\.file, args: launch\.args, viaShell: launch\.viaShell, detached: true \};\n \}\n \/\/ \[dsh-purge\] market restart[^\n]*\n \{[\s\S]*?\n \}\n/,
|
||||
needle,
|
||||
);
|
||||
const importNeedle = "import { tmpdir } from 'node:os';\nimport { join } from 'node:path';";
|
||||
const importReplacement =
|
||||
"import { existsSync } from 'node:fs';\n" +
|
||||
"import { tmpdir } from 'node:os';\n" +
|
||||
"import { dirname, join } from 'node:path';";
|
||||
if (next.includes(importReplacement)) next = next.replace(importReplacement, importNeedle);
|
||||
return next;
|
||||
});
|
||||
return { hide, subprocess, customBash, phase1, doctorSpawn, market };
|
||||
}
|
||||
|
||||
export function silenceSubprocessLocalFlash(dshHome = findDshHome()) {
|
||||
if (process.platform !== "win32") return "skipped_not_win32";
|
||||
const marker = "[dsh-purge] subprocess-local windowsHide";
|
||||
|
||||
@@ -239,4 +239,38 @@ export function installHideConsoleIntoBin(aiBase, { fs, path: nodePath } = {}) {
|
||||
return "injected";
|
||||
}
|
||||
|
||||
export function revertHideConsoleFromBin(aiBase, { fs, path: nodePath } = {}) {
|
||||
const nodeFs = fs ?? requireFs();
|
||||
const p = nodePath ?? requirePath();
|
||||
const root = resolveDshBinRoot(aiBase, { fs: nodeFs, path: p });
|
||||
if (!root) return "missing_bin";
|
||||
const binJs = p.join(root, "lib", "bin.js");
|
||||
const side = p.join(root, "lib", `${IMPORT_MARK}.js`);
|
||||
const facadeSide = p.join(root, "lib", "dsh-purge-child-process-hide.mjs");
|
||||
let changed = false;
|
||||
if (nodeFs.existsSync(binJs)) {
|
||||
try {
|
||||
const text = nodeFs.readFileSync(binJs, "utf8");
|
||||
const next = text.replace(/^import "\.\/dsh-purge-hide-console\.js";.*\r?\n/gm, "");
|
||||
if (next !== text) {
|
||||
nodeFs.writeFileSync(binJs, next, "utf8");
|
||||
changed = true;
|
||||
}
|
||||
} catch (e) {
|
||||
return `error:${e}`;
|
||||
}
|
||||
}
|
||||
for (const fp of [side, facadeSide]) {
|
||||
try {
|
||||
if (nodeFs.existsSync(fp)) {
|
||||
nodeFs.unlinkSync(fp);
|
||||
changed = true;
|
||||
}
|
||||
} catch {
|
||||
// 重启后再删
|
||||
}
|
||||
}
|
||||
return changed ? "reverted" : "absent";
|
||||
}
|
||||
|
||||
installHideConsole();
|
||||
+45
-2
@@ -15,6 +15,7 @@ import {
|
||||
shouldInjectPrompt,
|
||||
} from "./identity.js";
|
||||
import * as rewind from "./rewind.js";
|
||||
import * as uninstaller from "./uninstall.js";
|
||||
|
||||
export const name = "dsh-purge";
|
||||
|
||||
@@ -348,6 +349,23 @@ async function handlePurgeCommand(rawInput, config) {
|
||||
lines.push("注: prompt-inject.md 保留(用户文件)/ prompt-inject.md kept (user file)");
|
||||
return { kind: "success", text: lines.join("\n") };
|
||||
}
|
||||
case "uninstall":
|
||||
case "remove": {
|
||||
const result = await uninstaller.uninstallPurge();
|
||||
const lines = [];
|
||||
if (result.applied) lines.push("已检测到补丁,已还原回原版。");
|
||||
else lines.push("未检测到已应用补丁,仍会清除插件文件。");
|
||||
if (result.patches) {
|
||||
lines.push(` 还原文件 ${result.patches.reverted?.length || 0} 个`);
|
||||
}
|
||||
if (result.override?.removed) lines.push(` 已删除 ${result.override.path}`);
|
||||
if (result.stripped?.length) lines.push(` 已从 profile 移除: ${result.stripped.join(", ")}`);
|
||||
if (result.errors?.length) {
|
||||
for (const e of result.errors) lines.push(` ⚠ ${e}`);
|
||||
}
|
||||
lines.push("", "请重启 dsh。重启后插件不再加载。");
|
||||
return { kind: result.ok ? "success" : "error", text: lines.join("\n") };
|
||||
}
|
||||
case "edit":
|
||||
case "e": {
|
||||
const state = await core.gatherState();
|
||||
@@ -374,6 +392,7 @@ async function handlePurgeCommand(rawInput, config) {
|
||||
" /purge status 显示状态\n" +
|
||||
" /purge apply 应用全部清洗(提示词+代码+shim+override)\n" +
|
||||
" /purge revert 回滚还原\n" +
|
||||
" /purge uninstall 卸载插件(已应用则先还原)\n" +
|
||||
" /purge edit 编辑注入文件 prompt-inject.md\n" +
|
||||
" /purge help 显示帮助\n" +
|
||||
"规则集切换见 /rules(list | use <id> | create | delete | reset)",
|
||||
@@ -530,8 +549,8 @@ export function apply(ctx, config) {
|
||||
if (commands) {
|
||||
commands.register({
|
||||
name: "purge",
|
||||
description: "dsh 指令权威性清洗(status/apply/revert/edit/help)",
|
||||
input: { hint: "status | apply | revert | edit | help" },
|
||||
description: "dsh 指令权威性清洗(status/apply/revert/uninstall/edit/help)",
|
||||
input: { hint: "status | apply | revert | uninstall | edit | help" },
|
||||
handler: async (invocation) => handlePurgeCommand(invocation.rawInput ?? "", cfg),
|
||||
});
|
||||
commands.register({
|
||||
@@ -941,6 +960,30 @@ function installWebServer(ctx, cfg) {
|
||||
}
|
||||
},
|
||||
}, "dsh-purge: revert");
|
||||
host.webServer.register({
|
||||
kind: "exact",
|
||||
path: "/dsh-purge/uninstall",
|
||||
handler: async (request, response) => {
|
||||
if (request.method !== "POST") {
|
||||
response.writeHead(405, { allow: "POST" });
|
||||
response.end();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await uninstaller.uninstallPurge();
|
||||
sendJson(response, result.ok ? 200 : 500, result);
|
||||
if (result.ok) {
|
||||
uninstaller.scheduleCleanupRestart({
|
||||
request,
|
||||
restartArgv: restartArgv(),
|
||||
cleanup: result.cleanup,
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
sendJson(response, 500, { ok: false, error: String(e && e.message ? e.message : e) });
|
||||
}
|
||||
},
|
||||
}, "dsh-purge: uninstall");
|
||||
host.webServer.register({
|
||||
kind: "exact",
|
||||
path: "/dsh-purge/override",
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import fs from "node:fs";
|
||||
import net from "node:net";
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
const encoded = process.env.DSH_PURGE_RESTART;
|
||||
if (!encoded) process.exit(1);
|
||||
|
||||
let info;
|
||||
try {
|
||||
info = JSON.parse(encoded);
|
||||
} catch {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const port = Number(info.port) || 3080;
|
||||
const host = typeof info.host === "string" && info.host ? info.host : "127.0.0.1";
|
||||
const cleanup = Array.isArray(info.cleanup) ? info.cleanup : [];
|
||||
|
||||
function spawnEnv() {
|
||||
const env = { ...process.env };
|
||||
delete env.DSH_PERMISSION_MODE;
|
||||
delete env.DSH_PURGE_RESTART;
|
||||
return env;
|
||||
}
|
||||
|
||||
function portFree() {
|
||||
return new Promise((resolve) => {
|
||||
const socket = net.createConnection({ host, port }, () => {
|
||||
socket.destroy();
|
||||
resolve(false);
|
||||
});
|
||||
socket.on("error", () => resolve(true));
|
||||
});
|
||||
}
|
||||
|
||||
async function waitFree() {
|
||||
for (let i = 0; i < 80; i++) {
|
||||
if (await portFree()) return true;
|
||||
await new Promise((r) => setTimeout(r, 120));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function rmTree(dir) {
|
||||
if (!dir) return;
|
||||
try {
|
||||
fs.rmSync(dir, { recursive: true, force: true, maxRetries: 8, retryDelay: 120 });
|
||||
} catch {
|
||||
// 锁着就留下
|
||||
}
|
||||
}
|
||||
|
||||
const ok = await waitFree();
|
||||
if (!ok) process.exit(1);
|
||||
|
||||
for (const dir of cleanup) rmTree(dir);
|
||||
if (info.helper) {
|
||||
try {
|
||||
fs.unlinkSync(info.helper);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
const child = spawn(info.execPath, info.argv, {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
cwd: info.cwd || process.cwd(),
|
||||
env: spawnEnv(),
|
||||
windowsHide: true,
|
||||
shell: false,
|
||||
});
|
||||
child.on("error", () => process.exit(1));
|
||||
child.unref();
|
||||
await new Promise((r) => setTimeout(r, 400));
|
||||
process.exit(0);
|
||||
@@ -0,0 +1,294 @@
|
||||
import fs from "node:fs";
|
||||
import { promises as fsp } from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawn } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import * as core from "./core.js";
|
||||
import * as rules from "./rules.js";
|
||||
import * as updater from "./update.js";
|
||||
|
||||
export function wasApplied(state) {
|
||||
if (!state) return false;
|
||||
if (state.has_backup) return true;
|
||||
if (Number(state.patches_applied) > 0) return true;
|
||||
return [state.shim_cmd, state.shim_ps1, state.shim_bin].includes("patched");
|
||||
}
|
||||
|
||||
export function shouldDeletePluginTree(dir, dshHome = core.findDshHome()) {
|
||||
if (!dir) return false;
|
||||
let real;
|
||||
try {
|
||||
real = fs.realpathSync(dir);
|
||||
} catch {
|
||||
real = path.resolve(dir);
|
||||
}
|
||||
const n = real.replace(/[/\\]+/g, "/").toLowerCase();
|
||||
if (n.includes("/node_modules/dsh-purge")) return true;
|
||||
let home;
|
||||
try {
|
||||
home = fs.realpathSync(dshHome);
|
||||
} catch {
|
||||
home = path.resolve(dshHome);
|
||||
}
|
||||
const homeN = home.replace(/[/\\]+/g, "/").toLowerCase();
|
||||
return n.startsWith(`${homeN}/profiles/`);
|
||||
}
|
||||
|
||||
export function stripPluginFromPackage(pkg) {
|
||||
if (!pkg || typeof pkg !== "object") return false;
|
||||
let changed = false;
|
||||
for (const key of ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"]) {
|
||||
if (pkg[key] && Object.prototype.hasOwnProperty.call(pkg[key], "dsh-purge")) {
|
||||
delete pkg[key]["dsh-purge"];
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
for (const key of ["bundles", "plugins"]) {
|
||||
if (!Array.isArray(pkg[key])) continue;
|
||||
const next = pkg[key].filter((item) => {
|
||||
if (typeof item === "string") return item !== "dsh-purge" && !item.startsWith("dsh-purge@");
|
||||
const id = item && (item.id || item.name);
|
||||
return id !== "dsh-purge";
|
||||
});
|
||||
if (next.length !== pkg[key].length) {
|
||||
pkg[key] = next;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
function readJson(fp) {
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(fp, "utf8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function writeJson(fp, value) {
|
||||
fs.writeFileSync(fp, `${JSON.stringify(value, null, 2)}\n`, "utf8");
|
||||
}
|
||||
|
||||
function pkgMentionsPurge(pkg) {
|
||||
if (!pkg) return false;
|
||||
if (pkg.dependencies?.["dsh-purge"] || pkg.devDependencies?.["dsh-purge"]) return true;
|
||||
for (const key of ["bundles", "plugins"]) {
|
||||
if (!Array.isArray(pkg[key])) continue;
|
||||
if (pkg[key].some((item) => {
|
||||
if (typeof item === "string") return item === "dsh-purge" || item.startsWith("dsh-purge@");
|
||||
return item && (item.id === "dsh-purge" || item.name === "dsh-purge");
|
||||
})) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function listInstalledProfiles(dshHome = core.findDshHome()) {
|
||||
const root = path.join(dshHome, "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 pkgPath = path.join(dir, "package.json");
|
||||
const pkg = readJson(pkgPath);
|
||||
const nm = path.join(dir, "node_modules", "dsh-purge");
|
||||
if (!pkgMentionsPurge(pkg) && !fs.existsSync(nm)) continue;
|
||||
const spec = pkg?.dependencies?.["dsh-purge"] || pkg?.devDependencies?.["dsh-purge"] || "";
|
||||
out.push({ name, dir, spec: String(spec || ""), pkgPath, hasModule: fs.existsSync(nm) });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
async function unlinkIfExists(fp) {
|
||||
try {
|
||||
await fsp.unlink(fp);
|
||||
return true;
|
||||
} catch (e) {
|
||||
if (e && e.code === "ENOENT") return false;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
async function rmIfExists(fp) {
|
||||
try {
|
||||
await fsp.rm(fp, { recursive: true, force: true });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function removeOverride(dshHome) {
|
||||
const fp = core.findOverrideFile(dshHome);
|
||||
const ok = await unlinkIfExists(fp);
|
||||
return { path: fp, removed: ok };
|
||||
}
|
||||
|
||||
async function resetRules(dshHome) {
|
||||
const reset = await rules.resetToOriginal(dshHome);
|
||||
const dir = rules.rulesDir(dshHome);
|
||||
const removedDir = await rmIfExists(dir);
|
||||
return { ...reset, rules_dir: dir, rules_dir_removed: removedDir };
|
||||
}
|
||||
|
||||
function collectCleanupDirs(profiles, dshHome) {
|
||||
const seen = new Set();
|
||||
const cleanup = [];
|
||||
const remember = (dir) => {
|
||||
if (!dir) return;
|
||||
let real;
|
||||
try {
|
||||
real = fs.realpathSync(dir);
|
||||
} catch {
|
||||
real = path.resolve(dir);
|
||||
}
|
||||
const key = real.toLowerCase();
|
||||
if (seen.has(key)) return;
|
||||
seen.add(key);
|
||||
cleanup.push(real);
|
||||
};
|
||||
|
||||
for (const p of profiles) {
|
||||
const nm = path.join(p.dir, "node_modules", "dsh-purge");
|
||||
if (!fs.existsSync(nm)) continue;
|
||||
let real;
|
||||
try {
|
||||
real = fs.realpathSync(nm);
|
||||
} catch {
|
||||
real = path.resolve(nm);
|
||||
}
|
||||
if (shouldDeletePluginTree(real, dshHome)) remember(real);
|
||||
if (path.resolve(nm).toLowerCase() !== real.toLowerCase()) remember(nm);
|
||||
}
|
||||
|
||||
const dataDir = path.join(dshHome, "dsh-purge");
|
||||
remember(dataDir);
|
||||
|
||||
const root = updater.pluginRoot();
|
||||
if (shouldDeletePluginTree(root, dshHome)) remember(root);
|
||||
|
||||
return cleanup;
|
||||
}
|
||||
|
||||
function unregisterProfiles(profiles) {
|
||||
const stripped = [];
|
||||
const errors = [];
|
||||
for (const p of profiles) {
|
||||
try {
|
||||
const pkg = readJson(p.pkgPath) || {};
|
||||
if (stripPluginFromPackage(pkg)) {
|
||||
writeJson(p.pkgPath, pkg);
|
||||
stripped.push(p.name);
|
||||
}
|
||||
} catch (e) {
|
||||
errors.push({ profile: p.name, error: String(e && e.message ? e.message : e) });
|
||||
}
|
||||
}
|
||||
return { stripped, errors };
|
||||
}
|
||||
|
||||
export async function uninstallPurge() {
|
||||
const state = await core.gatherState();
|
||||
const applied = wasApplied(state);
|
||||
const dshHome = state.dsh_home || core.findDshHome();
|
||||
const report = {
|
||||
ok: true,
|
||||
applied,
|
||||
reverted: false,
|
||||
needRestart: true,
|
||||
patches: null,
|
||||
shim: null,
|
||||
flash: null,
|
||||
override: null,
|
||||
rules: null,
|
||||
profiles: [],
|
||||
cleanup: [],
|
||||
errors: [],
|
||||
};
|
||||
|
||||
try {
|
||||
if (state.ai_base) {
|
||||
report.patches = await core.revertAll(state.ai_base);
|
||||
if (applied) report.reverted = true;
|
||||
}
|
||||
} catch (e) {
|
||||
report.errors.push(`revert patches: ${e.message || e}`);
|
||||
}
|
||||
if (applied && (report.patches?.errors?.length || report.errors.some((e) => /^revert patches:/.test(e)))) {
|
||||
report.ok = false;
|
||||
report.needRestart = false;
|
||||
report.cleanup = [];
|
||||
return report;
|
||||
}
|
||||
|
||||
try {
|
||||
report.shim = await core.revertAllShims();
|
||||
if (state.shim_cmd === "patched" || state.shim_ps1 === "patched" || state.shim_bin === "patched") {
|
||||
report.reverted = true;
|
||||
}
|
||||
} catch (e) {
|
||||
report.errors.push(`revert shims: ${e.message || e}`);
|
||||
}
|
||||
|
||||
try {
|
||||
report.flash = core.revertCmdFlash(state.ai_base, dshHome);
|
||||
} catch (e) {
|
||||
report.errors.push(`revert flash: ${e.message || e}`);
|
||||
}
|
||||
|
||||
try {
|
||||
report.override = await removeOverride(dshHome);
|
||||
} catch (e) {
|
||||
report.errors.push(`remove override: ${e.message || e}`);
|
||||
}
|
||||
|
||||
try {
|
||||
report.rules = await resetRules(dshHome);
|
||||
} catch (e) {
|
||||
report.errors.push(`reset rules: ${e.message || e}`);
|
||||
}
|
||||
|
||||
const profiles = listInstalledProfiles(dshHome);
|
||||
report.profiles = profiles.map((p) => p.name);
|
||||
const unreg = unregisterProfiles(profiles);
|
||||
report.stripped = unreg.stripped;
|
||||
report.errors.push(...unreg.errors.map((x) => `${x.profile}: ${x.error}`));
|
||||
|
||||
report.cleanup = collectCleanupDirs(profiles, dshHome);
|
||||
return report;
|
||||
}
|
||||
|
||||
export function scheduleCleanupRestart({ request, restartArgv, cleanup = [] } = {}) {
|
||||
const src = fileURLToPath(new URL("./uninstall-restart.js", import.meta.url));
|
||||
const dest = path.join(os.tmpdir(), `dsh-purge-uninst-${process.pid}.mjs`);
|
||||
fs.copyFileSync(src, dest);
|
||||
const hostHeader = String(request?.headers?.host || "127.0.0.1");
|
||||
const portMatch = hostHeader.match(/:(\d+)$/);
|
||||
const child = spawn(process.execPath, [dest], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
windowsHide: true,
|
||||
shell: false,
|
||||
env: {
|
||||
...core.envForDetachedSpawn(),
|
||||
DSH_PURGE_RESTART: JSON.stringify({
|
||||
execPath: process.execPath,
|
||||
argv: restartArgv || [process.argv[1], "--no-open"],
|
||||
cwd: process.cwd(),
|
||||
host: hostHeader.replace(/:\d+$/, "") || "127.0.0.1",
|
||||
port: portMatch ? Number(portMatch[1]) : 3080,
|
||||
cleanup,
|
||||
helper: dest,
|
||||
}),
|
||||
},
|
||||
});
|
||||
child.unref();
|
||||
setTimeout(() => process.exit(0), 400);
|
||||
}
|
||||
+6
-6
@@ -67,7 +67,7 @@ function sameRev(a, b) {
|
||||
return a === b || a.startsWith(b) || b.startsWith(a);
|
||||
}
|
||||
|
||||
function realPath(dir) {
|
||||
export function realPath(dir) {
|
||||
try {
|
||||
return fs.realpathSync(dir);
|
||||
} catch {
|
||||
@@ -109,17 +109,17 @@ function gitHead(dir) {
|
||||
}
|
||||
}
|
||||
|
||||
function isLinkSpec(spec) {
|
||||
export function isLinkSpec(spec) {
|
||||
const s = String(spec || "");
|
||||
return /^(link|file):/i.test(s) || s === "." || /^\.\.?(?:[/\\]|$)/.test(s);
|
||||
}
|
||||
|
||||
function resolveLinkDir(profileDir, spec) {
|
||||
export function resolveLinkDir(profileDir, spec) {
|
||||
const raw = String(spec).replace(/^(link|file):/i, "");
|
||||
return path.resolve(profileDir, raw);
|
||||
}
|
||||
|
||||
function findPurgeProfiles() {
|
||||
export function findPurgeProfiles() {
|
||||
const root = path.join(findDshHome(), "profiles");
|
||||
if (!fs.existsSync(root)) return [];
|
||||
let names = [];
|
||||
@@ -139,7 +139,7 @@ function findPurgeProfiles() {
|
||||
return out;
|
||||
}
|
||||
|
||||
function profilePluginDir(profileDir) {
|
||||
export function profilePluginDir(profileDir) {
|
||||
const nm = path.join(profileDir, "node_modules", "dsh-purge");
|
||||
return fs.existsSync(nm) ? realPath(nm) : "";
|
||||
}
|
||||
@@ -167,7 +167,7 @@ function resolveDshBin() {
|
||||
return "";
|
||||
}
|
||||
|
||||
function runDshPlugin(profile, args) {
|
||||
export function runDshPlugin(profile, args) {
|
||||
const bin = resolveDshBin();
|
||||
if (!bin) throw new Error("找不到 dsh");
|
||||
execFileSync(bin, ["plugin", "--profile", profile, ...args], {
|
||||
|
||||
Reference in new issue
Block a user