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