idlize

Форк
0
232 строки · 6.8 Кб
1
/*
2
 * Copyright (c) 2022-2023 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 path from 'path'
17
import * as fs from 'fs'
18
import { assert } from "chai"
19
import * as child from "child_process"
20

21
export function testsForDirectories(goldenDir: string, otherDir: string) {
22
    const files = collectFiles(goldenDir)
23
    console.log(files)
24

25
    return files.map(file => () => test(file, () => {
26
        const golden = path.resolve(goldenDir, file)
27
        const other = path.resolve(otherDir, file)
28
        assertEqualFiles(golden, other)
29
    }))
30
}
31

32
export function assertGeneratedEqualsGolden(filename: string) {
33
    const goldenFile = path.resolve("./test/golden", filename)
34
    const generatedFile = path.resolve("./test/generated", filename)
35
    return assertEqualFiles(goldenFile, generatedFile)
36
}
37

38
function assertEqualFiles(goldenFilePath: string, otherFilePath: string) {
39
    const golden = fs.readFileSync(goldenFilePath, "utf-8")
40
    const other = fs.readFileSync(otherFilePath, "utf-8")
41

42
    return assert.equal(golden, other)
43
}
44

45
export function collectFiles(root: string): string[] {
46
    if (!fs.existsSync(root)) {
47
        throw new Error(`No such directory ${root}`)
48
    }
49

50
    let files: string[] = []
51

52
    function traverse(directory: string) {
53
        const dirents = fs.readdirSync(directory, { withFileTypes: true }) as fs.Dirent[]
54

55
        dirents.forEach(dirent => {
56
            const name = dirent.name
57
            const fullPath = path.resolve(directory, name)
58

59
            if (dirent.isFile()) {
60
                const relative = path.relative(root, fullPath)
61
                files.push(relative)
62
            }
63
            if (dirent.isDirectory()) {
64
                traverse(fullPath)
65
            }
66
        })
67
    }
68
    traverse(root)
69
    return files
70
}
71

72
export function copy(from: string, to: string, files: string[],
73
    sourceToEts: boolean = false, erasePath: boolean = false, etsFileExtension: boolean = false, makeModule: boolean = false): string[] {
74
 
75
    let newFiles: string[] = []
76
    files.forEach(file => {
77
        if (!file.endsWith('.ts') && !file.endsWith('.ets')) {
78
            return
79
        }
80

81
        const fromPath = path.join(from, file)
82

83
        let content = fileContent(fromPath, sourceToEts)
84
        if (makeModule) {
85
            content += ' export {}'
86
        }
87

88
        let writePath = file
89
        if (erasePath) {
90
            writePath = writePath.split(path.sep).pop()!
91
        }
92
        writePath = path.join(to, writePath)
93
        writePath = etsFileExtension ? writePath.replace(".ts", ".ets") : writePath
94

95
        if (!fs.existsSync(writePath)) {
96
            newFiles.push(file)
97
        }
98
        forceWriteFile(writePath, content)
99
    })
100
    return newFiles
101
}
102

103
function fileContent(fromPath: string, isEts: boolean) {
104
    if (!isEts) {
105
        return fs.readFileSync(fromPath)
106
    }
107
    const module = require(fromPath)
108
    if (module?.source === undefined) {
109
        throw new Error(`Failed to runtime import ${fromPath}`)
110
    }
111

112
    return module.source
113
}
114

115
function forceWriteFile(filePath: string, content: string) {
116
    const folders = filePath.split(path.sep).slice(0, -1)
117

118
    forceWriteFolders(folders)
119

120
    fs.writeFileSync(filePath, content)
121
}
122

123
function forceWriteFolders(folders: string | string[]) {
124
    if (typeof(folders) == "string") {
125
        folders = folders.split(path.sep)
126
    }
127

128
    if (folders.length == 0) {
129
        return
130
    }
131
    folders.reduce((last, folder) => {
132
        const folderPath = last + path.sep + folder
133
        if (!fs.existsSync(folderPath)) {
134
            fs.mkdirSync(folderPath)
135
        }
136
        return folderPath
137
    })
138
}
139

140
class DirectoriesManager {
141

142
    private readonly root = this.initRoot()
143

144
    private initRoot() {
145
        const initDir = process.env.INIT_CWD
146
        if (initDir === undefined) {
147
            throw new Error(`Launch only from npm run`)
148
        }
149
        return initDir
150
    }
151

152
    constructor() {
153
        if (!this.root.includes('ets-plugin')) {
154
            throw new Error(`
155
                Launch only from subdirectory of koala-ui/ets-plugin
156
            `.trim())
157
        }
158
        this.root = this.root.split('ets-plugin')[0] + 'ets-plugin' // sets root to .../something/ets-plugin
159

160
        const dirs = [this.testsDir, this.goldenSpecificationDir, this.testPagesDir]
161
        dirs.forEach((dir) => {
162
            if (!fs.existsSync(dir)) {
163
                forceWriteFolders(dir)
164
            }
165
        })
166
    }
167

168
    get testsDir() {
169
        return path.resolve(this.root, './test/ets/specification')
170
    }
171

172
    get testPagesDir() {
173
        return path.resolve(this.root, './test/ets/specification/test/pages')
174
    }
175

176
    get goldenSpecificationDir() {
177
        return path.resolve(this.root, './test/golden/specification/')
178
    }
179

180
    get generatedDir() {
181
        return path.resolve(this.root, './test/generated/specification/')
182
    }
183

184
    private get repoPath() {
185
        return path.resolve(this.root, './test/specification/ets2bundle/')
186
    }
187

188
    getOrDownloadSpecificationTestsDir() {
189
        const dir = path.resolve(this.repoPath, './compiler/test/utForPartialUpdate')
190
        this.downloadDeveloptoolsEts2Bundle(dir)
191
        return dir
192
    }
193

194
    getOrDownloadSpecificationPagesDir() {
195
        const dir = path.resolve(this.repoPath, './compiler/test/pages')
196
        this.downloadDeveloptoolsEts2Bundle(dir)
197
        return dir
198
    }
199

200
    private downloadDeveloptoolsEts2Bundle(dir: string) {
201
        if (fs.existsSync(dir)) {
202
            console.log(`Found ${dir}, no need to download or patch`)
203
            return
204
        }
205

206
        const cloneTo = path.resolve(this.root, './test/specification/')
207

208
        if (!fs.existsSync(this.repoPath)) {
209
            this.run(
210
                cloneTo,
211
                `git clone --depth 1 https://_:bVGsDK-34ViNC37AZY5a@rnd-gitlab-msc.huawei.com/rus-os-team/koala-ui/ets2bundle.git`,
212
            )
213
        }
214

215
        this.run(
216
            this.repoPath,
217
            `git apply ../patches/*.patch`
218
        )
219

220
        if (!fs.existsSync(dir)) {
221
            throw new Error(`Somehow ${dir} still doesn't exist after cloning repo. Check developtoolsEts2Bundle files layout`)
222
        }
223
    }
224

225
    private run(where: string, ...commands: string[]) {
226
        commands.forEach(cmd =>
227
            child.execSync(`cd ${where} && ${cmd}`, { stdio: 'inherit' })
228
        )
229
    }
230
}
231

232
export const directoriesManager = new DirectoriesManager()
233

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

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

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

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