idlize

Форк
0
/
getDependencies4ohos.mjs 
228 строк · 8.6 Кб
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 { error } from "node:console";
17
import * as fs from "node:fs"
18
import * as path from "node:path"
19
import { argv } from 'process'
20

21
let isFull = true
22
let isArm64 = true
23

24
for (let i = 2; i < argv.length; ++i) {
25
    switch (argv[i]) {
26
        case "subset":
27
            isFull = false
28
            break;
29
        case "full":
30
            isFull = true
31
            break;
32
        case "arm64":
33
            isArm64 = true
34
            break;
35
        case "arm32":
36
        case "arm":
37
            isArm64 = false
38
            break;
39
        default:
40
            break;
41
    }
42
}
43

44
let arch = 'arm64'
45
let archPath = 'arm64-v8a'
46
if (!isArm64) {
47
    arch = 'arm'
48
    archPath = 'armeabi-v7a'
49
}
50

51
const libName = `libNativeBridge_ohos_${arch}.so`
52
const libSource = `native/${libName}`
53

54

55
const libsDir = `ohos-app/api_perf/entry/libs/`
56
const libTargetDir = `${libsDir}/${archPath}`
57
const libTarget = `${libTargetDir}/${libName}`
58
const codesTargetDir = 'ohos-app/api_perf/entry/src/main/ets/idlize'
59
const koalauiModulesDir = 'peer_lib/ts/@koalaui'
60
const arkoalaArkuiSrcDir = `generated/${isFull ? 'peers' : 'subset'}/koalaui/arkoala-arkui/src`
61
const peerNodePath = `${arkoalaArkuiSrcDir}/PeerNode.ts`
62
const testDtsDir = `tests/subset/ets`
63
const commonFilePath = path.join(codesTargetDir, 'common.ts')
64
const testDtsPath = path.join(codesTargetDir, 'test.d.ts')
65
let ohosSdkRoot = process.env.OHOS_SDK ?? '../koala-ui/ohos-sdk/ohos-sdk'
66
let ohosSdkVersion = process.env.OHOS_SDK_VERSION ?? 'HarmonyOS-NEXT-DP1'
67
let sysroot = `${ohosSdkRoot}/${ohosSdkVersion}/base/native/sysroot/`
68
let llvm = `${ohosSdkRoot}/${ohosSdkVersion}/base/native/llvm/`
69
let target = `${isArm64 ? 'aarch64-linux-ohos' : 'arm-linux-ohos'}`
70

71
if (fs.existsSync(codesTargetDir)) fs.rmSync(codesTargetDir, { recursive: true })
72
if (fs.existsSync(libTargetDir)) fs.rmSync(libTargetDir, { recursive: true })
73
if (!fs.existsSync(libsDir)) fs.mkdirSync(libsDir)
74
fs.mkdirSync(codesTargetDir)
75
if (!fs.existsSync(libTargetDir)) fs.mkdirSync(libTargetDir)
76

77

78
function resolveLibDependency() {
79
    // copy libc++_shared.so to app avoid runtime errors because of wrong version libc++
80
    // let cppSharedLibPath = `${sysroot}/usr/lib/${target}/`
81
    let cppSharedLibPath = `${llvm}/lib/${target}/`
82
    let cppLibName = `libc++_shared.so`
83
    console.log(`copy ${cppSharedLibPath}/${cppLibName} ${libTargetDir}/${cppLibName}`)
84
    fs.copyFileSync(`${cppSharedLibPath}/${cppLibName}`, `${libTargetDir}/${cppLibName}`)
85

86
    // copy libNativeBridge_ohos_xxx.so
87
    console.log(`copy ${libSource} ${libTarget}`)
88
    fs.copyFileSync(libSource, libTarget)
89
}
90

91

92
const whiteList = [
93
    "ArkUINodeType.ts"
94
]
95

96
const blackList = [
97
    "main.ts"
98
]
99

100
const testDtsWhiteList = []
101

102
function getCommonFilePath() {
103
    return commonFilePath
104
}
105

106
function getTestDtsPath() {
107
    return testDtsPath
108
}
109

110
function copyTestDts(sourceDir, specificFile = undefined) {
111
    let resolveTestDts = file => {
112
        const sourceFile = path.join(sourceDir, specificFile ?? file)
113
        if (fs.lstatSync(sourceFile).isDirectory()) {
114
            copyTestDts(sourceFile)
115
            return
116
        }
117
        console.log(`sourceFile : ${sourceFile}`)
118
        if (file.endsWith('.d.ts') || testDtsWhiteList.includes(file)) {
119
            console.log(`sourceFile endsWith : ${sourceFile}`)
120
            let data = fs.readFileSync(sourceFile, 'utf8')
121
            let expectedData = data
122
            fs.appendFileSync(getTestDtsPath(), expectedData, 'utf8', (error) => {
123
                if (error) {
124
                  console.error(`appendFile ${getTestDtsPath()} error :`, error)
125
                  return
126
                }
127
                console.log(`appendFile ${getTestDtsPath()} successfully`)
128
            });
129
        }
130
    }
131
    if (!specificFile) {
132
        fs.readdirSync(sourceDir).forEach(resolveTestDts)
133
    } else {
134
        resolveTestDts(sourceDir)
135
    }
136
}
137

