-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathformat.ts
More file actions
60 lines (51 loc) · 1.55 KB
/
Copy pathformat.ts
File metadata and controls
60 lines (51 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Derived from @prettier/cli, see THIRD_PARTY_NOTICES.md
import {
format,
getFileInfo,
type FileInfoOptions,
type Options as PrettierOptions,
} from 'prettier';
import { getPrettierPlugins } from './prettierPlugins.ts';
import type { FmtFileRequest } from './types.ts';
type PrettierPlugins = NonNullable<PrettierOptions['plugins']>;
type FormatFmtSourceResult =
| { status: 'unsupported' }
| { status: 'formatted'; source: string; formatted: string };
const fileInfoOptions = {
ignorePath: [],
resolveConfig: false,
withNodeModules: true,
} satisfies FileInfoOptions;
/** Uses the configured parser or infers one without loading Prettier config. */
const resolveFmtParser = async (
filePath: string,
options: PrettierOptions,
plugins: PrettierPlugins,
): Promise<PrettierOptions['parser'] | null> =>
options.parser ??
(
await getFileInfo(filePath, {
...fileInfoOptions,
plugins,
})
).inferredParser;
/** Formats file contents, requesting the source only once a parser is known. */
const formatFmtSource = async (
{ path, options }: FmtFileRequest,
readSource: () => string,
): Promise<FormatFmtSourceResult> => {
const plugins = await getPrettierPlugins(options, path);
const parser = await resolveFmtParser(path, options, plugins);
if (!parser) {
return { status: 'unsupported' };
}
const source = readSource();
const formatted = await format(source, {
...options,
filepath: path,
parser,
plugins,
});
return { status: 'formatted', source, formatted };
};
export { formatFmtSource };