• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2* Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development 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*/
15const main = require("./main");
16const tsMain = require("../tsGen/tsMain");
17const re = require("./tools/re");
18const { checkFileError } = require("./tools/common");
19const { NapiLog } = require("./tools/NapiLog");
20const path = require("path");
21const stdio = require("stdio");
22var fs = require('fs');
23const { print } = require("./tools/tool");
24
25let ops = stdio.getopt({
26    'filename': { key: 'f', args: 1, description: ".d.ts file", default: "" },
27    'directory': { key: 'd', args: 1, description: ".d.ts directory", default: "" },
28    'imports': { key: 'i', args: 1, description: "enable or disable support imports self-define file", default: false },
29    'out': { key: 'o', args: 1, description: "output directory", default: "." },
30    'loglevel': { key: 'l', args: 1, description: "Log Level : 0~3", default: "1" },
31    // 新增控制number类型转C++类型参数
32    'numbertype':{key: 'n', args: 1, description: "optional elemtype: basic cpp elemtype", default: "uint32_t"},
33    'tsGen':{key: 't', args: 1, description: "enable or disable generate typescript file", default: false },
34
35    /* 新增业务代码可配置参数:写在json文件里:
36     * [{"includeName":"xxx.h", "cppName":"xxx.cpp","interfaceName": "functest",
37     * "serviceCode":"out = codeTestFunc(v);"}]
38     * 配置cfg.json文件路径
39     */
40    'serviceCode': {key: 's', args: 1, description: "configure the service code", default: ""}
41
42});
43
44NapiLog.init(ops.loglevel, path.join("" + ops.out, "napi_gen.log"))
45
46let fileNames = ops.filename;
47var pathDir = ops.directory;
48var imports = ops.imports;
49if (fileNames == null && pathDir == null) {
50    NapiLog.logInfo("fileNames and pathDir both cannot be empty at the same time");
51} else if (pathDir != '') {
52    readDirFiles();
53} else if (fileNames != '') {
54    readFiles();
55}
56
57function readFiles() {
58    fileNames = fileNames.replace(/(^\s*)|(\s*$)/g, ''); // trim before and after espace
59    let regex = ',';
60    let filenameArray = fileNames.toString().split(regex);
61
62    let n = filenameArray.length;
63    for (let i = 0; i < n; i++) {
64        let fileName = filenameArray[i];
65        if (fileName !== ' ') {
66            fileName = fileName.replace(/(^\s*)|(\s*$)/g, '');
67            checkGenerate(fileName);
68        }
69    }
70}
71
72function handleDirFiles(files) {
73    if (0 === files.length) {
74        NapiLog.logInfo('[Func: readDirFiles] No files in path  %s!'.format(pathDir));
75        return;
76    }
77    (function iterator(i) {
78        if (i === files.length) {
79            return;
80        }
81        let data = fs.statSync(path.join(pathDir + '', files[i]))
82        if (data.isFile()) {
83            let fileName = files[i];
84            checkGenerate(pathDir + '/' + fileName);
85        }
86        iterator(i + 1);
87    })(0);
88}
89
90function readDirFiles() {
91    let fileList;
92    try {
93        fileList = fs.readdirSync(pathDir + '');
94    } catch (err) {
95        NapiLog.logError('readdir file error ' + err);
96        return;
97    }
98
99    handleDirFiles(fileList);
100}
101
102/**
103 * 获取Json配置文件内容
104 * @returns
105 */
106function getJsonCfg(currentPath) {
107    let jsonCfg = null; // cfg.json 配置文件
108    currentPath = currentPath.replace(/(^\s*)|(\s*$)/g, ''); // trim before and after espace
109    let jsonFilePath = path.join(currentPath);
110    let jsonFile = fs.readFileSync(jsonFilePath, { encoding: "utf8" });
111    jsonCfg = JSON.parse(jsonFile);
112    return jsonCfg;
113}
114
115function checkGenerate(fileName) {
116    NapiLog.logInfo("check file []".format(fileName))
117    let suffix = fileName.split('.').pop().toLowerCase();
118    if (ops.tsGen == 'true' && suffix === 'h') {
119        NapiLog.logInfo("convert .h file to .ts file...")
120        tsMain.doGenerate(fileName, ops.out);
121        return;
122    }
123    let fn = re.getFileInPath(fileName);
124    let tt = re.match('(@ohos\.)*([.a-z_A-Z0-9]+).d.ts', fn);
125    if (tt) {
126        let result = checkFileError(fileName);
127        let jsonConfig
128        if (ops.serviceCode) {
129            jsonConfig = getJsonCfg(ops.serviceCode);
130        }
131        if (result[0]) {
132            main.doGenerate(fileName, ops.out, imports, ops.numbertype, jsonConfig);
133        }
134        else {
135            NapiLog.logError(result[1]);
136        }
137
138    }
139    else {
140        NapiLog.logError('file name ' + fn + ' format invalid in function of checkGenerate!');
141    }
142}
143
144let ret = NapiLog.getResult();
145if (ret[0]) {
146    print('success');
147    NapiLog.logInfo('success');
148}
149else {
150    print('fail\n' + ret[1]);
151    NapiLog.logInfo('fail\n' + ret[1]);
152}
153