/
format-files.ts
111 lines (98 loc) · 2.73 KB
/
format-files.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import type { Tree } from 'nx/src/generators/tree';
import * as path from 'path';
import type * as Prettier from 'prettier';
import { readJson, updateJson, writeJson } from 'nx/src/generators/utils/json';
import { getWorkspacePath } from 'nx/src/generators/utils/project-configuration';
import { sortObjectByKeys } from 'nx/src/utils/object-sort';
/**
* Formats all the created or updated files using Prettier
* @param tree - the file system tree
*/
export async function formatFiles(tree: Tree): Promise<void> {
let prettier: typeof Prettier;
try {
prettier = await import('prettier');
} catch {}
sortWorkspaceJson(tree);
sortTsConfig(tree);
if (!prettier) return;
const files = new Set(
tree.listChanges().filter((file) => file.type !== 'DELETE')
);
await Promise.all(
Array.from(files).map(async (file) => {
const systemPath = path.join(tree.root, file.path);
let options: any = {
filepath: systemPath,
};
const resolvedOptions = await prettier.resolveConfig(systemPath, {
editorconfig: true,
});
if (!resolvedOptions) {
return;
}
options = {
...options,
...resolvedOptions,
};
if (file.path.endsWith('.swcrc')) {
options.parser = 'json';
}
const support = await prettier.getFileInfo(systemPath, options);
if (support.ignored || !support.inferredParser) {
return;
}
try {
tree.write(
file.path,
prettier.format(file.content.toString('utf-8'), options)
);
} catch (e) {
console.warn(`Could not format ${file.path}. Error: "${e.message}"`);
}
})
);
}
function sortWorkspaceJson(tree: Tree) {
const workspaceJsonPath = getWorkspacePath(tree);
if (!workspaceJsonPath) {
return;
}
try {
const workspaceJson = readJson(tree, workspaceJsonPath);
if (Object.entries(workspaceJson.projects).length !== 0) {
const sortedProjects = sortObjectByKeys(workspaceJson.projects);
writeJson(tree, workspaceJsonPath, {
...workspaceJson,
projects: sortedProjects,
});
}
} catch (e) {
// catch noop
}
}
function sortTsConfig(tree: Tree) {
try {
const tsConfigPath = getRootTsConfigPath(tree);
if (!tsConfigPath) {
return;
}
updateJson(tree, tsConfigPath, (tsconfig) => ({
...tsconfig,
compilerOptions: {
...tsconfig.compilerOptions,
paths: sortObjectByKeys(tsconfig.compilerOptions.paths),
},
}));
} catch (e) {
// catch noop
}
}
function getRootTsConfigPath(tree: Tree): string | null {
for (const path of ['tsconfig.base.json', 'tsconfig.json']) {
if (tree.exists(path)) {
return path;
}
}
return null;
}