-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
format_file.ts
49 lines (45 loc) 路 1.35 KB
/
format_file.ts
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
import prettier from 'prettier';
import {extname} from 'node:path';
import {load_package_json} from './package_json.js';
let cached_base_options: prettier.Options | undefined;
/**
* Formats a file with Prettier.
* @param content
* @param options
* @param base_options - defaults to the the cwd's package.json `prettier` value
*/
export const format_file = async (
content: string,
options: prettier.Options,
base_options: prettier.Options | null | undefined = cached_base_options,
): Promise<string> => {
const final_base_options =
base_options !== undefined
? base_options
: (cached_base_options = (await load_package_json()).prettier as any);
let final_options = options;
if (options.filepath && !options.parser) {
const {filepath, ...rest} = options;
const parser = infer_parser(filepath);
if (parser) final_options = {...rest, parser};
}
try {
return await prettier.format(content, {...final_base_options, ...final_options});
} catch (err) {
return content;
}
};
// This is just a simple convenience for callers so they can pass a file path.
// They can provide the Prettier `options.parser` for custom extensions.
const infer_parser = (path: string): string | null => {
const extension = extname(path).substring(1);
switch (extension) {
case 'svelte':
case 'xml': {
return extension;
}
default: {
return null;
}
}
};