config2ts 2.2.8 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -19,6 +19,7 @@ config2ts -d config -o dist -m csv.ts
19
19
  | Number | number |
20
20
  | Boolean | boolean |
21
21
  | Enum | type |
22
+ | EnumIndex | type |
22
23
  | String[] | string[] |
23
24
  | Number[] | number[] |
24
25
  | Enum[] | type[] |
@@ -26,6 +27,7 @@ config2ts -d config -o dist -m csv.ts
26
27
  * `Number` support Infinity and NaN
27
28
  * `Enum` support empty string type
28
29
  * `Enum[]` do not include empty string type
30
+ * `EnumIndex` will generate index type, and will use `Enum` type to generate interface
29
31
 
30
32
  ## Usage
31
33
 
package/bin/config2ts CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- require('../src/main');
2
+ require('../lib/main');
@@ -0,0 +1,10 @@
1
+ export declare const Convert: {
2
+ ini: (str: any, moduleName: any) => string;
3
+ csv: (str: any, moduleName: any) => string;
4
+ toml: (str: any, moduleName: any) => string;
5
+ };
6
+ export declare function GetTsString(filePath: any): any;
7
+ export declare function GetTsStringFromFileList(fileList: any): any;
8
+ export declare function GetHeaderInfo(): string;
9
+ export declare function GetValidFileList(fileList: any): any;
10
+ export declare function startConvert(dir: string, outDir: string, merge: boolean): void;
@@ -1,192 +1,223 @@
1
- exports.GetValidFileList = exports.GetHeaderInfo = exports.GetTsStringFromFileList = exports.GetTsString = exports.Convert = void 0;
2
- var path = require("path");
3
- var fs = require("fs");
4
- var d3 = require("d3");
5
- var json5 = require("json5");
6
- var changeCase = require("change-case");
7
- var toml = require('toml');
8
- var packageJson = require('../package.json');
9
- var EnumStr = 'Enum';
10
- var EnumArrayString = 'Enum[]';
11
- var IndexStr = 'Index';
12
-
13
- exports.Convert = {
14
- ini: function (str, moduleName) {
15
- var obj = toml.parse(str);
16
- return "export const ".concat(moduleName, " = ").concat(json5.stringify(obj, null, 4), ";");
17
- },
18
- csv: function (str, moduleName) {
19
- return csv2ts(str, moduleName);
20
- },
21
- toml: function (str, moduleName) {
22
- var obj = toml.parse(str);
23
- return "export const ".concat(moduleName, " = ").concat(json5.stringify(obj, null, 4), ";");
24
- }
25
- };
26
- function csv2ts(csvString, moduleName) {
27
- var convert = {};
28
- var result = d3.csvParse(csvString, function (d, i) {
29
- if (i === 0) {
30
- convert = d;
31
- return null;
32
- }
33
- else {
34
- for (var k in d) {
35
- // console.log(`convert[k]: ${convert[k]}, d[k]: ${d[k]}, k: ${k}`)
36
- if (global[convert[k]] instanceof Function) {
37
- d[k] = global[convert[k]](d[k]);
38
- } else if (convert[k] === 'String[]') {
39
- if (d[k] === '') {
40
- // Enum array do not include empty string
41
- d[k] = [];
42
- } else {
43
- d[k] = d[k].trim().split(',').map((v) => v.trim());
44
- }
45
- } else if (convert[k] === 'Number[]') {
46
- d[k] = d[k].trim().split(',').map((val) => Number(val));
47
- } else if (convert[k] === 'Enum[]') {
48
- if (d[k] === '') {
49
- // Enum array do not include empty string
50
- d[k] = [];
51
- } else {
52
- d[k] = d[k].trim().split(',').map((v) => v.trim());
53
- }
54
- } else {
55
- d[k] = String(d[k]);
56
- }
57
- }
58
- return d;
59
- }
60
- });
61
- // 删除columns属性
62
- delete result.columns;
63
- if (result.length <= 0) {
64
- return "";
65
- }
66
- var template = "export namespace ".concat(moduleName, " {\n\n");
67
- // generate enum type
68
- for (var field in convert) {
69
- if (convert[field] == EnumStr) {
70
- let enumValues = [];
71
- for (const row of result) {
72
- let enumValue = row[field];
73
- if (!enumValues.includes(enumValue)) {
74
- enumValues.push(enumValue);
75
- }
76
- }
77
-
78
- enumValues = enumValues.map((value) => {return `"${value}"`});
79
- template += ` export type ${field} = ${enumValues.join(' | ')};\n`;
80
- // general enum list for length test
81
- template += ` export const ${field}List: ${field}[] = [${enumValues.join(', ')}];\n\n`;
82
- } else if (convert[field] == EnumArrayString) {
83
- let enumValues = [];
84
- for (const row of result) {
85
- let enumArrayValue = row[field];
86
- for (const enumValue of enumArrayValue) {
87
- if (!enumValues.includes(enumValue)) {
88
- enumValues.push(enumValue);
89
- }
90
- }
91
- }
92
-
93
- enumValues = enumValues.map((value) => {return `"${value}"`});
94
- template += ` export type ${field} = ${enumValues.join(' | ')};\n`;
95
- // general enum list for length test
96
- template += ` export const ${field}List: ${field}[] = [${enumValues.join(', ')}];\n\n`;
97
- }
98
- }
99
-
100
- // generate interface
101
- template += " export interface Record {\n";
102
- var indexField = null;
103
- for (var field in convert) {
104
- // var fieldType = convert[field] !== '' ? convert[field].toLowerCase() : 'string';
105
- // console.log(`generate interface field: ${field}, convert[field]: ${convert[field]}`);
106
- var fieldType = 'string';
107
-
108
- if (convert[field] != '') {
109
- if (convert[field] == EnumStr) {
110
- fieldType = field;
111
- } else if (convert[field] == IndexStr) {
112
- indexField = field;
113
- } else if (convert[field] == EnumArrayString) {
114
- fieldType = field + '[]';
115
- } else {
116
- fieldType = convert[field].toLowerCase();
117
- }
118
- }
119
-
120
- field = serializeField(field)
121
- template += " ".concat(field, ": ").concat(fieldType, ";\n");
122
- }
123
- template += ' };\n\n';
124
-
125
- // remove object when index is empty
126
- if (indexField) {
127
- result = result.filter((v) => {
128
- return v[indexField] !== '';
129
- })
130
- }
131
-
132
- // generate table
133
- template += " export const List: Record[] = ";
134
- // console.log(prettyFormat(result, op));
135
- template += json5.stringify(result, null, 4).replace(/\n/g, '\n ');
136
- template += ';\n\n';
137
- if (indexField != null) {
138
- template += " export const Map: { [id: string]: Record } = {};\n";
139
- template += ` for (const v of List) { Map[v.${indexField}] = v; };\n\n`;
140
- }
141
- template += "};";
142
- return template;
143
- }
144
-
145
- /**
146
- * serialize interface field
147
- * @param {string} field
148
- */
149
- function serializeField(key) {
150
- const obj = {}
151
- obj[key] = true
152
- const objString = json5.stringify(obj);
153
- // console.log('serializeField:', json5.stringify(obj))
154
- return objString.includes("'") ? "'" + key + "'" : key;
155
- }
156
-
157
- function GetFileExt(filePath) {
158
- var pathObject = path.parse(filePath);
159
- return pathObject.ext.slice(1);
160
- }
161
- function GetTsString(filePath) {
162
- var pathObject = path.parse(filePath);
163
- var handle = exports.Convert[GetFileExt(filePath)];
164
- if (handle) {
165
- var moduleName = changeCase.pascalCase(pathObject.base);
166
- var fileString = fs.readFileSync(filePath).toString();
167
- if (fileString.charAt(0) === '\uFEFF') fileString = fileString.substr(1);
168
- return handle(fileString, moduleName);
169
- }
170
- else {
171
- return '';
172
- }
173
- }
174
- exports.GetTsString = GetTsString;
175
- function GetTsStringFromFileList(fileList) {
176
- return fileList.map(function (filePath) {
177
- return GetTsString(filePath);
178
- }).join('\n\n');
179
- }
180
- exports.GetTsStringFromFileList = GetTsStringFromFileList;
181
- function GetHeaderInfo() {
182
- var header = "export let config2ts_version = \"".concat(packageJson.version, "\";\n\n");
183
- header += "export let config2ts_build_timestamp = ".concat(Date.now(), ";\n\n");
184
- return header;
185
- }
186
- exports.GetHeaderInfo = GetHeaderInfo;
187
- function GetValidFileList(fileList) {
188
- return fileList.filter(function (filePath) {
189
- return exports.Convert[GetFileExt(filePath)] != null;
190
- });
191
- }
192
- exports.GetValidFileList = GetValidFileList;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Convert = void 0;
4
+ exports.GetTsString = GetTsString;
5
+ exports.GetTsStringFromFileList = GetTsStringFromFileList;
6
+ exports.GetHeaderInfo = GetHeaderInfo;
7
+ exports.GetValidFileList = GetValidFileList;
8
+ exports.startConvert = startConvert;
9
+ var path = require("path");
10
+ var fs = require("fs");
11
+ var d3 = require("d3");
12
+ var json5 = require("json5");
13
+ var changeCase = require("change-case");
14
+ var toml = require('toml');
15
+ var packageJson = require('../package.json');
16
+ var EnumStr = 'Enum';
17
+ var EnumIndexStr = 'EnumIndex';
18
+ var EnumArrayString = 'Enum[]';
19
+ var IndexStr = 'Index';
20
+ exports.Convert = {
21
+ ini: function (str, moduleName) {
22
+ var obj = toml.parse(str);
23
+ return "export const ".concat(moduleName, " = ").concat(json5.stringify(obj, null, 4), ";");
24
+ },
25
+ csv: function (str, moduleName) {
26
+ return csv2ts(str, moduleName);
27
+ },
28
+ toml: function (str, moduleName) {
29
+ var obj = toml.parse(str);
30
+ return "export const ".concat(moduleName, " = ").concat(json5.stringify(obj, null, 4), ";");
31
+ }
32
+ };
33
+ function csv2ts(csvString, moduleName) {
34
+ var convert = {};
35
+ var result = d3.csvParse(csvString, function (d, i) {
36
+ if (i === 0) {
37
+ convert = d;
38
+ return null;
39
+ }
40
+ else {
41
+ for (var k in d) {
42
+ // console.log(`convert[k]: ${convert[k]}, d[k]: ${d[k]}, k: ${k}`)
43
+ if (global[convert[k]] instanceof Function) {
44
+ d[k] = global[convert[k]](d[k]);
45
+ }
46
+ else if (convert[k] === 'String[]') {
47
+ if (d[k] === '') {
48
+ // Enum array do not include empty string
49
+ d[k] = [];
50
+ }
51
+ else {
52
+ d[k] = d[k].trim().split(',').map(function (v) { return v.trim(); });
53
+ }
54
+ }
55
+ else if (convert[k] === 'Number[]') {
56
+ d[k] = d[k].trim().split(',').map(function (val) { return Number(val); });
57
+ }
58
+ else if (convert[k] === 'Enum[]') {
59
+ if (d[k] === '') {
60
+ // Enum array do not include empty string
61
+ d[k] = [];
62
+ }
63
+ else {
64
+ d[k] = d[k].trim().split(',').map(function (v) { return v.trim(); });
65
+ }
66
+ }
67
+ else {
68
+ d[k] = String(d[k]);
69
+ }
70
+ }
71
+ return d;
72
+ }
73
+ });
74
+ // 删除columns属性
75
+ delete result.columns;
76
+ if (result.length <= 0) {
77
+ return "";
78
+ }
79
+ var template = "export namespace ".concat(moduleName, " {\n\n");
80
+ // generate enum type
81
+ for (var field in convert) {
82
+ if (convert[field] == EnumStr || convert[field] == EnumIndexStr) {
83
+ var enumValues = [];
84
+ for (var _i = 0, result_1 = result; _i < result_1.length; _i++) {
85
+ var row = result_1[_i];
86
+ var enumValue = row[field];
87
+ if (!enumValues.includes(enumValue)) {
88
+ enumValues.push(enumValue);
89
+ }
90
+ }
91
+ enumValues = enumValues.map(function (value) { return "\"".concat(value, "\""); });
92
+ template += " export type ".concat(field, " = ").concat(enumValues.join(' | '), ";\n");
93
+ // general enum list for length test
94
+ template += " export const ".concat(field, "List: ").concat(field, "[] = [").concat(enumValues.join(', '), "];\n\n");
95
+ }
96
+ else if (convert[field] == EnumArrayString) {
97
+ var enumValues = [];
98
+ for (var _a = 0, result_2 = result; _a < result_2.length; _a++) {
99
+ var row = result_2[_a];
100
+ var enumArrayValue = row[field];
101
+ for (var _b = 0, enumArrayValue_1 = enumArrayValue; _b < enumArrayValue_1.length; _b++) {
102
+ var enumValue = enumArrayValue_1[_b];
103
+ if (!enumValues.includes(enumValue)) {
104
+ enumValues.push(enumValue);
105
+ }
106
+ }
107
+ }
108
+ enumValues = enumValues.map(function (value) { return "\"".concat(value, "\""); });
109
+ template += " export type ".concat(field, " = ").concat(enumValues.join(' | '), ";\n");
110
+ // general enum list for length test
111
+ template += " export const ".concat(field, "List: ").concat(field, "[] = [").concat(enumValues.join(', '), "];\n\n");
112
+ }
113
+ }
114
+ // generate interface
115
+ template += " export interface Record {\n";
116
+ var indexField = null;
117
+ for (var field in convert) {
118
+ // var fieldType = convert[field] !== '' ? convert[field].toLowerCase() : 'string';
119
+ // console.log(`generate interface field: ${field}, convert[field]: ${convert[field]}`);
120
+ var fieldType = 'string';
121
+ if (convert[field] != '') {
122
+ if (convert[field] == EnumStr) {
123
+ fieldType = field;
124
+ }
125
+ else if (convert[field] == EnumIndexStr) {
126
+ fieldType = field;
127
+ indexField = field;
128
+ }
129
+ else if (convert[field] == IndexStr) {
130
+ indexField = field;
131
+ }
132
+ else if (convert[field] == EnumArrayString) {
133
+ fieldType = field + '[]';
134
+ }
135
+ else {
136
+ fieldType = convert[field].toLowerCase();
137
+ }
138
+ }
139
+ field = serializeField(field);
140
+ template += " ".concat(field, ": ").concat(fieldType, ";\n");
141
+ }
142
+ template += ' };\n\n';
143
+ // remove object when index is empty
144
+ if (indexField) {
145
+ result = result.filter(function (v) {
146
+ return v[indexField] !== '';
147
+ });
148
+ }
149
+ // generate table
150
+ template += " export const List: Record[] = ";
151
+ // console.log(prettyFormat(result, op));
152
+ template += json5.stringify(result, null, 4).replace(/\n/g, '\n ');
153
+ template += ';\n\n';
154
+ if (indexField != null) {
155
+ template += " export const Map: { [id: string]: Record } = {};\n";
156
+ template += " for (const v of List) { Map[v.".concat(indexField, "] = v; };\n\n");
157
+ }
158
+ template += "};";
159
+ return template;
160
+ }
161
+ /**
162
+ * serialize interface field
163
+ * @param {string} field
164
+ */
165
+ function serializeField(key) {
166
+ var obj = {};
167
+ obj[key] = true;
168
+ var objString = json5.stringify(obj);
169
+ // console.log('serializeField:', json5.stringify(obj))
170
+ return objString.includes("'") ? "'" + key + "'" : key;
171
+ }
172
+ function GetFileExt(filePath) {
173
+ var pathObject = path.parse(filePath);
174
+ return pathObject.ext.slice(1);
175
+ }
176
+ function GetTsString(filePath) {
177
+ var pathObject = path.parse(filePath);
178
+ var handle = exports.Convert[GetFileExt(filePath)];
179
+ if (handle) {
180
+ var moduleName = changeCase.pascalCase(pathObject.base);
181
+ var fileString = fs.readFileSync(filePath).toString();
182
+ if (fileString.charAt(0) === '\uFEFF')
183
+ fileString = fileString.substr(1);
184
+ return handle(fileString, moduleName);
185
+ }
186
+ else {
187
+ return '';
188
+ }
189
+ }
190
+ function GetTsStringFromFileList(fileList) {
191
+ return fileList.map(function (filePath) {
192
+ return GetTsString(filePath);
193
+ }).join('\n\n');
194
+ }
195
+ function GetHeaderInfo() {
196
+ var header = "export let config2ts_version = \"".concat(packageJson.version, "\";\n\n");
197
+ header += "export let config2ts_build_timestamp = ".concat(Date.now().toString(), ";\n\n");
198
+ return header;
199
+ }
200
+ function GetValidFileList(fileList) {
201
+ return fileList.filter(function (filePath) {
202
+ return exports.Convert[GetFileExt(filePath)] != null;
203
+ });
204
+ }
205
+ function startConvert(dir, outDir, merge) {
206
+ var fileList = fs.readdirSync(dir);
207
+ if (merge) {
208
+ fileList = config2ts.GetValidFileList(fileList).map(function (filename) {
209
+ return path.join(dir, filename);
210
+ });
211
+ var mergeFile = path.join(outDir, merge);
212
+ fs.writeFileSync(mergeFile, config2ts.GetTsStringFromFileList(fileList), { encoding: 'utf-8' });
213
+ console.log("config2ts, ".concat(fileList.length, " config files, merge into: ").concat(mergeFile));
214
+ }
215
+ else {
216
+ config2ts.GetValidFileList(fileList).forEach(function (filename) {
217
+ var target = path.join(outDir, "".concat(filename, ".ts"));
218
+ fs.writeFileSync(target, config2ts.GetTsString(path.join(dir, filename)), { encoding: 'utf-8' });
219
+ console.log("config2ts, convert: ".concat(filename, " , to: ").concat(target));
220
+ });
221
+ console.log('config2ts convert done!');
222
+ }
223
+ }
package/lib/main.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ declare var fs: any;
2
+ declare var path: any;
3
+ declare var program: any;
4
+ declare var config2ts: any;
5
+ declare const options: any;
6
+ declare var dir: any;
7
+ declare var outDir: any;
8
+ declare var merge: any;
9
+ declare var fileList: any;
package/lib/main.js ADDED
@@ -0,0 +1,24 @@
1
+ var fs = require("fs");
2
+ var path = require("path");
3
+ var program = require("commander");
4
+ var config2ts = require("./config2ts");
5
+ program.version(require(path.join(__dirname, '..', 'package.json'))['version']);
6
+ program
7
+ .option('-d, --dir <path>', 'set convert path. default: ./')
8
+ .option('-o, --outDir <path>', 'set outDir path. default: ./')
9
+ .option('-m, --merge <name>', 'merge all to one ts file.')
10
+ .parse(process.argv);
11
+ var options = program.opts();
12
+ console.log(options);
13
+ var dir = options['dir'] || '.';
14
+ dir = path.resolve(dir);
15
+ console.log('dir:', dir);
16
+ var outDir = options['outDir'] || dir;
17
+ outDir = path.resolve(outDir);
18
+ console.log('outDir:', outDir);
19
+ if (!fs.existsSync(outDir)) {
20
+ fs.mkdirSync(outDir, { recursive: true });
21
+ }
22
+ var merge = options['merge'];
23
+ var fileList = fs.readdirSync(dir);
24
+ config2ts.startConvert(dir, outDir, merge);
package/package.json CHANGED
@@ -1,16 +1,19 @@
1
1
  {
2
2
  "name": "config2ts",
3
- "version": "2.2.8",
3
+ "version": "2.3.0",
4
4
  "description": "convert config to ts file.",
5
- "main": "index.js",
6
- "type": "commonjs",
7
- "directories": {
8
- "test": "test"
9
- },
5
+ "main": "lib/config2ts.js",
6
+ "types": "lib/config2ts.d.ts",
10
7
  "bin": {
11
8
  "config2ts": "./bin/config2ts"
12
9
  },
10
+ "files": [
11
+ "lib/**/*",
12
+ "bin/**/*"
13
+ ],
13
14
  "scripts": {
15
+ "build": "tsc",
16
+ "convert": "node ./bin/config2ts -d ./config -o ./config",
14
17
  "test": "jest",
15
18
  "watch-test": "node_modules/.bin/jest --watch"
16
19
  },
@@ -33,6 +36,9 @@
33
36
  "toml": "^3.0.0"
34
37
  },
