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

feat: write file auto detect newline & indent #113

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 @@ -24,6 +24,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.1.1",
"pathe": "^1.1.0"
Expand Down
7 changes: 7 additions & 0 deletions pnpm-lock.yaml

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

18 changes: 13 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
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 {
findFile,
FindFileOptions,
findNearestFile,
writeJsonFile,
WriteOptions,
} from "./utils";
import type { PackageJson, TSConfig } from "./types";

export * from "./types";
Expand Down Expand Up @@ -42,9 +48,10 @@ export async function readPackageJSON(

export async function writePackageJSON(
path: string,
package_: PackageJson
package_: PackageJson,
options: WriteOptions = {}
): Promise<void> {
await fsp.writeFile(path, JSON.stringify(package_, undefined, 2));
await writeJsonFile(path, package_, options);
}

export async function readTSConfig(
Expand All @@ -68,9 +75,10 @@ export async function readTSConfig(

export async function writeTSConfig(
path: string,
tsconfig: TSConfig
tsconfig: TSConfig,
options: WriteOptions = {}
): Promise<void> {
await fsp.writeFile(path, JSON.stringify(tsconfig, undefined, 2));
await writeJsonFile(path, tsconfig, options);
}

export async function resolvePackageJSON(
Expand Down
46 changes: 45 additions & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { statSync } from "node:fs";
import { statSync, existsSync } from "node:fs";
import { readFile, writeFile } from "node:fs/promises";
import { join, resolve } from "pathe";
import detectIndent from "detect-indent";

export interface FindFileOptions {
/**
Expand Down Expand Up @@ -30,6 +32,16 @@ export interface FindFileOptions {
/** @deprecated */
export type FindNearestFileOptions = FindFileOptions;

export type WriteOptions = {
indent?: number | string;
newline?: boolean | string;
};

export type ResolvedWriteOptions = {
indent: number | string;
newline: string;
};

const defaultFindOptions: Required<FindFileOptions> = {
startingFrom: ".",
rootPattern: /^node_modules$/,
Expand Down Expand Up @@ -97,3 +109,35 @@ export function findFarthestFile(
): Promise<string> {
return findFile(filename, { ..._options, reverse: true });
}

export async function resolveWriteOptions(
path: string,
options: WriteOptions
): Promise<ResolvedWriteOptions> {
const file = existsSync(path) ? await readFile(path, "utf8") : undefined;
const indent = options.indent ?? (file ? detectIndent(file).indent : 2);
const newline =
options.newline === true
? "\n"
: options.newline === false
? ""
: options.newline ?? (file ? (file.endsWith("\n") ? "\n" : "") : "\n");

return {
indent,
newline,
};
}

export async function writeJsonFile(
path: string,
value: any,
options: WriteOptions = {}
): Promise<void> {
const resolvedOpts = await resolveWriteOptions(path, options);

let content = JSON.stringify(value, undefined, resolvedOpts.indent);
content += resolvedOpts.newline;

await writeFile(path, content);
}
32 changes: 32 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { fileURLToPath } from "node:url";
import { readFile } from "node:fs/promises";
import { dirname, resolve } from "pathe";
import { describe, expect, it } from "vitest";
import { expectTypeOf } from "expect-type";
import detectIndent from "detect-indent";
import {
readPackageJSON,
readTSConfig,
Expand Down Expand Up @@ -90,6 +92,36 @@ describe("package.json", () => {
"string"
);
});

it("write package.json with tab indent", async () => {
const path = rFixture("package.json.tab.tmp");
const indent = "\t";
await writePackageJSON(path, { version: "1.0.0" }, { indent });
const file = await readFile(path, "utf8");
expect(detectIndent(file).indent).toBe(indent);
});

it("write package.json with 4 space indent", async () => {
const path = rFixture("package.json.3space.tmp");
const indent = 4;
await writePackageJSON(path, { version: "1.0.0" }, { indent });
const file = await readFile(path, "utf8");
expect(detectIndent(file).indent).toBe(" ");
});

it("write package.json with newline", async () => {
const path = rFixture("package.json.newline.tmp");
await writePackageJSON(path, { version: "1.0.0" }, { newline: true });
const file = await readFile(path, "utf8");
expect(file.endsWith("\n")).toBe(true);
});

it("write package.json with no newline", async () => {
const path = rFixture("package.json.no-newline.tmp");
await writePackageJSON(path, { version: "1.0.0" }, { newline: false });
const file = await readFile(path, "utf8");
expect(file.endsWith("\n")).toBe(false);
});
});

describe("tsconfig.json", () => {
Expand Down