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

chore: statements in format #1598

Merged
merged 3 commits into from
Dec 17, 2024
Merged
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
27 changes: 27 additions & 0 deletions src/cli/format.helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2023-Present The Pepr Authors

import { ESLint } from "eslint";
import { promises as fs } from "fs";
import { format, resolveConfig } from "prettier";

export async function formatWithPrettier(
results: ESLint.LintResult[],
validateOnly: boolean,
): Promise<boolean> {
let hasFailure = false;
for (const { filePath } of results) {
const content = await fs.readFile(filePath, "utf8");
const cfg = await resolveConfig(filePath);
const formatted = await format(content, { filepath: filePath, ...cfg });

// If in validate-only mode, check if the file is formatted correctly
if (validateOnly && formatted !== content) {
hasFailure = true;
console.error(`File ${filePath} is not formatted correctly`);
} else {
await fs.writeFile(filePath, formatted);
}
}
return hasFailure;
}
75 changes: 75 additions & 0 deletions src/cli/format.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2023-Present The Pepr Authors

import { jest, describe, it, expect, beforeEach } from "@jest/globals";
import { formatWithPrettier } from "./format.helpers";
import { promises as fs } from "fs";
import { resolveConfig, format } from "prettier";
import { ESLint } from "eslint";

jest.mock("fs", () => ({
promises: {
readFile: jest.fn(),
writeFile: jest.fn(),
},
}));

jest.mock("prettier", () => ({
resolveConfig: jest.fn(),
format: jest.fn(),
}));

describe("formatWithPrettier", () => {
const mockReadFile = fs.readFile as jest.MockedFunction<typeof fs.readFile>;
const mockWriteFile = fs.writeFile as jest.MockedFunction<typeof fs.writeFile>;
const mockResolveConfig = resolveConfig as jest.MockedFunction<typeof resolveConfig>;
const mockFormat = format as jest.MockedFunction<typeof format>;

const mockResults: ESLint.LintResult[] = [
{ filePath: "package.json" } as ESLint.LintResult,
{ filePath: "hello-pepr.ts" } as ESLint.LintResult,
cmwylie19 marked this conversation as resolved.
Show resolved Hide resolved
];

beforeEach(() => {
jest.clearAllMocks();
});

it("should format files and write back to the file system", async () => {
mockReadFile.mockResolvedValue("const x =1;");
mockResolveConfig.mockResolvedValue({ semi: true });
mockFormat.mockResolvedValue("const x = 1;");

const validateOnly = false;

const result = await formatWithPrettier(mockResults, validateOnly);

expect(result).toBe(false);
expect(mockReadFile).toHaveBeenCalledTimes(2);
expect(mockWriteFile).toHaveBeenCalledTimes(2);
expect(mockFormat).toHaveBeenCalledTimes(2);

expect(mockWriteFile).toHaveBeenCalledWith("package.json", "const x = 1;");
expect(mockWriteFile).toHaveBeenCalledWith("hello-pepr.ts", "const x = 1;");
});

it("should report failures in validate-only mode if files are not formatted", async () => {
mockReadFile.mockResolvedValue("const x =1;");
mockResolveConfig.mockResolvedValue({ semi: true });
mockFormat.mockResolvedValue("const x = 1;");

const validateOnly = true;

const mockError = jest.spyOn(console, "error").mockImplementation(() => {
return undefined as never;
});
const result = await formatWithPrettier(mockResults, validateOnly);

expect(result).toBe(true);
expect(mockReadFile).toHaveBeenCalledTimes(2);
expect(mockWriteFile).not.toHaveBeenCalled();
expect(mockError).toHaveBeenCalledWith("File package.json is not formatted correctly");
expect(mockError).toHaveBeenCalledWith("File hello-pepr.ts is not formatted correctly");

mockError.mockRestore();
});
});
18 changes: 2 additions & 16 deletions src/cli/format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@
// SPDX-FileCopyrightText: 2023-Present The Pepr Authors

import { ESLint } from "eslint";
import { promises as fs } from "fs";
import { format, resolveConfig } from "prettier";
import { formatWithPrettier } from "./format.helpers";

import { RootCmd } from "./root";

Expand Down Expand Up @@ -56,20 +55,7 @@ export async function peprFormat(validateOnly: boolean): Promise<boolean> {
await ESLint.outputFixes(results);
}

// Format with Prettier
for (const { filePath } of results) {
const content = await fs.readFile(filePath, "utf8");
const cfg = await resolveConfig(filePath);
const formatted = await format(content, { filepath: filePath, ...cfg });

// If in validate-only mode, check if the file is formatted correctly
if (validateOnly && formatted !== content) {
hasFailure = true;
console.error(`File ${filePath} is not formatted correctly`);
} else {
await fs.writeFile(filePath, formatted);
}
}
hasFailure = await formatWithPrettier(results, validateOnly);

return !hasFailure;
} catch (e) {
Expand Down
Loading