35
38
  "devDependencies": {
36
- "jest": "^29.5.0"
39
+ "@types/jest": "^30.0.0",
40
+ "@types/node": "^24.5.2",
41
+ "jest": "^29.5.0",
42
+ "ts-jest": "^29.4.4"
37
43
  }
38
44
  }
@@ -1,31 +0,0 @@
1
- {
2
- // See https://go.microsoft.com/fwlink/?LinkId=733558
3
- // for the documentation about the tasks.json format
4
- "version": "2.0.0",
5
- "command": "tsc",
6
- "args": [
7
- "-p",
8
- ".",
9
- "--outDir",
10
- "dist"
11
- ],
12
- "problemMatcher": "$tsc",
13
- "tasks": [
14
- {
15
- "label": "tsc",
16
- "type": "shell",
17
- "command": "tsc",
18
- "args": [
19
- "-p",
20
- ".",
21
- "--outDir",
22
- "dist"
23
- ],
24
- "problemMatcher": "$tsc",
25
- "group": {
26
- "_id": "build",
27
- "isDefault": false
28
- }
29
- }
30
- ]
31
- }
package/config/data.csv DELETED
@@ -1,7 +0,0 @@
1
- id,name,bool,num,mytype,stringarray,numberarray,typearray,space field/sub
2
- Index,String,Boolean,Number,Enum,String[],Number[],Enum[],String
3
- 1,xxx,1,111,type1,"1, 2, 3","1, 2, 3",t1,a
4
- 2,xxx,,222,type2," a , b",,"t1, t2",a
5
- 3,333,,NaN,,,"1,2","t2, t3, t4",b
6
- ,,,,,,,,
7
- 4,444,0,Infinity,type2,",1,,b",",1,,3",,c
@@ -1,106 +0,0 @@
1
- export namespace DataCsv {
2
-
3
- export type mytype = "type1" | "type2" | "";
4
- export const mytypeList: mytype[] = ["type1", "type2", ""];
5
-
6
- export type typearray = "t1" | "t2" | "t3" | "t4";
7
- export const typearrayList: typearray[] = ["t1", "t2", "t3", "t4"];
8
-
9
- export interface Record {
10
- id: string;
11
- name: string;
12
- bool: boolean;
13
- num: number;
14
- mytype: mytype;
15
- stringarray: string[];
16
- numberarray: number[];
17
- typearray: typearray[];
18
- 'space field/sub': string;
19
- };
20
-
21
- export const List: Record[] = [
22
- {
23
- id: '1',
24
- name: 'xxx',
25
- bool: true,
26
- num: 111,
27
- mytype: 'type1',
28
- stringarray: [
29
- '1',
30
- '2',
31
- '3',
32
- ],
33
- numberarray: [
34
- 1,
35
- 2,
36
- 3,
37
- ],
38
- typearray: [
39
- 't1',
40
- ],
41
- 'space field/sub': 'a',
42
- },
43
- {
44
- id: '2',
45
- name: 'xxx',
46
- bool: false,
47
- num: 222,
48
- mytype: 'type2',
49
- stringarray: [
50
- 'a',
51
- 'b',
52
- ],
53
- numberarray: [
54
- 0,
55
- ],
56
- typearray: [
57
- 't1',
58
- 't2',
59
- ],
60
- 'space field/sub': 'a',
61
- },
62
- {
63
- id: '3',
64
- name: '333',
65
- bool: false,
66
- num: NaN,
67
- mytype: '',
68
- stringarray: [],
69
- numberarray: [
70
- 1,
71
- 2,
72
- ],
73
- typearray: [
74
- 't2',
75
- 't3',
76
- 't4',
77
- ],
78
- 'space field/sub': 'b',
79
- },
80
- {
81
- id: '4',
82
- name: '444',
83
- bool: true,
84
- num: Infinity,
85
- mytype: 'type2',
86
- stringarray: [
87
- '',
88
- '1',
89
- '',
90
- 'b',
91
- ],
92
- numberarray: [
93
- 0,
94
- 1,
95
- 0,
96
- 3,
97
- ],
98
- typearray: [],
99
- 'space field/sub': 'c',
100
- },
101
- ];
102
-
103
- export const Map: { [id: string]: Record } = {};
104
- for (const v of List) { Map[v.id] = v; };
105
-
106
- };
@@ -1,9 +0,0 @@
1
- num = 1
2
-
3
- str = "string"
4
-
5
- bool = true
6
-
7
- [ItemType]
8
- book = 1
9
- fruit = 2
@@ -1,9 +0,0 @@
1
- export const IniFileIni = {
2
- num: 1,
3
- str: 'string',
4
- bool: true,
5
- ItemType: {
6
- book: 1,
7
- fruit: 2,
8
- },
9
- };
package/config/no-id.csv DELETED
@@ -1,5 +0,0 @@
1
- name,bool,num
2
- String,Boolean,Number
3
- "xxx",1,111
4
- "xxx",,222
5
- 333,,
@@ -1,27 +0,0 @@
1
- export namespace NoIdCsv {
2
-
3
- export interface Record {
4
- name: string;
5
- bool: boolean;
6
- num: number;
7
- };
8
-
9
- export const List: Record[] = [
10
- {
11
- name: 'xxx',
12
- bool: true,
13
- num: 111,
14
- },
15
- {
16
- name: 'xxx',
17
- bool: false,
18
- num: 222,
19
- },
20
- {
21
- name: '333',
22
- bool: false,
23
- num: 0,
24
- },
25
- ];
26
-
27
- };
@@ -1,7 +0,0 @@
1
- num = 1
2
-
3
- str = "test"
4
-
5
- [ItemType]
6
- book = 1
7
- fruit = 2
@@ -1,8 +0,0 @@
1
- export const TomlFileToml = {
2
- num: 1,
3
- str: 'test',
4
- ItemType: {
5
- book: 1,
6
- fruit: 2,
7
- },
8
- };
package/config/total.ts DELETED
@@ -1,153 +0,0 @@
1
- export namespace DataCsv {
2
-
3
- export type mytype = "type1" | "type2" | "";
4
- export const mytypeList: mytype[] = ["type1", "type2", ""];
5
-
6
- export type typearray = "t1" | "t2" | "t3" | "t4";
7
- export const typearrayList: typearray[] = ["t1", "t2", "t3", "t4"];
8
-
9
- export interface Record {
10
- id: string;
11
- name: string;
12
- bool: boolean;
13
- num: number;
14
- mytype: mytype;
15
- stringarray: string[];
16
- numberarray: number[];
17
- typearray: typearray[];
18
- 'space field/sub': string;
19
- };
20
-
21
- export const List: Record[] = [
22
- {
23
- id: '1',
24
- name: 'xxx',
25
- bool: true,
26
- num: 111,
27
- mytype: 'type1',
28
- stringarray: [
29
- '1',
30
- '2',
31
- '3',
32
- ],
33
- numberarray: [
34
- 1,
35
- 2,
36
- 3,
37
- ],
38
- typearray: [
39
- 't1',
40
- ],
41
- 'space field/sub': 'a',
42
- },
43
- {
44
- id: '2',
45
- name: 'xxx',
46
- bool: false,
47
- num: 222,
48
- mytype: 'type2',
49
- stringarray: [
50
- 'a',
51
- 'b',
52
- ],
53
- numberarray: [
54
- 0,
55
- ],
56
- typearray: [
57
- 't1',
58
- 't2',
59
- ],
60
- 'space field/sub': 'a',
61
- },
62
- {
63
- id: '3',
64
- name: '333',
65
- bool: false,
66
- num: NaN,
67
- mytype: '',
68
- stringarray: [],
69
- numberarray: [
70
- 1,
71
- 2,
72
- ],
73
- typearray: [
74
- 't2',
75
- 't3',
76
- 't4',
77
- ],
78
- 'space field/sub': 'b',
79
- },
80
- {
81
- id: '4',
82
- name: '444',
83
- bool: true,
84
- num: Infinity,
85
- mytype: 'type2',
86
- stringarray: [
87
- '',
88
- '1',
89
- '',
90
- 'b',
91
- ],
92
- numberarray: [
93
- 0,
94
- 1,
95
- 0,
96
- 3,
97
- ],
98
- typearray: [],
99
- 'space field/sub': 'c',
100
- },
101
- ];
102
-
103
- export const Map: { [id: string]: Record } = {};
104
- for (const v of List) { Map[v.id] = v; };
105
-
106
- };
107
-
108
- export const IniFileIni = {
109
- num: 1,
110
- str: 'string',
111
- bool: true,
112
- ItemType: {
113
- book: 1,
114
- fruit: 2,
115
- },
116
- };
117
-
118
- export namespace NoIdCsv {
119
-
120
- export interface Record {
121
- name: string;
122
- bool: boolean;
123
- num: number;
124
- };
125
-
126
- export const List: Record[] = [
127
- {
128
- name: 'xxx',
129
- bool: true,
130
- num: 111,
131
- },
132
- {
133
- name: 'xxx',
134
- bool: false,
135
- num: 222,
136
- },
137
- {
138
- name: '333',
139
- bool: false,
140
- num: 0,
141
- },
142
- ];
143
-
144
- };
145
-
146
- export const TomlFileToml = {
147
- num: 1,
148
- str: 'test',
149
- ItemType: {
150
- book: 1,
151
- fruit: 2,
152
- },
153
- };
package/src/main.js DELETED
@@ -1,43 +0,0 @@
1
- var fs = require("fs");
2
- var path = require("path");
3
- var program = require("commander");
4
- var config2ts = require("./config2ts");
5
- program.version(require(path.join(__dirname, '..', 'package.json'))['version']);
6
- program
7
- .option('-d, --dir <path>', 'set convert path. default: ./')
8
- .option('-o, --outDir <path>', 'set outDir path. default: ./')
9
- .option('-m, --merge <name>', 'merge all to one ts file.')
10
- .parse(process.argv);
11
-
12
- const options = program.opts();
13
- console.log(options);
14
-
15
- var dir = options['dir'] || '.';
16
- dir = path.resolve(dir);
17
- console.log('dir:', dir);
18
-
19
- var outDir = options['outDir'] || dir;
20
- outDir = path.resolve(outDir);
21
- console.log('outDir:', outDir);
22
- if (!fs.existsSync(outDir)) {
23
- fs.mkdirSync(outDir, {recursive: true});
24
- }
25
-
26
- var merge = options['merge'];
27
- var fileList = fs.readdirSync(dir);
28
- if (merge) {
29
- fileList = config2ts.GetValidFileList(fileList).map(function (filename) {
30
- return path.join(dir, filename);
31
- });
32
- var mergeFile = path.join(outDir, merge);
33
- fs.writeFileSync(mergeFile, config2ts.GetTsStringFromFileList(fileList), {encoding: 'utf-8'});
34
- console.log("config2ts, ".concat(fileList.length, " config files, merge into: ").concat(mergeFile));
35
- }
36
- else {
37
- config2ts.GetValidFileList(fileList).forEach(function (filename) {
38
- var target = path.join(outDir, "".concat(filename, ".ts"));
39
- fs.writeFileSync(target, config2ts.GetTsString(path.join(dir, filename)), {encoding: 'utf-8'});
40
- console.log("config2ts, convert: ".concat(filename, " , to: ").concat(target));
41
- });
42
- console.log('config2ts convert done!');
43
- }
@@ -1,27 +0,0 @@
1
- var fs = require("fs");
2
- var config2ts = require("../src/config2ts");
3
-
4
- var reg = /[\t\r\f\n\s]*/g;
5
- function getTsFileString(tsFilePath) {
6
- return fs.readFileSync(tsFilePath).toString().replace(reg, '');
7
- }
8
-
9
- test('convert csv file with id', function () {
10
- expect(config2ts.GetTsString('./config/data.csv').replace(reg, '')).toBe(getTsFileString('./config/data.csv.ts'));
11
- });
12
- test('convert csv file without id', function () {
13
- expect(config2ts.GetTsString('./config/no-id.csv').replace(reg, '')).toBe(getTsFileString('./config/no-id.csv.ts'));
14
- });
15
- test('convert ini file', function () {
16
- expect(config2ts.GetTsString('./config/ini-file.ini').replace(reg, '')).toBe(getTsFileString('./config/ini-file.ini.ts'));
17
- });
18
- test('convert toml file', function () {
19
- // console.log(config2ts.GetTsString('./config/toml_file.toml'))
20
- expect(config2ts.GetTsString('./config/toml_file.toml').replace(reg, '')).toBe(getTsFileString('./config/toml_file.toml.ts'));
21
- });
22
- test('config2ts merge csv file list', function () {
23
- expect(config2ts.GetTsStringFromFileList(["./config/data.csv", "./config/ini-file.ini", "./config/no-id.csv", "./config/toml_file.toml"]).replace(reg, '')).toBe(fs.readFileSync('./config/total.ts').toString().replace(/\s/g, ''));
24
- });
25
- test('config2ts GetValidFileList', function () {
26
- expect(config2ts.GetValidFileList(['a.csv', 'b.ini', 'c.xxx'])).toEqual(['a.csv', 'b.ini']);
27
- });