138
function copyAndFixPeerFiles(sourceDir, codesTargetDir, isCommon) {
139
    const importUtil = 'import util from \'@ohos.util\'\n'
140
    let initString = `${importUtil}
141

142
export class ArkComponent {
143
    protected peer?: NativePeerNode
144
    setPeer(peer: NativePeerNode) {
145

146
    }
147
}`
148

149
    if (isCommon) {
150
        fs.readFile(peerNodePath, 'utf8', (error, data) => {
151
            if (error) {
152
                console.error(`read ${peerNodePath} error : `, error)
153
                return
154
            }
155
            initString += data.replace(/.*@koalaui\/common"/g, '')
156
            initString = initString.replace(/.*@koalaui\/arkoala"/g, '')
157
            initString = initString.replace(/.*@koalaui\/interop"/g, '')
158
            initString = initString.replace(/.*@koalaui\/runtime"/g, '')
159
            fs.writeFile(getCommonFilePath(), initString, 'utf8', (error) => {
160
                if (error) {
161
                    console.error(`Init ${getCommonFilePath()} error : `, error)
162
                    return
163
                }
164
                console.log(`Init ${getCommonFilePath()} successfully`);
165
            });
166
        })
167
    }
168

169
    fs.readdirSync(sourceDir).forEach(file => {
170
        const sourceFile = path.join(sourceDir, file);
171
        if (fs.lstatSync(sourceFile).isDirectory()) {
172
            copyAndFixPeerFiles(sourceFile, codesTargetDir, isCommon)
173
        }
174
        const targetFile = path.join(codesTargetDir, file);
175
        let condition = file.endsWith('.ts')
176
        if (!blackList.includes(file) && (condition || whiteList.includes(file))) {
177
            fs.readFile(sourceFile, 'utf8', (error, data) => {
178
                if (error) {
179
                    console.error(`read ${sourceFile} error : `, error)
180
                    return
181
                }
182
                let expectedData
183
                if (isCommon) {
184
                    expectedData = data.replace(/import.*/g, '')
185
                    expectedData = expectedData.replace(/new TextDecoder/g, 'new util.TextDecoder')
186
                    fs.appendFile(getCommonFilePath(), expectedData, 'utf8', (error) => {
187
                        if (error) {
188
                          console.error(`appendFile ${getCommonFilePath()} error :`, error)
189
                          return
190
                        }
191
                        console.log(`appendFile ${getCommonFilePath()} successfully`);
192
                    });
193
                } else {
194
                    expectedData = data.replace(/@arkoala\/arkui/g, '.')
195
                    expectedData = expectedData.replace(/@koalaui\/arkoala/g, './common')
196
                    expectedData = expectedData.replace(/@koalaui\/common/g, './common')
197
                    expectedData = expectedData.replace(/@koalaui\/interop/g, './common')
198
                    expectedData = expectedData.replace(/@koalaui\/runtime/g, './common')
199
                    expectedData = expectedData.replace(/implements.*/g, '{')
200
                    if (file === "NativeModule.ts") {
201
                        const requireStatement = 'LOAD_NATIVE as NativeModule'
202
                        const requireNapiStatement = `globalThis.requireNapi("libNativeBridge_ohos_${arch}.so", true)`
203
                        expectedData = expectedData.replace(requireStatement, requireNapiStatement)
204
                    }
205
                    if (expectedData.includes('new TextDecoder') || expectedData.includes('new TextEncoder')) {
206
                        expectedData = expectedData.replace(/new TextDecoder/g, 'new util.TextDecoder')
207
                        expectedData = expectedData.replace(/new TextEncoder/g, 'new util.TextEncoder')
208
                        expectedData = importUtil + expectedData
209
                    }
210
                    fs.writeFile(targetFile, expectedData, 'utf8', (error) => {
211
                        if (error) {
212
                          console.error(`write ${targetFile} error :`, error)
213
                          return
214
                        }
215
                        console.log(`write ${targetFile} successfully`);
216
                    });
217
                }
218
            })
219
        }
220
    });
221
}
222

223
resolveLibDependency()
224
copyAndFixPeerFiles(koalauiModulesDir, codesTargetDir, true)
225
if (!isFull) copyTestDts(testDtsDir)
226

227
console.log(`copy ${isFull ? 'full' : 'subset'} peer codes to ohos project.`)
228
copyAndFixPeerFiles(arkoalaArkuiSrcDir, codesTargetDir)
229

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

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

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

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