Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: preserve package.json indent & EOF newline #158

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"test:types": "tsc --noEmit --module esnext --skipLibCheck --moduleResolution node ./test/*.test.ts"
},
"dependencies": {
"detect-indent": "^7.0.1",
"jsonc-parser": "^3.2.0",
"mlly": "^1.4.2",
"pathe": "^1.1.1"
Expand Down
20 changes: 10 additions & 10 deletions pnpm-lock.yaml

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

31 changes: 21 additions & 10 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { promises as fsp } from "node:fs";
import { dirname, resolve, isAbsolute } from "pathe";
import { ResolveOptions as _ResolveOptions, resolvePath } from "mlly";
import { findFile, FindFileOptions, findNearestFile } from "./utils";
import type { PackageJson, TSConfig } from "./types";
import detectIndent from "detect-indent";
import { detectNewline, findFile, FindFileOptions, findNearestFile } from "./utils";
import type { PackageJsonFile, TSConfig } from "./types";

export * from "./types";
export * from "./utils";
Expand All @@ -12,7 +13,7 @@ export type ReadOptions = {
cache?: boolean | Map<string, Record<string, any>>;
};

export function definePackageJSON(package_: PackageJson): PackageJson {
export function definePackageJSON(package_: PackageJsonFile): PackageJsonFile {
return package_;
}

Expand All @@ -25,26 +26,36 @@ const FileCache = new Map<string, Record<string, any>>();
export async function readPackageJSON(
id?: string,
options: ResolveOptions & ReadOptions = {}
): Promise<PackageJson> {
): Promise<PackageJsonFile & PackageJsonFile> {
const resolvedPath = await resolvePackageJSON(id, options);
const cache =
options.cache && typeof options.cache !== "boolean"
? options.cache
: FileCache;
if (options.cache && cache.has(resolvedPath)) {
return cache.get(resolvedPath)!;
return cache.get(resolvedPath)! as PackageJsonFile & PackageJsonFile;
}
const blob = await fsp.readFile(resolvedPath, "utf8");
const parsed = JSON.parse(blob) as PackageJson;
cache.set(resolvedPath, parsed);
return parsed;
const meta = {
indent: detectIndent(blob).indent,
newline: detectNewline(blob),
};
const parsed = JSON.parse(blob) as PackageJsonFile;
const file = { ...parsed, ...meta };
cache.set(resolvedPath, file);
return file;
}

export async function writePackageJSON(
path: string,
package_: PackageJson
package_: PackageJsonFile & PackageJsonFile
): Promise<void> {
await fsp.writeFile(path, JSON.stringify(package_, undefined, 2));
const { indent, newline, ...data } = package_;
let json = JSON.stringify(data, undefined, indent);
if (newline) {
json += newline;
}
await fsp.writeFile(path, json);
}

export async function readTSConfig(
Expand Down
5 changes: 5 additions & 0 deletions src/types/packagejson.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,3 +157,8 @@ export interface PackageJson {
workspaces?: string[];
[key: string]: any;
}

export type PackageJsonFile = {
indent?: string;
newline?: string | undefined;
} & PackageJson;
14 changes: 14 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,20 @@ const defaultFindOptions: Required<FindFileOptions> = {
},
};

export function detectNewline(str: string) {
if (typeof str !== 'string') {
throw new TypeError('Expected a string');
}
const newlines = str.match(/(?:\r?\n)/g) || [];
if (newlines.length === 0) {
return;
}
const crlf = newlines.filter(newline => newline === '\r\n').length;
const lf = newlines.length - crlf;

return crlf > lf ? '\r\n' : '\n';
}

export async function findFile(
filename: string,
_options: FindFileOptions = {}
Expand Down
22 changes: 22 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,28 @@ describe("package.json", () => {
).to.equal("1.0.0");
});

it("correctly indents package.json", async () => {
const indent = " ";
await writePackageJSON(rFixture("package.json.tmp"), {
version: "1.0.0",
indent,
});
expect(
(await readPackageJSON(rFixture("package.json.tmp"))).indent
).to.equal(indent);
});

it("correctly adds EOF newline to package.json", async () => {
const newline = "\n";
await writePackageJSON(rFixture("package.json.tmp"), {
version: "1.0.0",
newline,
});
expect(
(await readPackageJSON(rFixture("package.json.tmp"))).newline
).to.equal(newline);
});

it("correctly reads a version from absolute path", async () => {
expect(
await readPackageJSON(rFixture(".")).then((p) => p?.version)
Expand Down