-
-
Notifications
You must be signed in to change notification settings - Fork 430
/
Copy pathgenerate.ts
96 lines (85 loc) · 2.39 KB
/
generate.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
import { applyEdits, modify } from 'jsonc-parser'
import { readFileSync, writeFileSync } from 'node:fs'
import { type BuiltInParserName, format } from 'prettier'
import type { Package } from './package'
import type { Path } from './path'
import { Logger } from './logger'
import { Workspace } from './workspace'
export function generateTsConfig() {
const generator = new Generator()
generator.run().catch(console.error)
}
export class Generator {
workspace: Workspace
logger: Logger
constructor() {
this.workspace = new Workspace()
this.workspace.join('tsconfig.json')
this.logger = new Logger('TS Config')
}
async run() {
this.logger.info('Generating workspace files')
await this.generateWorkspaceFiles()
this.logger.info('Workspace files generated')
}
generateWorkspaceFiles = async () => {
const filesToGenerate: [
Path,
(prev: string) => string,
BuiltInParserName?,
][] = [
[this.workspace.join('tsconfig.json'), this.genProjectTsConfig, 'json'],
...this.workspace.packages
.filter((p) => p.isTsProject)
.map(
(p) =>
[
p.join('tsconfig.json'),
this.genPackageTsConfig.bind(this, p),
'json',
] as any
),
]
for (const [path, content, formatter] of filesToGenerate) {
this.logger.info(`Generating: ${path}`)
const previous = readFileSync(path.value, 'utf-8')
let file = content(previous)
if (formatter) {
file = await this.format(file, formatter)
}
writeFileSync(path.value, file)
}
}
format = (content: string, parser: BuiltInParserName) => {
const config = JSON.parse(
readFileSync(this.workspace.join('.prettierrc').value, 'utf-8')
)
return format(content, { parser, ...config })
}
genProjectTsConfig = (prev: string) => {
return applyEdits(
prev,
modify(
prev,
['references'],
this.workspace.packages
.filter((p) => p.isTsProject)
.map((p) => ({ path: p.path.relativePath })),
{}
)
)
}
genPackageTsConfig = (pkg: Package, prev: string) => {
return applyEdits(
prev,
modify(
prev,
['references'],
pkg.deps
.filter((p) => p.isTsProject)
.map((d) => ({ path: pkg.path.relative(d.path.value) })),
{}
)
)
}
}