-
Notifications
You must be signed in to change notification settings - Fork 6
/
source.ts
102 lines (88 loc) · 2.15 KB
/
source.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
import * as path from 'path'
import { format, resolveConfig } from 'prettier'
import { SourceFile } from 'ts-morph'
import { RootContext } from '../../tools/context'
export class Source {
context: RootContext
constructor(context: RootContext) {
this.context = context
}
/**
* Generate files bases on template.
* @param tplDir Template directory
* @param destDir Destination directory
* @param files Files to be generated
* @param props Template props
*/
async generate(
tplDir: string,
destDir: string,
files: Array<GenerateFileInfo | string>,
props?: any
) {
const {
template: { generate },
filesystem: { write }
} = this.context
for (const file of files) {
const target =
typeof file === 'string'
? path.join(destDir, file)
: path.join(destDir, file.dest ? file.dest : file.source)
const sourceCode = await generate({
template: path.join(
tplDir,
`${typeof file === 'string' ? file : file.source}.ejs`
),
props
})
if (target.endsWith('ts') || target.endsWith('tsx')) {
this.prettify(target, sourceCode)
} else {
write(target, sourceCode)
}
}
}
/**
* Format source code.
* @param filepath file to save
* @param source source file contents
*/
async prettify(filepath: string, source?: string) {
const {
filesystem: { cwd, write, read }
} = this.context
if (!source) {
source = read(filepath)
}
const opt = await resolveConfig(cwd())
write(
filepath,
format(source, {
...opt,
parser: 'typescript'
})
)
}
/**
* Format sourfile with prettier
* @param sourceFile ts-morph source file
*/
async prettifySoureFile(sourceFile: SourceFile) {
const {
filesystem: { cwd }
} = this.context
sourceFile.organizeImports()
const opt = await resolveConfig(cwd())
sourceFile.replaceWithText(
format(sourceFile.getFullText(), {
...opt,
parser: 'typescript'
})
)
}
}
export interface GenerateFileInfo {
source: string
dest?: string
}