Skip to content
Closed
Show file tree
Hide file tree
Changes from 10 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
2 changes: 2 additions & 0 deletions package-lock.json

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

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@
"@types/js-yaml": "^4.0.9",
"@types/node": "^20.12.7",
"cross-env": "^7.0.3",
"dedent": "^1.5.3",
"jest": "^29.7.0",
"jest-snapshot-serializer-ansi": "^2.1.0",
"jest-snapshot-serializer-raw": "^2.0.0",
Expand Down
14 changes: 7 additions & 7 deletions src/config_editorconfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ import { fastJoinedPath, findLastIndex, isUndefined, memoize, noop, zipObjectUnl
import type { Config, ConfigWithOverrides } from "tiny-editorconfig";
import type { FormatOptions, PromiseMaybe } from "./types.js";

const getEditorConfig = memoize((folderPath: string, filesNames: string[]): PromiseMaybe<ConfigWithOverrides | undefined> => {
const getEditorConfig = memoize((folderPath: string, filesNames: string[], ignoreKnown?: boolean): PromiseMaybe<ConfigWithOverrides | undefined> => {
for (let i = 0, l = filesNames.length; i < l; i++) {
const fileName = filesNames[i];
const filePath = fastJoinedPath(folderPath, fileName);
if (!Known.hasFilePath(filePath)) continue;
if (!ignoreKnown && !Known.hasFilePath(filePath)) continue;
Copy link
Copy Markdown
Contributor Author

@pralkarz pralkarz Apr 23, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not a huge fan as ignoreKnown needs to be passed through multiple hoops before it ends up here, but I'm not sure how else we could solve this (getStdin doesn't populate Known, and so we'd always end up not reading any config).

I'm also not sure whether this impacts performance, i.e. the whole chain – not populating Known in runStdin and resolving the configs without it.

return fs.readFile(filePath, "utf8").then(EditorConfig.parse).catch(noop);
}
});
Expand All @@ -21,18 +21,18 @@ const getEditorConfigsMap = async (foldersPaths: string[], filesNames: string[])
return map;
};

const getEditorConfigsUp = memoize(async (folderPath: string, filesNames: string[]): Promise<ConfigWithOverrides[]> => {
const config = await getEditorConfig(folderPath, filesNames);
const getEditorConfigsUp = memoize(async (folderPath: string, filesNames: string[], ignoreKnown?: boolean): Promise<ConfigWithOverrides[]> => {
const config = await getEditorConfig(folderPath, filesNames, ignoreKnown);
const folderPathUp = path.dirname(folderPath);
const configsUp = folderPath !== folderPathUp ? await getEditorConfigsUp(folderPathUp, filesNames) : [];
const configsUp = folderPath !== folderPathUp ? await getEditorConfigsUp(folderPathUp, filesNames, ignoreKnown) : [];
const configs = config ? [...configsUp, config] : configsUp;
const lastRootIndex = findLastIndex(configs, (config) => config.root);
return lastRootIndex > 0 ? configs.slice(lastRootIndex) : configs;
});

const getEditorConfigResolved = async (filePath: string, filesNames: string[]): Promise<Config> => {
const getEditorConfigResolved = async (filePath: string, filesNames: string[], ignoreKnown?: boolean): Promise<Config> => {
const folderPath = path.dirname(filePath);
const configs = await getEditorConfigsUp(folderPath, filesNames);
const configs = await getEditorConfigsUp(folderPath, filesNames, ignoreKnown);
const config = EditorConfig.resolve(configs, filePath);
return config;
};
Expand Down
22 changes: 11 additions & 11 deletions src/config_ignore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@ import Known from "./known.js";
import { fastJoinedPath, fastRelativeChildPath, isString, isUndefined, memoize, noop, someOf, zipObjectUnless } from "./utils.js";
import type { Ignore, PromiseMaybe } from "./types.js";

const getIgnoreContent = (folderPath: string, fileName: string): PromiseMaybe<string | undefined> => {
const getIgnoreContent = (folderPath: string, fileName: string, ignoreKnown?: boolean): PromiseMaybe<string | undefined> => {
const filePath = fastJoinedPath(folderPath, fileName);
if (!Known.hasFilePath(filePath)) return;
if (!ignoreKnown && !Known.hasFilePath(filePath)) return;
return fs.readFile(filePath, "utf8").catch(noop);
};

const getIgnoresContent = memoize(async (folderPath: string, filesNames: string[]): Promise<string[] | undefined> => {
const contentsRaw = await Promise.all(filesNames.map((fileName) => getIgnoreContent(folderPath, fileName)));
const getIgnoresContent = memoize(async (folderPath: string, filesNames: string[], ignoreKnown?: boolean): Promise<string[] | undefined> => {
const contentsRaw = await Promise.all(filesNames.map((fileName) => getIgnoreContent(folderPath, fileName, ignoreKnown)));
const contents = contentsRaw.filter(isString);
if (!contents.length) return;
return contents;
Expand All @@ -39,26 +39,26 @@ const getIgnoreBys = (foldersPaths: string[], filesContents: string[][]): Ignore
return ignore;
};

const getIgnores = memoize(async (folderPath: string, filesNames: string[]): Promise<Ignore | undefined> => {
const contents = await getIgnoresContent(folderPath, filesNames);
const getIgnores = memoize(async (folderPath: string, filesNames: string[], ignoreKnown?: boolean): Promise<Ignore | undefined> => {
const contents = await getIgnoresContent(folderPath, filesNames, ignoreKnown);
if (!contents?.length) return;
const ignore = getIgnoreBy(folderPath, contents);
return ignore;
});

const getIgnoresUp = memoize(async (folderPath: string, filesNames: string[]): Promise<Ignore | undefined> => {
const ignore = await getIgnores(folderPath, filesNames);
const getIgnoresUp = memoize(async (folderPath: string, filesNames: string[], ignoreKnown?: boolean): Promise<Ignore | undefined> => {
const ignore = await getIgnores(folderPath, filesNames, ignoreKnown);
const folderPathUp = path.dirname(folderPath);
const ignoreUp = folderPath !== folderPathUp ? await getIgnoresUp(folderPathUp, filesNames) : undefined;
const ignoreUp = folderPath !== folderPathUp ? await getIgnoresUp(folderPathUp, filesNames, ignoreKnown) : undefined;
const ignores = ignore ? (ignoreUp ? [ignore, ignoreUp] : [ignore]) : ignoreUp ? [ignoreUp] : [];
if (!ignores.length) return;
const ignoreAll = someOf(ignores);
return ignoreAll;
});

const getIgnoreResolved = async (filePath: string, filesNames: string[]): Promise<boolean> => {
const getIgnoreResolved = async (filePath: string, filesNames: string[], ignoreKnown?: boolean): Promise<boolean> => {
const folderPath = path.dirname(filePath);
const ignore = await getIgnoresUp(folderPath, filesNames);
const ignore = await getIgnoresUp(folderPath, filesNames, ignoreKnown);
const ignored = !!ignore?.(filePath);
return ignored;
};
Expand Down
28 changes: 15 additions & 13 deletions src/config_prettier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,38 +94,40 @@ const Ext2Loader: Record<string, (filePath: string) => Promise<unknown>> = {
mjs: Loaders.js,
};

const getPrettierConfig = (folderPath: string, fileName: string): PromiseMaybe<PrettierConfigWithOverrides | undefined> => {
const getPrettierConfig = (folderPath: string, fileName: string, ignoreKnown?: boolean): PromiseMaybe<PrettierConfigWithOverrides | undefined> => {
const filePath = fastJoinedPath(folderPath, fileName);
if (!Known.hasFilePath(filePath)) return;
if (!ignoreKnown && !Known.hasFilePath(filePath)) return;
const loader = File2Loader[fileName] || File2Loader["default"];
const normalize = (config: unknown) => (isObject(config) ? { ...config, ...normalizePrettierOptions(config, folderPath) } : undefined);
return loader(filePath).then(normalize).catch(noop);
};

const getPrettierConfigs = memoize(async (folderPath: string, filesNames: string[]): Promise<PrettierConfigWithOverrides[] | undefined> => {
const configsRaw = await Promise.all(filesNames.map((fileName) => getPrettierConfig(folderPath, fileName)));
const configs = configsRaw.filter(isTruthy);
if (!configs.length) return;
return configs;
});
const getPrettierConfigs = memoize(
async (folderPath: string, filesNames: string[], ignoreKnown: boolean = false): Promise<PrettierConfigWithOverrides[] | undefined> => {
const configsRaw = await Promise.all(filesNames.map((fileName) => getPrettierConfig(folderPath, fileName, ignoreKnown)));
const configs = configsRaw.filter(isTruthy);
if (!configs.length) return;
return configs;
},
);

const getPrettierConfigsMap = async (foldersPaths: string[], filesNames: string[]): Promise<Partial<Record<string, PrettierConfig[]>>> => {
const configs = await Promise.all(foldersPaths.map((folderPath) => getPrettierConfigs(folderPath, filesNames)));
const map = zipObjectUnless(foldersPaths, configs, isUndefined);
return map;
};

const getPrettierConfigsUp = memoize(async (folderPath: string, filesNames: string[]): Promise<PrettierConfigWithOverrides[]> => {
const config = (await getPrettierConfigs(folderPath, filesNames))?.[0];
const getPrettierConfigsUp = memoize(async (folderPath: string, filesNames: string[], ignoreKnown: boolean = false): Promise<PrettierConfigWithOverrides[]> => {
const config = (await getPrettierConfigs(folderPath, filesNames, ignoreKnown))?.[0];
const folderPathUp = path.dirname(folderPath);
const configsUp = folderPath !== folderPathUp ? await getPrettierConfigsUp(folderPathUp, filesNames) : [];
const configsUp = folderPath !== folderPathUp ? await getPrettierConfigsUp(folderPathUp, filesNames, ignoreKnown) : [];
const configs = config ? [...configsUp, config] : configsUp;
return configs;
});

const getPrettierConfigResolved = async (filePath: string, filesNames: string[]): Promise<PrettierConfig> => {
const getPrettierConfigResolved = async (filePath: string, filesNames: string[], ignoreKnown?: boolean): Promise<PrettierConfig> => {
const folderPath = path.dirname(filePath);
const configs = await getPrettierConfigsUp(folderPath, filesNames);
const configs = await getPrettierConfigsUp(folderPath, filesNames, ignoreKnown);
let resolved: PrettierConfig = {};

for (let ci = 0, cl = configs.length; ci < cl; ci++) {
Expand Down
20 changes: 18 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { fastRelativePath, isNull, isString, isUndefined, negate, pluralize, tri
import type { FormatOptions, Options, PluginsOptions } from "./types.js";

async function run(options: Options, pluginsDefaultOptions: PluginsOptions, pluginsCustomOptions: PluginsOptions): Promise<void> {
if (options.globs.length || !isString(await getStdin())) {
if (options.globs.length || (!isString(await getStdin()) && !("stdinFilepath" in options))) {
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you explain this one?

if there is stdin and there is a stdinFilepath, we now runGlobs?

and if there's no stdin but there is a stdinFilepath, we'd also runGlobs?

unless im reading wrong, thats what its doing now

Copy link
Copy Markdown
Contributor Author

@pralkarz pralkarz May 7, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I based this branch on yours, you seem to have added this condition in 585f1be. Not really sure what the rationale was, but it seems to make sense, right? We runGlobs either when options.globs is not empty or there's no stdinFilepath in options AND there's no stdin data.

Copy link
Copy Markdown
Collaborator

@43081j 43081j May 7, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if there's no stdinFilePath but there is stdin, we'll now call runStdin i think?

so i probably got this condition wrong. i don't remember why i did it that way

if there's no stdin or there's globs, we should runGlobs. otherwise, we can runStdin

return runGlobs(options, pluginsDefaultOptions, pluginsCustomOptions);
} else {
return runStdin(options, pluginsDefaultOptions, pluginsCustomOptions);
Expand All @@ -31,8 +31,24 @@ async function runStdin(options: Options, pluginsDefaultOptions: PluginsOptions,
const fileName = options.stdinFilepath || "stdin";
const fileContent = (await getStdin()) || "";

const ignoreNames = options.ignore ? [".gitignore", ".prettierignore"] : [];
const isIgnored = await getIgnoreResolved(fileName, ignoreNames, true);
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The logic is a bit more involved in runGlobs, but we don't have a way to explicitly include a file when handling the stdin case, so it's quite simplified.

if (isIgnored) {
stdout.always(trimFinalNewline(fileContent));
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This matches the v3 behavior based on the related test case, where the ignored file gets output as is.

process.exitCode = 0;
return;
}

const editorConfigNames = options.editorConfig ? [".editorconfig"] : [];
const editorConfig = options.editorConfig ? getEditorConfigFormatOptions(await getEditorConfigResolved(fileName, editorConfigNames, true)) : {};

const prettierConfigNames = options.config ? without(Object.keys(File2Loader), ["default"]) : [];
const prettierConfig = options.config ? await getPrettierConfigResolved(fileName, prettierConfigNames, true) : {};

const formatOptions = { ...editorConfig, ...prettierConfig, ...options.formatOptions };

try {
const formatted = await prettier.format(fileName, fileContent, options.formatOptions, options.contextOptions, pluginsDefaultOptions, pluginsCustomOptions);
const formatted = await prettier.format(fileName, fileContent, formatOptions, options.contextOptions, pluginsDefaultOptions, pluginsCustomOptions);
if (options.check || options.list) {
if (formatted !== fileContent) {
stdout.warn("(stdin)");
Expand Down
8 changes: 7 additions & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ function fastRelativeChildPath(fromPath: string, toPath: string): string | undef
return toPath.slice(fromPath.length + 1);
}
}

if (fromPath === ".") {
return toPath;
}
}

function findLastIndex<T>(array: T[], predicate: (value: T, index: number, array: T[]) => unknown): number {
Expand Down Expand Up @@ -343,7 +347,9 @@ async function normalizeOptions(options: unknown, targets: unknown[]): Promise<O

const stdin = await getStdin();

if (!isString(stdin) && !globs.length) exit("Expected at least one target file/dir/glob");
if (!isString(stdin) && !globs.length && !("stdinFilepath" in options)) {
exit("Expected at least one target file/dir/glob");
}

const check = "check" in options && !!options.check;
const list = "listDifferent" in options && !!options.listDifferent;
Expand Down
18 changes: 18 additions & 0 deletions test/__fixtures__/editorconfig/.editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
root = true

[*.js]
indent_style = tab
tab_width = 8
indent_size = 2 # overridden by tab_width since indent_style = tab
max_line_length = 100

# Indentation override for all JS under lib directory
[lib/**.js]
indent_style = space
indent_size = 2

[lib/indent_size=tab.js]
indent_size = tab

[tab_width=unset.js]
tab_width = unset
8 changes: 8 additions & 0 deletions test/__fixtures__/editorconfig/.prettierrc
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In Prettier v3, this file lives in a bigger overarching fixture directory (config), but it's needed for the snapshots to match what we expect. We could consider removing it, but then we need to update the snapshots to include semicolons.

Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
endOfLine: 'auto'
overrides:
- files: "**/*.js"
Copy link
Copy Markdown
Contributor Author

@pralkarz pralkarz Apr 23, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In Prettier v3, this is just "*.js", but a/a/a/a/a/a/three.js matches that there somehow (maybe they do some exploding to include the leading **?). Since we usually provide nested paths in --stdin-path, the overrides wouldn't apply without **/.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

prettier treats *.ext as **/*.ext. not through any exploding/splitting, it just prepends it iirc

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this something that we should do in v4 too or rather require the users to handle it explicitly?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

there was a conversation a while back around it. im not sure if it was in discord or on here
but iirc, fisker's opinion was that it makes patterns easier to write (*.ts to format all ts files is easier than **/*.ts). even though it isn't the right glob

we should probably discuss it again and make a decision

options:
semi: false
- files: "**/*.ts"
options:
semi: true
3 changes: 3 additions & 0 deletions test/__fixtures__/editorconfig/file.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
function f() {
console.log("should have tab width 8");
}
3 changes: 3 additions & 0 deletions test/__fixtures__/editorconfig/lib/file.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
function f() {
console.log("should have space width 2");
}
3 changes: 3 additions & 0 deletions test/__fixtures__/editorconfig/lib/indent_size=tab.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
function f() {
console.log("should have space width 8");
}
2 changes: 2 additions & 0 deletions test/__fixtures__/editorconfig/repo-root/.hg/.gitkeep
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
This isn't really a Mercurial repo, but we want to pretend it is for testing purposes.
See https://github.com/prettier/prettier/pull/3559#issuecomment-353857109
3 changes: 3 additions & 0 deletions test/__fixtures__/editorconfig/repo-root/file.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
function f() {
console.log("should have space width 2 despite ../.editorconfig specifying 8, because ./.hg is present");
}
1 change: 1 addition & 0 deletions test/__fixtures__/stdin-ignore/.prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ignore/
85 changes: 85 additions & 0 deletions test/__tests__/__snapshots__/stdin-filepath.js.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`apply editorconfig for stdin-filepath with a deep path (stderr) 1`] = `""`;

exports[`apply editorconfig for stdin-filepath with a deep path (stderr) 2`] = `""`;

exports[`apply editorconfig for stdin-filepath with a deep path (stdout) 1`] = `
"function f() {
console.log("should be indented with a tab")
}"
`;

exports[`apply editorconfig for stdin-filepath with a deep path (stdout) 2`] = `
"function f() {
console.log("should be indented with a tab")
}"
`;

exports[`apply editorconfig for stdin-filepath with a deep path (write) 1`] = `[]`;

exports[`apply editorconfig for stdin-filepath with a deep path (write) 2`] = `[]`;

exports[`apply editorconfig for stdin-filepath with nonexistent directory (stderr) 1`] = `""`;

exports[`apply editorconfig for stdin-filepath with nonexistent directory (stdout) 1`] = `
"function f() {
console.log("should be indented with a tab")
}"
`;

exports[`apply editorconfig for stdin-filepath with nonexistent directory (write) 1`] = `[]`;

exports[`apply editorconfig for stdin-filepath with nonexistent file (stderr) 1`] = `""`;

exports[`apply editorconfig for stdin-filepath with nonexistent file (stdout) 1`] = `
"function f() {
console.log("should be indented with a tab")
}"
`;

exports[`apply editorconfig for stdin-filepath with nonexistent file (write) 1`] = `[]`;

exports[`don't apply editorconfig outside project for stdin-filepath with nonexistent directory (stderr) 1`] = `""`;

exports[`don't apply editorconfig outside project for stdin-filepath with nonexistent directory (stdout) 1`] = `
"function f() {
console.log("should be indented with 2 spaces");
}"
`;

exports[`don't apply editorconfig outside project for stdin-filepath with nonexistent directory (write) 1`] = `[]`;

exports[`format correctly if stdin content compatible with stdin-filepath (stderr) 1`] = `""`;

exports[`format correctly if stdin content compatible with stdin-filepath (stdout) 1`] = `
".name {
display: none;
}"
`;

exports[`format correctly if stdin content compatible with stdin-filepath (write) 1`] = `[]`;

exports[`gracefully handle stdin-filepath with nonexistent directory (stderr) 1`] = `""`;

exports[`gracefully handle stdin-filepath with nonexistent directory (stdout) 1`] = `
".name {
display: none;
}"
`;

exports[`gracefully handle stdin-filepath with nonexistent directory (write) 1`] = `[]`;

exports[`output file as-is if stdin-filepath matched patterns in ignore-path (stderr) 1`] = `""`;

exports[`output file as-is if stdin-filepath matched patterns in ignore-path (write) 1`] = `[]`;

exports[`throw error if stdin content incompatible with stdin-filepath (stderr) 1`] = `
"[error] SyntaxError: Unexpected token (1:1)
[error] > 1 | .name { display: none; }
[error] | ^"
`;

exports[`throw error if stdin content incompatible with stdin-filepath (stdout) 1`] = `""`;

exports[`throw error if stdin content incompatible with stdin-filepath (write) 1`] = `[]`;
Loading
Loading