-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
238 lines (218 loc) · 9.46 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
const { transformJSON, transformCommand } = require("./transformations.js");
const { Settings, writeDebugLine, writeLine } = require("./inputSystem.js");
const readlineSync = require('readline-sync');
const fs = require("fs");
const package = require("./package.json")
const pathLib = require('path')
const readline = require('readline');
console.warn("\x1B[0m###")
console.warn("\x1B[0m### \x1B[32m\x1B[1mDatapack Upgrader \x1B[31mv" + package.version + "\x1B[0m\x1B[32m by " + package.author)
console.warn("\x1B[0m### \x1B[1mIf you encounter a problem, make an issue on \x1B[34m" + package.homepage)
console.warn("\x1B[0m### Use '-h' to get more information about arguments.")
console.warn("\x1B[0m### \x1B[0m")
process.on('SIGINT', () => {
console.log('\x1B[0m')
})
function listFile(dir) {
let arr = fs.readdirSync(dir);
let list = [];
arr.forEach(function (item) {
var fullpath = pathLib.join(dir, item);
var stats = fs.statSync(fullpath);
if (stats.isDirectory()) {
list = list.concat(listFile(fullpath));
} else {
list.push(fullpath);
}
});
return list;
}
function transformFile(input, output, overwrite = false) {
if (pathLib.extname(input) == '.json') {
try {
if (fs.existsSync(output) == true && !overwrite) {
warningMessages += "\n" + ("## WARNING: File " + output + " already exists. Skip it. If you want to overwrite it, please use '-y' after the arguments.")
return;
};
if (!fs.existsSync(pathLib.dirname(output))) fs.mkdirSync(pathLib.dirname(output), { recursive: true });
content = fs.readFileSync(input, { encoding: "utf8" });
Settings.OutputFile = fs.createWriteStream(output);
Settings.OutputFilePath = output;
writeLine(transformJSON(content));
return;
} catch (e) {
writeDebugLine(e);
console.error(`## ERROR: Reading file failed: ${e.message}`);
}
} else if (pathLib.extname(input) == '.mcfunction') {
try {
if (fs.existsSync(output) == true && !overwrite) {
Settings.warningMessages += "\n" + ("## WARNING: File " + output + " already exists. Skip it. If you want to overwrite it, please use '-y' after the arguments.")
return;
};
if (!fs.existsSync(pathLib.dirname(output))) fs.mkdirSync(pathLib.dirname(output), { recursive: true });
content = fs.readFileSync(input, { encoding: "utf8" });
Settings.OutputFile = fs.createWriteStream(output);
Settings.OutputFilePath = output;
writeLine("##")
writeLine("## Datapack Upgrader v" + package.version + " by " + package.author)
writeLine("## If you encounter a problem, make an issue on " + package.homepage)
writeLine("## ")
let arrs = content.replaceAll("\r", "").split("\n");
for (let j = 0; j < arrs.length; j++)
writeLine(transformCommand(arrs[j].trim()));
return;
} catch (e) {
writeDebugLine(e);
console.error(`## ERROR: Reading file failed: ${e.message}`);
}
} else {
return;
}
}
function transformFolder(dir, output, overwrite = false) {
Settings.warningMessages = "";
dir = dir.replaceAll("\\", "/");
output = output.replaceAll("\\", "/");
writeDebugLine(`## Reading the folder ${dir}...`);
Settings.OutputFile = null;
Settings.OutputFilePath = "";
var files = listFile(dir);
writeLine(`\nTotal files: ${files.length}`);
console.log("\n")
if (!output.endsWith("/")) output = output + "/";
for (let i = 0; i < files.length; i++) {
// readline.clearLine(process.stdout, 0); //移动光标到行首
let percent = (i / files.length).toFixed(4);
var cell_num = Math.floor(percent * 25); // 计算需要多少个 █ 符号来拼凑图案
// 拼接黑色条
var cell = '';
for (var j = 0; j < cell_num; j++) {
cell += '█';
}
// 拼接灰色条
var empty = '';
for (var j = 0; j < 25 - cell_num; j++) {
empty += '░';
}
// 获取相对路径
let relativeFilePath = files[i].replaceAll("\\", "/");;
if (relativeFilePath.startsWith(dir)) relativeFilePath = relativeFilePath.substring(dir.length);
if (relativeFilePath.startsWith("/")) relativeFilePath = relativeFilePath.substring(1);
transformFile(files[i], output + relativeFilePath, overwrite);
// 拼接最终文本
let cmdText = 'Transforming: ' + (100 * percent).toFixed(2) + '% ' + cell + empty + ' ' + i + '/' + files.length + ` Transforming: ${relativeFilePath}\n`;
process.stdout.write(cmdText, 'utf-8');
}
process.stdout.write("Transforming: 100.00% █████████████████████████ " + files.length + "/" + files.length + " Transforming Completed!\n", 'utf-8');
console.log("\n" + Settings.warningMessages + `\nTotal: ${Settings.warningMessages.split("\n").length - 1} Warnings/Errors`);
}
const HELP_CONTENT = `
Command Arguments:
[Commands 1] [Commands2] ...
Supported commands:
-h Show help texts(This).
-i <input(File)> <Output File> Transform a File.
[-y] Overwrite the existed file.
-i <input(Folder)> <Output Folder> Transform a Folder.
[-y] Overwrite the existed file.
-debug Show debug messages
-c <commands> Transform a command. Use '\\n' to transform multiline commands.`;
let argvs = process.argv;
let i = 0;
if (argvs.indexOf("-i") == -1 && argvs.indexOf("-h") == -1 && argvs.indexOf("-c") == -1) {
console.log("\n\x1B[32mWhat do you want to do?\x1B[0m\n\x1B[33m[1] \x1B[0mTranslate commands from input.\n\x1B[33m[2] \x1B[0mTranslate commands from files/folders\n\x1B[33m[3] \x1B[0mGet help of command line arguments.\n\x1B[32mEnter the number between '[]' to continue.")
let cont = readlineSync.question("\x1B[34mINPUT> \x1B[33m")
if (cont == '1') {
console.log("\x1B[32mPlease enter the command below: ")
let cmd = readlineSync.question("\x1B[34mINPUT> \x1B[33m")
argvs.push("-c")
argvs.push(cmd)
} else if (cont == '3') {
argvs.push("-h")
} else if (cont == '2') {
console.log("\x1B[32mPlease enter the file or folder path below: ")
let inputFile = readlineSync.questionPath("\x1B[35mINPUT FILE/FOLDER> \x1B[33m")
let outputFile = readlineSync.questionPath("\x1B[36mOUTPUT FILE/FOLDER> \x1B[33m", { exists: null })
let overwrite = readlineSync.keyInYN("\x1B[34mIf the folder exist, do you want to overwrite it?\x1B[33m")
argvs.push("-i")
argvs.push(inputFile)
argvs.push(outputFile)
if(overwrite) argvs.push("-y")
}
console.log('\x1B[0m')
}
while (i < argvs.length) {
let arg = argvs[i];
if (arg == '-h') {
console.log(HELP_CONTENT);
return;
}
if (arg == '-debug') {
Settings.debugMode = !Settings.debugMode;
}
if (arg == '-json') {
Settings.jsonMode = !Settings.jsonMode;
}
if (arg == '-c') {
i++;
if (i < argvs.length) {
let arrs = argvs[i].split("\\n");
for (let j = 0; j < arrs.length; j++)
writeLine(transformCommand(arrs[j]));
}
} else if (arg == '-i') {
i++;
if (i < argvs.length) {
let path = argvs[i];
let content = "";
try {
let stats = fs.statSync(path);
if (stats.isDirectory()) {
i++;
if (i < argvs.length) {
let output = argvs[i];
i++;
let overWriteFiles = false;
if (i < argvs.length) {
if (argvs[i] == '-y') {
overWriteFiles = true;
} else i--;
}
transformFolder(path, output, overWriteFiles);
continue;
} else {
console.error("## Missing output file.")
return;
}
} else {
i++;
warningMessages = "";
if (i < argvs.length) {
let output = argvs[i];
i++;
let overWriteFiles = false;
if (i < argvs.length) {
if (argvs[i] == '-y') {
overWriteFiles = true;
} else i--;
}
transformFile(path, output, overWriteFiles);
console.log("\n" + warningMessages + `\nTotal: ${warningMessages.split("\n").length - 1} Warnings/Errors`);
} else {
console.error("## Missing output file.")
return;
}
}
} catch (error) {
console.error("## Error while reading file: " + error.message)
writeDebugLine(error);
continue;
}
}
}
i++;
}
if (Settings.OutputFile != null) {
Settings.OutputFile.end();
}