xonecas.io
64875
Mc

mini-coder / commit d1f6c39

feat: add mc-edit helper and extract file edit internals

xonecas2026-03-15 d1f6c39b088f45f3fd48fbecf2ced072e032ba05 parent 5980c72

9 files changed

package.json+5−1
@@ -5,7 +5,8 @@
55 "module": "src/index.ts",
66 "type": "module",
77 "bin": {
8- "mc": "dist/mc.js"
8+ "mc": "dist/mc.js",
9+ "mc-edit": "dist/mc-edit.js"
910 },
1011 "scripts": {
1112 "build": "bun run scripts/build.ts",
@@ -35,5 +36,8 @@
3536 "knip": "^5.86.0",
3637 "typescript": "^5.9.3"
3738 },
39+ "knip": {
40+ "entry": ["src/mc-edit.ts"]
41+ },
3842 "license": "MIT"
3943 }
scripts/build.ts+19−14
@@ -1,19 +1,24 @@
11 import pkg from "../package.json";
22
3-const result = await Bun.build({
4- entrypoints: ["src/index.ts"],
5- target: "bun",
6- outdir: "dist",
7- naming: "mc.js",
8- packages: "external",
9- define: {
10- __PACKAGE_VERSION__: JSON.stringify(pkg.version),
11- },
12-});
3+async function buildEntrypoint(entrypoint: string, outputName: string) {
4+ const result = await Bun.build({
5+ entrypoints: [entrypoint],
6+ target: "bun",
7+ outdir: "dist",
8+ naming: outputName,
9+ packages: "external",
10+ define: {
11+ __PACKAGE_VERSION__: JSON.stringify(pkg.version),
12+ },
13+ });
1314
14-if (!result.success) {
15- for (const log of result.logs) {
16- console.error(log);
15+ if (!result.success) {
16+ for (const log of result.logs) {
17+ console.error(log);
18+ }
19+ process.exit(1);
1720 }
18- process.exit(1);
1921 }
22+
23+await buildEntrypoint("src/index.ts", "mc.js");
24+await buildEntrypoint("src/mc-edit.ts", "mc-edit.js");
src/internal/file-edit/cli.test.ts+84−0
@@ -0,0 +1,84 @@
1+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2+import { mkdtemp, rm, writeFile } from "node:fs/promises";
3+import { tmpdir } from "node:os";
4+import { join } from "node:path";
5+import { runFileEditCli } from "./cli.ts";
6+
7+let cwd = "";
8+
9+beforeEach(async () => {
10+ cwd = await mkdtemp(join(tmpdir(), "mc-file-edit-cli-test-"));
11+});
12+
13+afterEach(async () => {
14+ if (cwd) {
15+ await rm(cwd, { recursive: true, force: true });
16+ cwd = "";
17+ }
18+});
19+
20+function createIo() {
21+ let stdout = "";
22+ let stderr = "";
23+ return {
24+ io: {
25+ stdout: (text: string) => {
26+ stdout += text;
27+ },
28+ stderr: (text: string) => {
29+ stderr += text;
30+ },
31+ },
32+ getStdout: () => stdout,
33+ getStderr: () => stderr,
34+ };
35+}
36+
37+describe("runFileEditCli", () => {
38+ test("applies one edit from temp files and emits compact json", async () => {
39+ await writeFile(join(cwd, "f.txt"), "before\nOLD\nafter\n");
40+ await writeFile(join(cwd, "old.txt"), "OLD\n");
41+ await writeFile(join(cwd, "new.txt"), "NEW\n");
42+ const capture = createIo();
43+
44+ const exitCode = await runFileEditCli(
45+ [
46+ "f.txt",
47+ "--cwd",
48+ cwd,
49+ "--old-file",
50+ join(cwd, "old.txt"),
51+ "--new-file",
52+ join(cwd, "new.txt"),
53+ ],
54+ capture.io,
55+ );
56+
57+ expect(exitCode).toBe(0);
58+ expect(capture.getStderr()).toBe("");
59+ expect(JSON.parse(capture.getStdout())).toEqual({
60+ ok: true,
61+ path: "f.txt",
62+ changed: true,
63+ });
64+ expect(await Bun.file(join(cwd, "f.txt")).text()).toBe(
65+ "before\nNEW\nafter\n",
66+ );
67+ });
68+
69+ test("returns a structured invalid_args error", async () => {
70+ const capture = createIo();
71+
72+ const exitCode = await runFileEditCli(
73+ ["f.txt", "--old", "a", "--old-file", "old.txt"],
74+ capture.io,
75+ );
76+
77+ expect(exitCode).toBe(1);
78+ expect(JSON.parse(capture.getStdout())).toEqual({
79+ ok: false,
80+ code: "invalid_args",
81+ message: "Provide exactly one of --old or --old-file.",
82+ });
83+ });
84+});
src/internal/file-edit/cli.ts+165−0
@@ -0,0 +1,165 @@
1+import {
2+ applyExactTextEdit,
3+ FileEditError,
4+ type FileEditErrorCode,
5+} from "./exact-text.ts";
6+
7+interface FileEditCliArgs {
8+ cwd: string;
9+ path: string;
10+ oldText: string;
11+ newText: string;
12+}
13+
14+interface FileEditCliIo {
15+ stdout: (text: string) => void;
16+ stderr: (text: string) => void;
17+}
18+
19+type FileEditCliSuccess = {
20+ ok: true;
21+ path: string;
22+ changed: boolean;
23+};
24+
25+type FileEditCliFailure = {
26+ ok: false;
27+ code: FileEditErrorCode | "invalid_args";
28+ message: string;
29+ path?: string;
30+};
31+
32+const HELP = `Usage: mc-edit <path> (--old <text> | --old-file <path>) [--new <text> | --new-file <path>] [--cwd <path>]
33+
34+Apply one safe exact-text edit to an existing file.
35+- The expected old text must match exactly once.
36+- Omit --new / --new-file to delete the matched text.
37+- Output is a single JSON object on stdout.`;
38+
39+async function readArgText(
40+ flag: "--old-file" | "--new-file",
41+ filePath: string,
42+): Promise<string> {
43+ const file = Bun.file(filePath);
44+ if (!(await file.exists())) {
45+ throw new FileEditError(
46+ "file_not_found",
47+ `${flag} file not found: "${filePath}".`,
48+ );
49+ }
50+ return file.text();
51+}
52+
53+async function parseFileEditCliArgs(
54+ argv: string[],
55+): Promise<FileEditCliArgs | null> {
56+ let cwd = process.cwd();
57+ let path: string | null = null;
58+ let oldText: string | null = null;
59+ let oldFilePath: string | null = null;
60+ let newText: string | null = null;
61+ let newFilePath: string | null = null;
62+
63+ for (let i = 0; i < argv.length; i++) {
64+ const arg = argv[i] ?? "";
65+ switch (arg) {
66+ case "--help":
67+ case "-h":
68+ return null;
69+ case "--cwd":
70+ cwd = argv[++i] ?? process.cwd();
71+ break;
72+ case "--old":
73+ oldText = argv[++i] ?? "";
74+ break;
75+ case "--old-file":
76+ oldFilePath = argv[++i] ?? null;
77+ break;
78+ case "--new":
79+ newText = argv[++i] ?? "";
80+ break;
81+ case "--new-file":
82+ newFilePath = argv[++i] ?? null;
83+ break;
84+ default:
85+ if (arg.startsWith("-")) {
86+ throw new Error(`Unknown flag: ${arg}`);
87+ }
88+ if (path !== null) {
89+ throw new Error("Expected exactly one positional <path> argument.");
90+ }
91+ path = arg;
92+ }
93+ }
94+
95+ if (path === null) {
96+ throw new Error("Missing required <path> argument.");
97+ }
98+ if ((oldText === null) === (oldFilePath === null)) {
99+ throw new Error("Provide exactly one of --old or --old-file.");
100+ }
101+ if (newText !== null && newFilePath !== null) {
102+ throw new Error("Provide at most one of --new or --new-file.");
103+ }
104+
105+ return {
106+ cwd,
107+ path,
108+ oldText: oldText ?? (await readArgText("--old-file", oldFilePath ?? "")),
109+ newText:
110+ newText ??
111+ (newFilePath ? await readArgText("--new-file", newFilePath) : ""),
112+ };
113+}
114+
115+function writeJson(
116+ io: FileEditCliIo,
117+ payload: FileEditCliSuccess | FileEditCliFailure,
118+) {
119+ io.stdout(`${JSON.stringify(payload)}\n`);
120+}
121+
122+function normalizeCliError(error: unknown): FileEditCliFailure {
123+ if (error instanceof FileEditError) {
124+ return {
125+ ok: false,
126+ code: error.code,
127+ message: error.message,
128+ };
129+ }
130+ if (error instanceof Error) {
131+ return {
132+ ok: false,
133+ code: "invalid_args",
134+ message: error.message,
135+ };
136+ }
137+ return {
138+ ok: false,
139+ code: "invalid_args",
140+ message: "Unknown error.",
141+ };
142+}
143+
144+export async function runFileEditCli(
145+ argv: string[],
146+ io: FileEditCliIo = {
147+ stdout: (text) => process.stdout.write(text),
148+ stderr: (text) => process.stderr.write(text),
149+ },
150+): Promise<number> {
151+ try {
152+ const parsed = await parseFileEditCliArgs(argv);
153+ if (parsed === null) {
154+ io.stderr(`${HELP}\n`);
155+ return 0;
156+ }
157+
158+ const result = await applyExactTextEdit(parsed);
159+ writeJson(io, { ok: true, ...result });
160+ return 0;
161+ } catch (error) {
162+ writeJson(io, normalizeCliError(error));
163+ return 1;
164+ }
165+}
src/internal/file-edit/exact-text.test.ts+96−0
@@ -0,0 +1,96 @@
1+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2+import { mkdtemp, rm, writeFile } from "node:fs/promises";
3+import { tmpdir } from "node:os";
4+import { join } from "node:path";
5+import {
6+ applyExactTextEdit,
7+ FileEditError,
8+ planExactTextEdit,
9+} from "./exact-text.ts";
10+
11+let cwd = "";
12+
13+beforeEach(async () => {
14+ cwd = await mkdtemp(join(tmpdir(), "mc-file-edit-test-"));
15+});
16+
17+afterEach(async () => {
18+ if (cwd) {
19+ await rm(cwd, { recursive: true, force: true });
20+ cwd = "";
21+ }
22+});
23+
24+describe("planExactTextEdit", () => {
25+ test("replaces one exact unique match", () => {
26+ const result = planExactTextEdit(
27+ "alpha\nbeta\ngamma\n",
28+ "beta\n",
29+ "BETA\n",
30+ );
31+
32+ expect(result).toEqual({
33+ updated: "alpha\nBETA\ngamma\n",
34+ changed: true,
35+ });
36+ });
37+
38+ test("throws when the expected text is empty", () => {
39+ expect(() => planExactTextEdit("abc", "", "x")).toThrow(
40+ "Expected text must be non-empty.",
41+ );
42+ });
43+
44+ test("throws when the expected text matches multiple locations", () => {
45+ expect(() => planExactTextEdit("x\ny\nx\n", "x", "z")).toThrow(
46+ "Expected text matched multiple locations in the file.",
47+ );
48+ });
49+});
50+
51+describe("applyExactTextEdit", () => {
52+ test("writes an exact replacement and returns a relative path", async () => {
53+ await writeFile(join(cwd, "f.txt"), "a\nb\nc\n");
54+
55+ const result = await applyExactTextEdit({
56+ cwd,
57+ path: "f.txt",
58+ oldText: "b\n",
59+ newText: "B\n",
60+ });
61+
62+ expect(result).toEqual({ path: "f.txt", changed: true });
63+ expect(await Bun.file(join(cwd, "f.txt")).text()).toBe("a\nB\nc\n");
64+ });
65+
66+ test("does not rewrite the file when the replacement is identical", async () => {
67+ await writeFile(join(cwd, "f.txt"), "same\n");
68+
69+ const result = await applyExactTextEdit({
70+ cwd,
71+ path: "f.txt",
72+ oldText: "same\n",
73+ newText: "same\n",
74+ });
75+
76+ expect(result).toEqual({ path: "f.txt", changed: false });
77+ expect(await Bun.file(join(cwd, "f.txt")).text()).toBe("same\n");
78+ });
79+
80+ test("throws a typed error when the target is not found", async () => {
81+ await writeFile(join(cwd, "f.txt"), "a\nb\n");
82+
83+ try {
84+ await applyExactTextEdit({
85+ cwd,
86+ path: "f.txt",
87+ oldText: "missing",
88+ newText: "x",
89+ });
90+ expect.unreachable("expected applyExactTextEdit to throw");
91+ } catch (error) {
92+ expect(error).toBeInstanceOf(FileEditError);
93+ expect((error as FileEditError).code).toBe("target_not_found");
94+ }
95+ });
96+});
src/internal/file-edit/exact-text.ts+105−0
@@ -0,0 +1,105 @@
1+import { resolvePath } from "./path.ts";
2+
3+export type FileEditErrorCode =
4+ | "empty_old_text"
5+ | "file_not_found"
6+ | "target_not_found"
7+ | "target_not_unique";
8+
9+export class FileEditError extends Error {
10+ constructor(
11+ readonly code: FileEditErrorCode,
12+ message: string,
13+ ) {
14+ super(message);
15+ this.name = "FileEditError";
16+ }
17+}
18+
19+interface PlannedExactTextEdit {
20+ updated: string;
21+ changed: boolean;
22+}
23+
24+interface ApplyExactTextEditInput {
25+ cwd?: string;
26+ path: string;
27+ oldText: string;
28+ newText: string;
29+}
30+
31+interface ApplyExactTextEditResult {
32+ path: string;
33+ changed: boolean;
34+}
35+
36+function findExactMatchOffsets(source: string, target: string): number[] {
37+ if (target.length === 0) {
38+ throw new FileEditError(
39+ "empty_old_text",
40+ "Expected text must be non-empty.",
41+ );
42+ }
43+
44+ const matches: number[] = [];
45+ let searchStart = 0;
46+ while (searchStart <= source.length - target.length) {
47+ const matchIndex = source.indexOf(target, searchStart);
48+ if (matchIndex === -1) break;
49+ matches.push(matchIndex);
50+ searchStart = matchIndex + 1;
51+ }
52+ return matches;
53+}
54+
55+export function planExactTextEdit(
56+ source: string,
57+ oldText: string,
58+ newText: string,
59+): PlannedExactTextEdit {
60+ const matches = findExactMatchOffsets(source, oldText);
61+ if (matches.length === 0) {
62+ throw new FileEditError(
63+ "target_not_found",
64+ "Expected text was not found in the file.",
65+ );
66+ }
67+ if (matches.length > 1) {
68+ throw new FileEditError(
69+ "target_not_unique",
70+ "Expected text matched multiple locations in the file.",
71+ );
72+ }
73+
74+ const matchIndex = matches[0] ?? 0;
75+ const updated =
76+ source.slice(0, matchIndex) +
77+ newText +
78+ source.slice(matchIndex + oldText.length);
79+
80+ return {
81+ updated,
82+ changed: updated !== source,
83+ };
84+}
85+
86+export async function applyExactTextEdit(
87+ input: ApplyExactTextEditInput,
88+): Promise<ApplyExactTextEditResult> {
89+ const { filePath, relPath } = resolvePath(input.cwd, input.path);
90+ const file = Bun.file(filePath);
91+ if (!(await file.exists())) {
92+ throw new FileEditError("file_not_found", `File not found: "${relPath}".`);
93+ }
94+
95+ const original = await file.text();
96+ const plan = planExactTextEdit(original, input.oldText, input.newText);
97+ if (plan.changed) {
98+ await Bun.write(filePath, plan.updated);
99+ }
100+
101+ return {
102+ path: relPath,
103+ changed: plan.changed,
104+ };
105+}
src/internal/file-edit/path.ts+39−0
@@ -0,0 +1,39 @@
1+import { homedir } from "node:os";
2+import { join, relative } from "node:path";
3+
4+function stripMatchingQuotes(value: string): string {
5+ if (value.length < 2) return value;
6+ const first = value[0];
7+ const last = value[value.length - 1];
8+ if ((first === '"' || first === "'") && first === last) {
9+ return value.slice(1, -1);
10+ }
11+ return value;
12+}
13+
14+function normalizePathInput(pathInput: string): string {
15+ return stripMatchingQuotes(pathInput.trim());
16+}
17+
18+interface ResolvedPath {
19+ cwd: string;
20+ filePath: string;
21+ relPath: string;
22+}
23+
24+export function resolvePath(
25+ cwdInput: string | undefined,
26+ pathInput: string,
27+): ResolvedPath {
28+ const cwd = cwdInput ?? process.cwd();
29+ const normalizedInput = normalizePathInput(pathInput);
30+ const expanded = normalizedInput.startsWith("~/")
31+ ? join(homedir(), normalizedInput.slice(2))
32+ : normalizedInput === "~"
33+ ? homedir()
34+ : normalizedInput;
35+ const filePath = expanded.startsWith("/") ? expanded : join(cwd, expanded);
36+
37+ const relPath = relative(cwd, filePath);
38+ return { cwd, filePath, relPath };
39+}
src/mc-edit.ts+5−0
@@ -0,0 +1,5 @@
1+#!/usr/bin/env bun
2+import { runFileEditCli } from "./internal/file-edit/cli.ts";
3+
4+const exitCode = await runFileEditCli(process.argv.slice(2));
5+process.exit(exitCode);
src/tools/shared.ts+2−29
@@ -1,33 +1,6 @@
1-import { homedir } from "node:os";
2-import { join, relative } from "node:path";
1+import { resolvePath } from "../internal/file-edit/path.ts";
32
4-function stripMatchingQuotes(value: string): string {
5- if (value.length < 2) return value;
6- const first = value[0];
7- const last = value[value.length - 1];
8- if ((first === '"' || first === "'") && first === last) {
9- return value.slice(1, -1);
10- }
11- return value;
12-}
13-
14-function normalizePathInput(pathInput: string): string {
15- return stripMatchingQuotes(pathInput.trim());
16-}
17-
18-export function resolvePath(cwdInput: string | undefined, pathInput: string) {
19- const cwd = cwdInput ?? process.cwd();
20- const normalizedInput = normalizePathInput(pathInput);
21- const expanded = normalizedInput.startsWith("~/")
22- ? join(homedir(), normalizedInput.slice(2))
23- : normalizedInput === "~"
24- ? homedir()
25- : normalizedInput;
26- const filePath = expanded.startsWith("/") ? expanded : join(cwd, expanded);
27-
28- const relPath = relative(cwd, filePath);
29- return { cwd, filePath, relPath };
30-}
3+export { resolvePath };
314
325 export async function resolveExistingFile(
336 cwdInput: string | undefined,