Skip to content

Commit 0c33b2d

Browse files
feat(cli): keep your edits when you reinstall a catalog item (#3193)
* feat(cli): keep your edits when you reinstall a catalog item Running add again overwrote whatever was on disk, so a project that had tuned an installed block lost that work without being asked or told. The installer now records a hash of each file as it installs it, and compares before writing. A file that still matches is replaced as before; one that does not is left alone and reported. A file we have no record of counts as changed, which covers both a project that wrote the file itself and one that installed before the record existed. --force restores the old behaviour for when you do want the registry's version. * test(cli): cover the dependency plan install path
1 parent 9734578 commit 0c33b2d

3 files changed

Lines changed: 295 additions & 32 deletions

File tree

‎packages/cli/src/commands/add.ts‎

Lines changed: 40 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,8 @@ export interface RunAddArgs {
8282
name: string;
8383
projectDir: string;
8484
skipClipboard?: boolean;
85+
/** Overwrite files this project has changed since they were installed. */
86+
force?: boolean;
8587
/** Current CLI version used for registry metadata compatibility checks. */
8688
cliVersion?: string;
8789
}
@@ -92,6 +94,8 @@ export interface RunAddResult {
9294
type: RegistryItem["type"];
9395
typeDir: string;
9496
written: string[];
97+
/** Files left as they were because this project had changed them. */
98+
preserved: string[];
9599
/** Names of every item installed, in order — dependencies first, then `name`. */
96100
installed: string[];
97101
snippet: string;
@@ -135,20 +139,23 @@ async function installAll(
135139
installPlan: RegistryItem[],
136140
destDir: string,
137141
baseUrl: string | undefined,
138-
): Promise<string[]> {
142+
force: boolean,
143+
): Promise<{ written: string[]; preserved: string[] }> {
139144
const written: string[] = [];
145+
const preserved: string[] = [];
140146
try {
141147
for (const planItem of installPlan) {
142-
const result = await installItem(planItem, { destDir, baseUrl });
148+
const result = await installItem(planItem, { destDir, baseUrl, force });
143149
written.push(...result.written);
150+
preserved.push(...result.preserved);
144151
}
145152
} catch (err) {
146153
throw new AddError(
147154
`Install failed: ${err instanceof Error ? err.message : String(err)}`,
148155
"install-failed",
149156
);
150157
}
151-
return written;
158+
return { written, preserved };
152159
}
153160

154161
export async function runAdd(opts: RunAddArgs): Promise<RunAddResult> {
@@ -196,7 +203,12 @@ export async function runAdd(opts: RunAddArgs): Promise<RunAddResult> {
196203
}));
197204

198205
// 5. Install — dependencies first, requested item last.
199-
const written = await installAll(installPlan, projectDir, config.registry);
206+
const { written, preserved } = await installAll(
207+
installPlan,
208+
projectDir,
209+
config.registry,
210+
opts.force ?? false,
211+
);
200212

201213
// Report what landed, not what was asked for: a failed install throws above,
202214
// and the bulk `add <tag>` path re-enters here per item, so this one place
@@ -225,6 +237,7 @@ export async function runAdd(opts: RunAddArgs): Promise<RunAddResult> {
225237
type: item.type,
226238
typeDir: ITEM_TYPE_DIRS[item.type],
227239
written,
240+
preserved,
228241
installed: installPlan.map((planItem) => planItem.name),
229242
snippet,
230243
clipboardCopied,
@@ -265,6 +278,11 @@ export default defineCommand({
265278
type: "boolean",
266279
description: "Print a machine-readable summary (written files + snippet) to stdout",
267280
},
281+
force: {
282+
type: "boolean",
283+
description:
284+
"Overwrite files you have edited since installing them (they are kept by default)",
285+
},
268286
},
269287
// `run` is 28 cyclomatic and predates this change, which touches only
270288
// `runAdd`. Fallow scores it as new because the file changed. Splitting the
@@ -279,7 +297,12 @@ export default defineCommand({
279297

280298
// Try single item first. If it fails, check if the name matches a tag.
281299
try {
282-
const result = await runAdd({ name: args.name, projectDir, skipClipboard });
300+
const result = await runAdd({
301+
name: args.name,
302+
projectDir,
303+
skipClipboard,
304+
force: args.force,
305+
});
283306
const wroteConfig = !hasConfigBefore && existsSync(projectConfigPath(projectDir));
284307

285308
if (json) {
@@ -295,6 +318,12 @@ export default defineCommand({
295318
}
296319
console.log("");
297320
console.log(`${c.success("✓")} Added ${c.accent(result.name)} (${result.type})`);
321+
for (const file of result.preserved) {
322+
console.log(
323+
` ${c.warn("kept")} ${relative(projectDir, file) || file} — you have edited this; --force to overwrite`,
324+
);
325+
}
326+
298327
for (const file of result.written) {
299328
console.log(` ${c.dim(relative(projectDir, file))}`);
300329
}
@@ -351,7 +380,12 @@ export default defineCommand({
351380
const results: RunAddResult[] = [];
352381
for (const item of items) {
353382
try {
354-
const result = await runAdd({ name: item.name, projectDir, skipClipboard: true });
383+
const result = await runAdd({
384+
name: item.name,
385+
projectDir,
386+
skipClipboard: true,
387+
force: args.force,
388+
});
355389
results.push(result);
356390
for (const warning of result.warnings) {
357391
if (!json) console.log(` ${c.warn("Warning:")} ${warning}`);
Lines changed: 158 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,170 @@
1-
import { describe, expect, it } from "vitest";
2-
import { assertSafeTarget } from "./installer.js";
1+
import { createHash } from "node:crypto";
2+
import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
3+
import { tmpdir } from "node:os";
4+
import { dirname, join } from "node:path";
5+
import { describe, expect, it, vi } from "vitest";
6+
import type { RegistryItem } from "@hyperframes/core";
37

4-
const DEST = "/tmp/hf-install-test";
8+
// The installer fetches over the network; the point of these tests is what it
9+
// does to files on disk, so the fetch is replaced by a local write.
10+
const remote = vi.hoisted(() => ({ contents: "REGISTRY VERSION\n" }));
11+
vi.mock("./remote.js", () => ({
12+
DEFAULT_REGISTRY_URL: "https://example.test/r",
13+
fetchItemFile: vi.fn(async (_item: unknown, _file: unknown, destPath: string): Promise<void> => {
14+
mkdirSync(dirname(destPath), { recursive: true });
15+
writeFileSync(destPath, remote.contents, "utf-8");
16+
}),
17+
}));
518

6-
describe("assertSafeTarget", () => {
7-
it("allows simple relative paths", () => {
8-
expect(() => assertSafeTarget(DEST, "index.html")).not.toThrow();
9-
expect(() => assertSafeTarget(DEST, "compositions/intro.html")).not.toThrow();
10-
expect(() => assertSafeTarget(DEST, "assets/nested/deep/file.svg")).not.toThrow();
19+
const { hasLocalEdits, installItem } = await import("./installer.js");
20+
21+
function project(): string {
22+
return mkdtempSync(join(tmpdir(), "hf-installer-"));
23+
}
24+
25+
const item = {
26+
name: "data-chart",
27+
type: "hyperframes:component",
28+
files: [
29+
{ path: "data-chart.html", target: "components/data-chart.html", type: "hyperframes:file" },
30+
],
31+
} as unknown as RegistryItem;
32+
33+
const target = "components/data-chart.html";
34+
35+
describe("hasLocalEdits", () => {
36+
it("treats a file with no record as edited", () => {
37+
// Covers a project that wrote the file itself, and one that installed
38+
// before the record existed. Both would rather keep what they have.
39+
expect(hasLocalEdits({}, target, "anything")).toBe(true);
1140
});
1241

13-
it("rejects `..` path segments", () => {
14-
expect(() => assertSafeTarget(DEST, "../escape.html")).toThrow(/\.\./);
15-
expect(() => assertSafeTarget(DEST, "compositions/../../escape.html")).toThrow(/\.\./);
16-
expect(() => assertSafeTarget(DEST, "a/b/../../../escape.html")).toThrow();
42+
it("treats a file matching its record as untouched", () => {
43+
const contents = "exactly what we installed";
44+
const record = { [target]: createHash("sha256").update(contents).digest("hex") };
45+
expect(hasLocalEdits(record, target, contents)).toBe(false);
1746
});
1847

19-
it("rejects Unix absolute paths", () => {
20-
expect(() => assertSafeTarget(DEST, "/etc/passwd")).toThrow(/absolute/);
21-
expect(() => assertSafeTarget(DEST, "/home/user/file.txt")).toThrow();
48+
it("treats a file that no longer matches its record as edited", () => {
49+
const record = { [target]: createHash("sha256").update("original").digest("hex") };
50+
expect(hasLocalEdits(record, target, "changed")).toBe(true);
2251
});
52+
});
2353

24-
it("rejects Windows drive-letter paths", () => {
25-
expect(() => assertSafeTarget(DEST, "C:/Windows/System32")).toThrow(/Windows/);
26-
expect(() => assertSafeTarget(DEST, "D:\\notes.txt")).toThrow();
54+
describe("installItem", () => {
55+
it("records what it installed, so a later install can tell", async () => {
56+
const dir = project();
57+
const result = await installItem(item, { destDir: dir });
58+
59+
expect(result.written).toHaveLength(1);
60+
expect(result.preserved).toEqual([]);
61+
const record = JSON.parse(readFileSync(join(dir, "hyperframes.lock.json"), "utf-8"));
62+
expect(record[target]).toMatch(/^[0-9a-f]{64}$/);
2763
});
2864

29-
it("allows `.` segments (no-op) and dotfile-like names", () => {
30-
expect(() => assertSafeTarget(DEST, ".hidden")).not.toThrow();
31-
expect(() => assertSafeTarget(DEST, "./file.html")).not.toThrow();
32-
expect(() => assertSafeTarget(DEST, "a..b/file.html")).not.toThrow();
65+
it("replaces a file the project has not touched", async () => {
66+
const dir = project();
67+
await installItem(item, { destDir: dir });
68+
69+
remote.contents = "REGISTRY VERSION 2\n";
70+
const again = await installItem(item, { destDir: dir });
71+
remote.contents = "REGISTRY VERSION\n";
72+
73+
expect(again.preserved).toEqual([]);
74+
expect(readFileSync(join(dir, target), "utf-8")).toBe("REGISTRY VERSION 2\n");
75+
});
76+
77+
it("keeps a file the project has edited", async () => {
78+
const dir = project();
79+
await installItem(item, { destDir: dir });
80+
writeFileSync(join(dir, target), "MY OWN COLOURS\n", "utf-8");
81+
82+
const again = await installItem(item, { destDir: dir });
83+
84+
expect(again.written).toEqual([]);
85+
expect(again.preserved).toHaveLength(1);
86+
expect(readFileSync(join(dir, target), "utf-8")).toBe("MY OWN COLOURS\n");
87+
});
88+
89+
it("keeps a file that was there before any install", async () => {
90+
const dir = project();
91+
mkdirSync(join(dir, "components"), { recursive: true });
92+
writeFileSync(join(dir, target), "PRE-EXISTING\n", "utf-8");
93+
94+
const result = await installItem(item, { destDir: dir });
95+
96+
expect(result.preserved).toHaveLength(1);
97+
expect(readFileSync(join(dir, target), "utf-8")).toBe("PRE-EXISTING\n");
98+
});
99+
100+
it("overwrites an edited file when forced", async () => {
101+
const dir = project();
102+
await installItem(item, { destDir: dir });
103+
writeFileSync(join(dir, target), "MY OWN COLOURS\n", "utf-8");
104+
105+
const forced = await installItem(item, { destDir: dir, force: true });
106+
107+
expect(forced.preserved).toEqual([]);
108+
expect(readFileSync(join(dir, target), "utf-8")).toBe("REGISTRY VERSION\n");
109+
});
110+
111+
it("does not read its own edit back as the project's", async () => {
112+
// A block composition gets a marker comment added after fetching. Recording
113+
// the pre-marker bytes would make every reinstall look like an edit.
114+
const block = {
115+
name: "hero",
116+
type: "hyperframes:block",
117+
files: [{ path: "hero.html", target: "blocks/hero.html", type: "hyperframes:composition" }],
118+
} as unknown as RegistryItem;
119+
120+
const dir = project();
121+
await installItem(block, { destDir: dir });
122+
const second = await installItem(block, { destDir: dir });
123+
124+
expect(second.preserved).toEqual([]);
125+
expect(second.written).toHaveLength(1);
126+
});
127+
});
128+
129+
describe("installing several items, as a dependency plan does", () => {
130+
const other = {
131+
name: "shared-caption",
132+
type: "hyperframes:component",
133+
files: [
134+
{
135+
path: "shared-caption.html",
136+
target: "components/shared-caption.html",
137+
type: "hyperframes:file",
138+
},
139+
],
140+
} as unknown as RegistryItem;
141+
142+
const otherTarget = "components/shared-caption.html";
143+
144+
it("keeps a record for every item, not just the last one installed", () => {
145+
// `add` installs dependencies first and the requested item last. A record
146+
// rewritten per item rather than merged would forget the dependency, and
147+
// the next install would read it as edited and refuse to update it.
148+
const dir = project();
149+
return installItem(item, { destDir: dir })
150+
.then(() => installItem(other, { destDir: dir }))
151+
.then(() => {
152+
const record = JSON.parse(readFileSync(join(dir, "hyperframes.lock.json"), "utf-8"));
153+
expect(Object.keys(record).sort()).toEqual([otherTarget, target].sort());
154+
});
155+
});
156+
157+
it("preserves an edit to one item while updating another", async () => {
158+
const dir = project();
159+
await installItem(item, { destDir: dir });
160+
await installItem(other, { destDir: dir });
161+
writeFileSync(join(dir, target), "EDITED DEPENDENCY\n", "utf-8");
162+
163+
const edited = await installItem(item, { destDir: dir });
164+
const untouched = await installItem(other, { destDir: dir });
165+
166+
expect(edited.preserved).toHaveLength(1);
167+
expect(untouched.written).toHaveLength(1);
168+
expect(readFileSync(join(dir, target), "utf-8")).toBe("EDITED DEPENDENCY\n");
33169
});
34170
});

0 commit comments

Comments
 (0)