2
* Copyright (c) 2024 Huawei Device Co., Ltd.
3
* Licensed under the Apache License, Version 2.0 (the "License");
4
* you may not use this file except in compliance with the License.
5
* You may obtain a copy of the License at
7
* http://www.apache.org/licenses/LICENSE-2.0
9
* Unless required by applicable law or agreed to in writing, software
10
* distributed under the License is distributed on an "AS IS" BASIS,
11
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
* See the License for the specific language governing permissions and
13
* limitations under the License.
16
import * as ts from "typescript"
17
import * as fs from "fs"
18
import * as path from "path"
19
import { GenerateOptions, GenericVisitor } from "./options"
21
export function generate<T>(
23
inputFile: string | undefined,
25
visitorFactory: (sourceFile: ts.SourceFile, typeChecker: ts.TypeChecker) => GenericVisitor<T>,
26
options: GenerateOptions<T>
28
inputDir = path.resolve(inputDir)
29
// Build a program using the set of root file names in fileNames
30
let program = ts.createProgram(inputFile ? [
31
path.join(inputDir, inputFile)
32
] : fs.readdirSync(inputDir)
33
.map(elem => path.join(inputDir, elem)).concat([path.join(__dirname, "../stdlib.d.ts")]), options.compilerOptions)
35
// Get the checker, we will use it to find more about classes
36
if (outputDir && !fs.existsSync(outputDir)) fs.mkdirSync(outputDir, { recursive: true })
38
const typeChecker = program.getTypeChecker()
39
options.onBegin?.(outputDir,typeChecker)
41
// Visit every sourceFile in the program
42
for (const sourceFile of program.getSourceFiles()) {
43
if (path.resolve(sourceFile.fileName).indexOf(inputDir) == -1) {
44
// console.log("Ignore ", path.resolve(sourceFile.fileName) , "wrt", inputDir)
47
if (inputFile && path.basename(sourceFile.fileName) != inputFile) {
51
// Walk the tree to search for classes
52
const visitor = visitorFactory(sourceFile, typeChecker)
53
const output = visitor.visitWholeFile()
55
options.onSingleFile?.(output, outputDir, sourceFile)
58
options.onEnd?.(outputDir)