Skip to content

Commit

Permalink
fix: jsonc modifier
Browse files Browse the repository at this point in the history
  • Loading branch information
tscpp committed Jun 22, 2024
1 parent 56a7d29 commit 996a254
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 30 deletions.
13 changes: 2 additions & 11 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@
"execa": "^9.2.0",
"is-ci": "^3.0.1",
"jsonc-parser": "^3.2.1",
"magic-string": "^0.30.10",
"minimatch": "^9.0.4",
"semver": "^7.6.2",
"slash": "^5.1.0"
Expand Down
26 changes: 8 additions & 18 deletions src/lib/utils/jsonc.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import * as jsonc from "jsonc-parser";
import MagicString from "magic-string";
import detectIndent from "detect-indent";
import { detectNewline } from "detect-newline";
import { readFile, writeFile } from "node:fs/promises";
Expand All @@ -15,37 +14,28 @@ export interface JSONCEdit {
}

export async function modifyJsoncFile(path: string, edits: JSONCEdit[]) {
const originalText = await readFile(path, "utf8");
const modified = new MagicString(originalText);
let text = await readFile(path, "utf8");

// Formatting
const indent = detectIndent(originalText);
const indent = detectIndent(text);
const formattingOptions: jsonc.FormattingOptions = {
eol: detectNewline(originalText) ?? "\n",
eol: detectNewline(text) ?? "\n",
tabSize: indent.amount,
insertSpaces: (indent.type ?? "space") === "space",
};

// Apply edits
const changes = edits.flatMap((edit) =>
jsonc.modify(
for (const edit of edits) {
const jsoncEdits = jsonc.modify(
//
originalText,
text,
edit.path,
edit.value,
{ formattingOptions },
),
);
for (const change of changes) {
modified.update(
//
change.offset,
change.offset + change.length,
change.content,
);
text = jsonc.applyEdits(text, jsoncEdits);
}

// Save file
const modifiedText = modified.toString();
await writeFile(path, modifiedText);
await writeFile(path, text);
}

0 comments on commit 996a254

Please sign in to comment.