forked from angular/angular-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprettier.ts
More file actions
73 lines (64 loc) · 1.72 KB
/
prettier.ts
File metadata and controls
73 lines (64 loc) · 1.72 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
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { execFile } from 'node:child_process';
import { readFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
import { dirname, extname, join, relative } from 'node:path';
import { promisify } from 'node:util';
const execFileAsync = promisify(execFile);
let prettierCliPath: string | null | undefined;
/**
* File types that can be formatted using Prettier.
*/
const fileTypes: ReadonlySet<string> = new Set([
'.ts',
'.html',
'.js',
'.mjs',
'.cjs',
'.json',
'.css',
'.less',
'.scss',
'.sass',
]);
/**
* Formats files using Prettier.
* @param cwd The current working directory.
* @param files The files to format.
*/
export async function formatFiles(cwd: string, files: Set<string>): Promise<void> {
if (!files.size) {
return;
}
if (prettierCliPath === undefined) {
try {
const prettierPath = createRequire(cwd + '/').resolve('prettier/package.json');
const prettierPackageJson = JSON.parse(await readFile(prettierPath, 'utf-8')) as {
bin: string;
};
prettierCliPath = join(dirname(prettierPath), prettierPackageJson.bin);
} catch {
// Prettier is not installed.
prettierCliPath = null;
}
}
if (!prettierCliPath) {
return;
}
const filesToFormat: string[] = [];
for (const file of files) {
if (fileTypes.has(extname(file))) {
filesToFormat.push(relative(cwd, file));
}
}
if (!filesToFormat.length) {
return;
}
await execFileAsync(prettierCliPath, ['--write', ...filesToFormat], { cwd });
}