idlize

Форк
0
/
ImportsCollector.ts 
102 строки · 4.2 Кб
1
/*
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
6
 *
7
 * http://www.apache.org/licenses/LICENSE-2.0
8
 *
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.
14
 */
15

16
import * as ts from 'typescript'
17
import * as path from "path"
18
import { getOrPut, nameOrNull, renameClassToBuilderClass, renameClassToMaterialized, renameDtsToInterfaces } from "../util";
19
import { LanguageWriter } from "./LanguageWriters";
20
import { PeerLibrary } from './PeerLibrary';
21
import { isMaterialized } from './Materialized';
22
import { DeclarationNameConvertor } from './dependencies_collector';
23
import { PeerGeneratorConfig } from './PeerGeneratorConfig';
24
import { convertDeclaration } from './TypeNodeConvertor';
25
import { syntheticDeclarationFilename, isSyntheticDeclaration } from './synthetic_declaration';
26
import { isBuilderClass } from './BuilderClass';
27

28
export type ImportsCollectorFilter = (feature: string, module: string) => boolean
29

30
export class ImportsCollector {
31
    private readonly moduleToFeatures: Map<string, Set<string>> = new Map()
32
    private readonly filters: ImportsCollectorFilter[] = []
33

34
    addFeature(feature: string, module: string) {
35
        const dependencies = getOrPut(this.moduleToFeatures, module, () => new Set())
36
        dependencies.add(feature)
37
    }
38

39
    addFeatureByBasename(feature: string, basename: string) {
40
        const basenameNoExt = basename.replaceAll(path.extname(basename), '')
41
        this.addFeature(feature, `./${basenameNoExt}`)
42
    }
43

44
    addFilter(filter: ImportsCollectorFilter) {
45
        this.filters.push(filter)
46
    }
47

48
    addFilterByBasename(basename: string) {
49
        const basenameNoExt = basename.replaceAll(path.extname(basename), '')
50
        const module = `./${basenameNoExt}`
51
        this.addFilter((_, m) => m !== module)
52
    }
53

54
    print(printer: LanguageWriter) {
55
        this.moduleToFeatures.forEach((features, module) => {
56
            const filteredFeatures = Array.from(features).filter(feature => {
57
                return this.filters.every(it => it(feature, module))
58
            }).sort()
59
            if (filteredFeatures.length > 0)
60
                printer.print(`import { ${filteredFeatures.join(', ')} } from "${module}"`)
61
        })
62
    }
63
}
64

65
export type ImportFeature = { feature: string, module: string }
66

67
export function convertDeclToFeature(library: PeerLibrary, node: ts.Declaration): ImportFeature {
68
    if (isSyntheticDeclaration(node))
69
        return {
70
            feature: convertDeclaration(DeclarationNameConvertor.I, node), 
71
            module: `./${syntheticDeclarationFilename(node)}`
72
        }
73
    if (PeerGeneratorConfig.isConflictedDeclaration(node)) {
74
        const parent = node.parent
75
        let feature = ts.isModuleBlock(parent)
76
            ? parent.parent.name.text
77
            : convertDeclaration(DeclarationNameConvertor.I, node)
78
        return {
79
            feature: feature,
80
            module: './ConflictedDeclarations'
81
        }
82
    }
83

84
    if (!ts.isSourceFile(node.parent))
85
        throw "Expected parent of declaration to be a SourceFile"
86
    const originalBasename = path.basename(node.parent.fileName)
87
    let fileName = renameDtsToInterfaces(originalBasename, library.declarationTable.language)
88
    if ((ts.isInterfaceDeclaration(node) || ts.isClassDeclaration(node)) && !library.isComponentDeclaration(node)) {
89
        if (isBuilderClass(node)) {
90
            fileName = renameClassToBuilderClass(nameOrNull(node.name)!, library.declarationTable.language)
91
        } else if (isMaterialized(node)) {
92
            fileName = renameClassToMaterialized(nameOrNull(node.name)!, library.declarationTable.language)
93
        }
94
    }
95

96
    const basename = path.basename(fileName)
97
    const basenameNoExt = basename.replaceAll(path.extname(basename), '')
98
    return {
99
        feature: convertDeclaration(DeclarationNameConvertor.I, node),
100
        module: `./${basenameNoExt}`,
101
    }
102
}

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.