fix(core,cli): harden install engine and argument parsing
- Reject unknown flags with exit 2 and never write on --dry-run, even in a TTY - Treat files already matching the new content as up to date after an interrupted update - Remove unmodified orphan files from older versions, keep and report modified ones and shared paths - Degrade malformed manifests instead of blocking installs; readIfExists only maps ENOENT/ENOTDIR to null - Block downgrades from older CLIs (semver), honor uninstall --scope, dedupe targets, fix next-step output and table width - Deeper package verification, LF normalization for .mjs, MIT LICENSE
This commit is contained in:
parent
97f2c241e4
commit
eecd3f03ff
29 changed files with 867 additions and 124 deletions
|
|
@ -1,5 +1,5 @@
|
|||
import assert from "node:assert/strict";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { execFileSync, spawnSync } from "node:child_process";
|
||||
import fs from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
|
@ -33,6 +33,23 @@ function run(args: string[], cwd?: string): string {
|
|||
});
|
||||
}
|
||||
|
||||
/** 종료 코드·stderr 까지 본다. stdin 을 닫아 TTY 가 아닌 환경을 흉내 낸다 */
|
||||
function runRaw(args: string[], cwd?: string) {
|
||||
const r = spawnSync(process.execPath, [CLI, ...args, "--no-update-check"], {
|
||||
encoding: "utf8",
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
...(cwd ? { cwd } : {}),
|
||||
env: {
|
||||
...process.env,
|
||||
HOME: home,
|
||||
USERPROFILE: home,
|
||||
FORCE_COLOR: "0",
|
||||
DESIGNPACA_STATE_DIR: path.join(home, ".designpaca"),
|
||||
},
|
||||
});
|
||||
return { status: r.status, stdout: r.stdout, stderr: r.stderr };
|
||||
}
|
||||
|
||||
test("빌드 산출물이 있어야 한다", { skip: built ? false : "pnpm build 먼저 실행해라" }, () => {
|
||||
assert.ok(built);
|
||||
});
|
||||
|
|
@ -42,6 +59,10 @@ test("--version 은 스킬 버전과 같다", { skip: !built }, async () => {
|
|||
await fs.readFile(fileURLToPath(new URL("../dist/skill/.designpaca_version", import.meta.url)), "utf8")
|
||||
).trim();
|
||||
assert.equal(run(["--version"]).trim(), stamp);
|
||||
|
||||
// 스탬프를 --version 과만 비교하면 순환이다 — package.json 과의 일치까지 본다(AGENTS.md 4번 불변식)
|
||||
const pkg = JSON.parse(await fs.readFile(fileURLToPath(new URL("../package.json", import.meta.url)), "utf8"));
|
||||
assert.equal(stamp, pkg.version, "dist 가 오래됐다: 버전을 올린 뒤 pnpm build 를 다시 실행해라");
|
||||
});
|
||||
|
||||
test("도움말에 모든 명령이 나온다", { skip: !built }, () => {
|
||||
|
|
@ -163,3 +184,162 @@ test("update 는 project 설치를 기록된 root 에서 갱신하고 cwd 에는
|
|||
await assert.rejects(() => fs.access(path.join(repoA, ".claude", "skills", "designpaca", "SKILL.md")));
|
||||
assert.equal(await fs.readFile(userSkill, "utf8"), "user own skill\n");
|
||||
});
|
||||
|
||||
test("알 수 없는 옵션은 종료 코드 2 로 거부하고 아무것도 실행하지 않는다", { skip: !built }, () => {
|
||||
for (const flag of ["--dryrun", "--dry_run", "--forse", "--yes=true", "-x"]) {
|
||||
const r = runRaw(["uninstall", flag]);
|
||||
assert.equal(r.status, 2, `${flag} 가 거부되지 않았다`);
|
||||
assert.ok(r.stderr.includes("알 수 없는 옵션"), r.stderr);
|
||||
}
|
||||
const r = runRaw(["install", "foo", "-y"]);
|
||||
assert.equal(r.status, 2);
|
||||
assert.ok(r.stderr.includes("알 수 없는 인자"));
|
||||
// --help 는 다른 입력 오류보다 먼저 처리된다
|
||||
assert.equal(runRaw(["--help", "--dryrun"]).status, 0);
|
||||
});
|
||||
|
||||
test("값 옵션에 값이 없거나 비면 종료 코드 2 다", { skip: !built }, () => {
|
||||
for (const args of [
|
||||
["install", "-t"],
|
||||
["install", "-t", "-y"],
|
||||
["install", "--target="],
|
||||
["install", "-t", ",,"],
|
||||
["install", "-s"],
|
||||
["install", "--scope="],
|
||||
]) {
|
||||
const r = runRaw(args);
|
||||
assert.equal(r.status, 2, `${args.join(" ")} 가 거부되지 않았다`);
|
||||
assert.ok(r.stderr.includes("값이 필요합니다"), r.stderr);
|
||||
}
|
||||
});
|
||||
|
||||
test("종료 코드: 잘못된 범위와 알 수 없는 명령은 2, 기록 없는 update 는 1", { skip: !built }, () => {
|
||||
assert.equal(runRaw(["install", "-s", "galaxy", "-y"]).status, 2);
|
||||
assert.equal(runRaw(["frobnicate"]).status, 2);
|
||||
assert.equal(runRaw(["update"]).status, 1);
|
||||
assert.equal(runRaw(["doctor"]).status, 0);
|
||||
assert.equal(runRaw(["ls"]).status, 0);
|
||||
assert.equal(runRaw(["list"]).status, 0);
|
||||
});
|
||||
|
||||
test("stdin 이 TTY 가 아니면 인자 없이 실행해도 프롬프트 없이 사용법을 낸다", { skip: !built }, () => {
|
||||
const r = runRaw([]);
|
||||
assert.equal(r.status, 0);
|
||||
assert.ok(r.stdout.includes("사용법"));
|
||||
const d = runRaw(["install", "--dry-run"]);
|
||||
assert.equal(d.status, 0);
|
||||
assert.ok(d.stdout.includes("설치 계획"));
|
||||
});
|
||||
|
||||
test("중복 대상은 한 번만 설치한다", { skip: !built }, () => {
|
||||
const r = runRaw(["install", "-t", "claude-code,claude-code", "-t", "claude-code", "-y"]);
|
||||
assert.equal(r.status, 0);
|
||||
assert.equal(r.stdout.split("claude-code — 설치됨").length - 1, 1, r.stdout);
|
||||
runRaw(["uninstall", "-y"]);
|
||||
});
|
||||
|
||||
test("uninstall -s 는 지정한 범위만 지우고, 범위를 안 주면 모두 지운다", { skip: !built }, async () => {
|
||||
const proj = path.join(home, "scope-proj");
|
||||
await fs.mkdir(proj, { recursive: true });
|
||||
const userSkill = path.join(home, ".claude", "skills", "designpaca", "SKILL.md");
|
||||
const projSkill = path.join(proj, ".claude", "skills", "designpaca", "SKILL.md");
|
||||
|
||||
runRaw(["install", "-t", "claude-code", "-s", "user", "-y"], proj);
|
||||
runRaw(["install", "-t", "claude-code", "-s", "project", "-y"], proj);
|
||||
await fs.access(userSkill);
|
||||
await fs.access(projSkill);
|
||||
|
||||
assert.equal(runRaw(["uninstall", "-t", "claude-code", "-s", "project", "-y"], proj).status, 0);
|
||||
await assert.rejects(() => fs.access(projSkill));
|
||||
await fs.access(userSkill); // user 설치는 남아야 한다
|
||||
|
||||
runRaw(["install", "-t", "claude-code", "-s", "project", "-y"], proj);
|
||||
assert.equal(runRaw(["uninstall", "-y"], proj).status, 0);
|
||||
await assert.rejects(() => fs.access(userSkill));
|
||||
await assert.rejects(() => fs.access(projSkill));
|
||||
});
|
||||
|
||||
test("설치본이 CLI 보다 새로우면 update 는 건너뛰고 doctor 는 문제로 세지 않는다", { skip: !built }, async () => {
|
||||
runRaw(["install", "-t", "claude-code", "-s", "user", "-y"]);
|
||||
const manifestFile = path.join(home, ".designpaca", "manifest.json");
|
||||
const skillMd = path.join(home, ".claude", "skills", "designpaca", "SKILL.md");
|
||||
const manifest = JSON.parse(await fs.readFile(manifestFile, "utf8"));
|
||||
manifest.installs[0].version = "99.0.0";
|
||||
await fs.writeFile(manifestFile, JSON.stringify(manifest, null, 2) + "\n", "utf8");
|
||||
const manifestBefore = await fs.readFile(manifestFile, "utf8");
|
||||
const statBefore = await fs.stat(skillMd);
|
||||
|
||||
const up = runRaw(["update"]);
|
||||
assert.equal(up.status, 0, up.stdout);
|
||||
assert.ok(up.stdout.includes("건너뛴다"), up.stdout);
|
||||
assert.equal(await fs.readFile(manifestFile, "utf8"), manifestBefore, "다운그레이드가 기록을 바꿨다");
|
||||
assert.equal((await fs.stat(skillMd)).mtimeMs, statBefore.mtimeMs);
|
||||
|
||||
const doc = runRaw(["doctor"]);
|
||||
assert.equal(doc.status, 0, doc.stdout);
|
||||
assert.ok(doc.stdout.includes("더 오래됨"), doc.stdout);
|
||||
assert.ok(!doc.stdout.includes("업데이트 가능"));
|
||||
|
||||
// --force 일 때만 다시 쓴다
|
||||
assert.equal(runRaw(["update", "--force"]).status, 0);
|
||||
const after = JSON.parse(await fs.readFile(manifestFile, "utf8"));
|
||||
assert.equal(after.installs[0].version, run(["--version"]).trim());
|
||||
runRaw(["uninstall", "-y"]);
|
||||
});
|
||||
|
||||
test("사용자가 수정한 파일은 install 이 건너뛰고 --force 는 .orig 로 백업한다", { skip: !built }, async () => {
|
||||
runRaw(["install", "-t", "claude-code", "-s", "user", "-y"]);
|
||||
const skillMd = path.join(home, ".claude", "skills", "designpaca", "SKILL.md");
|
||||
await fs.appendFile(skillMd, "\n내 메모\n", "utf8");
|
||||
const edited = await fs.readFile(skillMd, "utf8");
|
||||
|
||||
runRaw(["install", "-t", "claude-code", "-s", "user", "-y"]);
|
||||
assert.equal(await fs.readFile(skillMd, "utf8"), edited, "수정 파일을 덮어썼다");
|
||||
|
||||
assert.equal(runRaw(["install", "-t", "claude-code", "-s", "user", "-y", "--force"]).status, 0);
|
||||
assert.notEqual(await fs.readFile(skillMd, "utf8"), edited);
|
||||
assert.equal(await fs.readFile(skillMd + ".orig", "utf8"), edited);
|
||||
await fs.rm(skillMd + ".orig", { force: true });
|
||||
runRaw(["uninstall", "-y"]);
|
||||
});
|
||||
|
||||
/** 매니페스트에 "이전 버전이 깔았던 파일"을 심는다 — 새 버전 계획에 없는 파일이 stale 이 된다 */
|
||||
async function plantStale(rel: string, content: string): Promise<string> {
|
||||
const manifestFile = path.join(home, ".designpaca", "manifest.json");
|
||||
const m = JSON.parse(await fs.readFile(manifestFile, "utf8"));
|
||||
const rec = m.installs[0];
|
||||
const file = path.join(rec.root, ...rel.split("/"));
|
||||
await fs.mkdir(path.dirname(file), { recursive: true });
|
||||
await fs.writeFile(file, content, "utf8");
|
||||
const { createHash } = await import("node:crypto");
|
||||
rec.files.push({ path: file, sha256: createHash("sha256").update(content).digest("hex") });
|
||||
await fs.writeFile(manifestFile, JSON.stringify(m, null, 2), "utf8");
|
||||
return file;
|
||||
}
|
||||
|
||||
test("새 버전에서 빠진 파일은 지우고 안내하며, 수정돼 있으면 남기고 안내한다", { skip: !built }, async () => {
|
||||
runRaw(["install", "-t", "claude-code", "-s", "user", "-y"]);
|
||||
const gone = await plantStale("references/old-removed.md", "예전 문서\n");
|
||||
const r1 = runRaw(["install", "-t", "claude-code", "-s", "user", "-y"]);
|
||||
assert.match(r1.stdout, /새 버전에서 빠진 파일 1개를 제거/);
|
||||
await assert.rejects(fs.access(gone), "빠진 파일이 남아 있다");
|
||||
|
||||
const kept = await plantStale("references/old-edited.md", "예전 문서\n");
|
||||
await fs.appendFile(kept, "내 메모\n", "utf8");
|
||||
const r2 = runRaw(["install", "-t", "claude-code", "-s", "user", "-y"]);
|
||||
assert.match(r2.stdout, /새 버전에서 빠졌지만 수정돼 있어 남겨 두었습니다/);
|
||||
await fs.access(kept);
|
||||
runRaw(["uninstall", "-y", "--force"]);
|
||||
});
|
||||
|
||||
test("다른 대상과 경로를 공유하는 파일은 uninstall 이 남기고 안내한다", { skip: !built }, async () => {
|
||||
const proj = await fs.mkdtemp(path.join(os.tmpdir(), "designpaca-shared-"));
|
||||
try {
|
||||
runRaw(["install", "-t", "agents,antigravity", "-s", "project", "-y"], proj);
|
||||
const r = runRaw(["uninstall", "-t", "agents", "-s", "project", "-y"], proj);
|
||||
assert.match(r.stdout, /다른 대상과 공유 중이라 남긴 파일 \d+개/);
|
||||
runRaw(["uninstall", "-y"], proj);
|
||||
} finally {
|
||||
await fs.rm(proj, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
|
|
|||
48
packages/cli/test/units.test.ts
Normal file
48
packages/cli/test/units.test.ts
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { compareVersions, isNewer } from "../src/semver.ts";
|
||||
import { displayWidth, fold, heading, padDisplay, table } from "../src/ui.ts";
|
||||
|
||||
test("isNewer 는 숫자 세 칸을 semver 로 비교한다", () => {
|
||||
assert.equal(isNewer("0.14.0", "0.12.0"), true);
|
||||
assert.equal(isNewer("0.12.0", "0.14.0"), false);
|
||||
assert.equal(isNewer("0.14.0", "0.14.0"), false);
|
||||
assert.equal(isNewer("0.10.0", "0.9.0"), true, "문자열 비교가 아니라 숫자 비교다");
|
||||
assert.equal(isNewer("1.0.0", "0.99.99"), true);
|
||||
});
|
||||
|
||||
test("프리릴리스는 같은 숫자의 정식 버전보다 낮다", () => {
|
||||
assert.equal(isNewer("1.0.0", "1.0.0-rc.1"), true);
|
||||
assert.equal(isNewer("1.0.0-rc.1", "1.0.0"), false);
|
||||
assert.ok(compareVersions("1.0.0-rc.2", "1.0.0-rc.1") > 0);
|
||||
assert.ok(compareVersions("1.0.0-rc.10", "1.0.0-rc.9") > 0);
|
||||
assert.equal(compareVersions("1.0.0+build5", "1.0.0"), 0);
|
||||
});
|
||||
|
||||
test("displayWidth 는 한글을 2칸으로 센다", () => {
|
||||
assert.equal(displayWidth("abc"), 3);
|
||||
assert.equal(displayWidth("위치"), 4);
|
||||
assert.equal(displayWidth("CLI 버전"), 8);
|
||||
assert.equal(displayWidth("\x1b[31mab\x1b[0m"), 2, "ANSI 이스케이프는 폭이 아니다");
|
||||
});
|
||||
|
||||
test("padDisplay 와 table 은 한글이 섞여도 값 열이 같은 칸에서 시작한다", () => {
|
||||
assert.equal(displayWidth(padDisplay("위치", 8)), 8);
|
||||
const lines = table([
|
||||
["위치", "a"],
|
||||
["CLI 버전", "b"],
|
||||
["Node", "c"],
|
||||
]).split("\n");
|
||||
const starts = lines.map((l) => displayWidth(l.slice(0, l.search(/[abc]$/))));
|
||||
assert.equal(new Set(starts).size, 1, `값 열 시작 칸이 제각각이다: ${starts}`);
|
||||
});
|
||||
|
||||
test("heading 밑줄은 표시 폭을 기준으로 한다", () => {
|
||||
const rule = (heading("설치 기록").split("\n")[2] ?? "").replace(/\x1b\[[0-9;]*m/g, "");
|
||||
assert.equal([...rule].length, displayWidth("설치 기록") + 8);
|
||||
});
|
||||
|
||||
test("fold 는 max 를 넘는 항목을 접는다", () => {
|
||||
assert.deepEqual(fold(["a", "b"], 3), ["a", "b"]);
|
||||
assert.equal(fold(["a", "b", "c", "d"], 2).length, 3);
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue