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

Add --check and --format actions #785

Merged
merged 1 commit into from
Jan 4, 2025
Merged
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
36 changes: 30 additions & 6 deletions src/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import type Prettier from "prettier";
import { promisify } from "node:util";
import { readdir } from "node:fs/promises";

type Task = "check" | "format";

type CliOptions = {
[key: string]: boolean | number | string | undefined;
config?: false | string;
Expand Down Expand Up @@ -130,9 +132,12 @@ const defaultCLIArguments: CLIArguments = {
ignorePath: ".prettierignore",
};

function parseCLIArguments(args: string[]): [CLIArguments, string, CliOptions] {
function parseCLIArguments(
args: string[],
): [CLIArguments, string, Task, CliOptions] {
const parsedArguments: CLIArguments = { ...defaultCLIArguments };
let fileName: string | null = null;
let task: Task = "format";

const optionArgs: string[] = [];

Expand All @@ -153,6 +158,14 @@ function parseCLIArguments(args: string[]): [CLIArguments, string, CliOptions] {
parsedArguments.ignorePath = nextArg.value;
break;
}
case "--check": {
task = "check";
break;
}
case "--format": {
task = "format";
break;
}
default: {
optionArgs.push(arg);
}
Expand All @@ -170,7 +183,7 @@ function parseCLIArguments(args: string[]): [CLIArguments, string, CliOptions] {
throw new Error("File name must be provided as an argument");
}

return [parsedArguments, fileName, argsToOptions(optionArgs)];
return [parsedArguments, fileName, task, argsToOptions(optionArgs)];
}

type InvokeArgs = {
Expand All @@ -186,6 +199,7 @@ async function run(
const [
{ ignorePath },
fileName,
task,
{ config, configPrecedence, editorconfig, ...cliOptions },
] = parseCLIArguments(args);
const env = { ...process.env, ...clientEnv };
Expand Down Expand Up @@ -213,10 +227,20 @@ async function run(
? { ...cliOptions, ...fileOptions }
: { ...fileOptions, ...cliOptions };

return prettier.format(text, {
...options,
filepath: fullPath,
});
switch (task) {
case "format":
return await prettier.format(text, {
...options,
filepath: fullPath,
});
case "check":
const valid = await prettier.check(text, {
...options,
filepath: fullPath,
});
if (!valid) throw `Invalid formatting: ${fullPath}`;
return "";
}
}

export type DebugInfo = {
Expand Down