-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
642 lines (570 loc) · 23.2 KB
/
index.js
File metadata and controls
642 lines (570 loc) · 23.2 KB
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
import dotenv from 'dotenv';
import chalk from 'chalk';
import { execSync } from 'child_process';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Load environment variables
try {
dotenv.config();
} catch (error) {
console.error(chalk.red('[CRITICAL]'), '.env file does not exist or cannot be loaded.');
process.exit(1);
}
// Variable definitions
const variables = {
STORAGE: {
required_by: ['function:2-sheetifier', 'function:3-translator', 'function:4-checker', 'function:5-desheetifier', 'tool:svscript-convert'],
check: 'checkStorageValue',
message: 'must be either "GOOGLE" or a valid path to an xlsx file'
},
SPREADSHEET_ID: {
required_by: ['function:2-sheetifier', 'function:3-translator', 'function:4-checker', 'function:5-desheetifier', 'tool:svscript-convert'],
conditional: 'requiresGoogleStorage'
},
GOOGLE_CREDENTIALS_FILE: {
required_by: ['function:2-sheetifier', 'function:3-translator', 'function:4-checker', 'function:5-desheetifier', 'tool:svscript-convert'],
check: 'fileExistsAndNotEmpty',
message: 'file does not exist or is empty',
conditional: 'requiresGoogleStorage'
},
VOCAB_CHARS_SHEET_NAME: {
required_by: ['function:2-sheetifier', 'function:3-translator', 'tool:svscript-convert']
},
VOCAB_TERMS_SHEET_NAME: {
required_by: ['function:2-sheetifier', 'function:3-translator']
},
SYSTEM_SHEET_NAME: {
required_by: ['function:2-sheetifier', 'function:5-desheetifier']
},
ACTORS_SHEET_NAME: {
required_by: ['function:2-sheetifier', 'function:5-desheetifier']
},
QUESTS_SHEET_NAME: {
required_by: ['function:2-sheetifier', 'function:5-desheetifier']
},
DIALOGUES_SHEET_NAME: {
required_by: ['function:2-sheetifier', 'function:3-translator', 'function:4-checker', 'function:5-desheetifier']
},
STRINGS_SHEET_NAME: {
required_by: ['function:2-sheetifier', 'function:5-desheetifier']
},
GAME_DATA_DIR: {
required_by: ['function:1-exporter', 'function:6-boom-boom-build'],
check: 'dirExistsAndNotEmpty',
message: 'directory does not exist or is empty'
},
GAME_UNITY_VERSION: {
required_by: ['function:1-exporter', 'function:6-boom-boom-build']
},
UNITYPY_USE_PYTHON_PARSER: {
required_by: [],
check: 'equalsTrueOrFalse',
message: "does not equal to 'true' or 'false'"
},
SKIP_TEXTURES: {
required_by: [],
check: 'equalsTrueOrFalse',
message: "does not equal to 'true' or 'false'"
},
RES_DIR: {
required_by: ['function:1-exporter', 'function:6-boom-boom-build'],
check: 'validDirOrCreatable',
message: 'is not a valid directory or cannot be created'
},
TEXTURES_DIR: {
required_by: ['function:1-exporter'],
check: 'validDirOrCreatable',
message: 'is not a valid directory or cannot be created',
conditional: 'requiresTextures'
},
OVERRIDES_DIR: {
required_by: [],
check: 'validDirOrCreatable',
message: 'is not a valid directory or cannot be created'
},
OUT_DIR: {
required_by: ['function:6-boom-boom-build'],
check: 'validDirOrCreatable',
message: 'is not a valid directory or cannot be created'
},
POST_CMD: {
required_by: []
},
BASE_LANG: {
required_by: ['function:2-sheetifier'],
check: 'checkLangCode',
message: 'is not a valid 2-symbol [a-z] code'
},
TARGET_LANG: {
required_by: ['function:5-desheetifier'],
check: 'checkLangCode',
message: 'is not a valid 2-symbol [a-z] code'
},
OPENAI_API_ENDPOINT: {
required_by: ['function:3-translator', 'function:4-checker'],
check: 'checkStartsWithHttp',
message: "does not start with 'http'"
},
OPENAI_API_KEY: {
required_by: ['function:3-translator', 'function:4-checker']
},
OPENAI_MODEL: {
required_by: ['function:3-translator', 'function:4-checker']
},
OPENAI_TEMPERATURE: {
required_by: ['function:3-translator', 'function:4-checker']
},
LANG_FROM: {
required_by: ['function:3-translator']
},
LANG_TO: {
required_by: ['function:3-translator', 'function:4-checker']
},
EXAMPLE_HI: {
required_by: ['function:3-translator']
},
EXAMPLE_HOWRU: {
required_by: ['function:3-translator']
},
SV_SPREADSHEET_ID: {
required_by: ['tool:svscript-convert']
}
};
// Check functions
const checks = {
fileExistsAndNotEmpty: (filePath) => {
try {
return fs.statSync(filePath).size > 0;
} catch {
return false;
}
},
dirExistsAndNotEmpty: (dirPath) => {
try {
return fs.readdirSync(dirPath).length > 0;
} catch {
return false;
}
},
validDirOrCreatable: (dirPath) => {
if (fs.existsSync(dirPath)) return true;
try {
fs.mkdirSync(dirPath, { recursive: true });
fs.rmdirSync(dirPath);
return true;
} catch {
return false;
}
},
checkLangCode: (code) => {
return /^[a-z]{2}$/.test(code);
},
checkStartsWithHttp: (url) => {
return url.toLowerCase().startsWith('http');
},
equalsTrueOrFalse: (value) => {
return ['true', 'false'].includes(value.toLowerCase());
},
checkStorageValue: (value) => {
if (value === 'GOOGLE') {
return true;
}
// Check if it's a valid path that could exist and ends with .xlsx
// Allow Windows paths (C:\path\file.xlsx) and Unix paths (./path/file.xlsx)
if (!value.endsWith('.xlsx')) {
return false;
}
// Basic path validation - exclude invalid characters but allow : for Windows drive letters
const invalidChars = /[<>"|?*]/;
return !invalidChars.test(value);
},
requiresGoogleStorage: () => {
return process.env.STORAGE === 'GOOGLE';
},
requiresTextures: () => {
return process.env.SKIP_TEXTURES !== 'true';
}
};
// Main check function
async function checkEnvironment(requiredFor = null) {
let errors = 0;
console.log('## Variable Checks ##');
// Function to check a single variable
const checkVariable = (varName, config) => {
// Check if this variable is conditionally required
if (config.conditional && !checks[config.conditional]()) {
let skipMessage;
if (config.conditional === 'requiresGoogleStorage') {
skipMessage = `${varName} is not required (STORAGE != GOOGLE).`;
} else if (config.conditional === 'requiresTextures') {
skipMessage = `${varName} is not required (SKIP_TEXTURES = true).`;
} else {
skipMessage = `${varName} is not required.`;
}
console.log(chalk.blue('[SKIPPED]'), skipMessage);
return true; // Skip this variable, don't count as error
}
const value = process.env[varName];
const requiredInfo = (config.required_by && config.required_by.length > 0) ? ` [Required by: ${config.required_by.join(', ')}]` : '';
const errorMessage = config.message || (config.check ? 'failed validation check.' : 'is not set or is empty.');
const isOptional = !config.required_by || config.required_by.length === 0;
if (!value) {
if (isOptional) {
console.log(chalk.blue('[SKIPPED]'), `${varName} is optional and not set.`);
return true; // Optional variables don't count as errors
} else {
console.log(chalk.yellow('[WARNING]'), `${varName} ${errorMessage}${requiredInfo}`);
return false;
}
}
if (config.check && !checks[config.check](value)) {
if (isOptional) {
console.log(chalk.yellow('[WARNING]'), `${varName} ${errorMessage} (optional)`);
return true; // Optional variables with invalid values don't count as errors
} else {
console.log(chalk.yellow('[WARNING]'), `${varName} ${errorMessage}${requiredInfo}`);
return false;
}
}
console.log(chalk.green('[OK]'), `${varName} is set and valid.`);
return true;
};
if (requiredFor) {
// Check only variables required for specific function/tool
for (const [varName, config] of Object.entries(variables)) {
if (config.required_by && config.required_by.includes(requiredFor)) {
if (!checkVariable(varName, config)) {
errors++;
}
}
}
if (errors > 0) {
console.log(chalk.red('\nRequired variables are missing or invalid.'));
process.exit(1);
}
} else {
// Check all variables
for (const [varName, config] of Object.entries(variables)) {
checkVariable(varName, config);
}
console.log('\n## Final Status ##');
console.log(chalk.green('Check completed. Any warnings above should be reviewed.'));
}
console.log();
}
async function cleanup(all = false) {
console.log(chalk.blue('Starting cleanup...'));
// Remove RES_DIR, TEXTURES_DIR, OUT_DIR and Logs
for (const dir of [process.env.RES_DIR, process.env.TEXTURES_DIR, process.env.OUT_DIR, path.join(__dirname, 'Logs')]) {
if (dir && fs.existsSync(dir)) {
console.log(`Removing directory: ${dir}`);
fs.rmSync(dir, { recursive: true, force: true });
}
}
if (all) {
// Process numbered folders under Functions directory
const functionsDir = path.join(process.cwd(), 'Functions');
if (fs.existsSync(functionsDir)) {
console.log('Processing Functions directory...');
const entries = fs.readdirSync(functionsDir);
for (const entry of entries) {
const fullPath = path.join(functionsDir, entry);
if (fs.statSync(fullPath).isDirectory() && /^\d+-/.test(entry)) {
console.log(`Processing Function directory: ${entry}`);
// Clean up specific paths in each numbered directory
const pathsToRemove = [
path.join(fullPath, '.venv'),
path.join(fullPath, 'node_modules'),
path.join(fullPath, 'package-lock.json')
];
for (const pathToRemove of pathsToRemove) {
if (fs.existsSync(pathToRemove)) {
console.log(`Removing: ${pathToRemove}`);
fs.rmSync(pathToRemove, { recursive: true, force: true });
}
}
}
}
}
// Handle tools under Misc directory
const miscDir = path.join(process.cwd(), 'Misc');
if (fs.existsSync(miscDir)) {
console.log('Processing Misc directory...');
const toolEntries = fs.readdirSync(miscDir);
for (const entry of toolEntries) {
const fullPath = path.join(miscDir, entry);
if (fs.statSync(fullPath).isDirectory()) {
const pathsToRemove = [
path.join(fullPath, '.venv'),
path.join(fullPath, 'node_modules'),
path.join(fullPath, 'package-lock.json')
];
for (const pathToRemove of pathsToRemove) {
if (fs.existsSync(pathToRemove)) {
console.log(`Removing: ${pathToRemove}`);
fs.rmSync(pathToRemove, { recursive: true, force: true });
}
}
}
}
}
}
// Clean up data directory
const dataDir = path.join(process.cwd(), 'Data');
if (fs.existsSync(dataDir)) {
console.log('Cleaning up data directory...');
const dataFiles = fs.readdirSync(dataDir);
for (const file of dataFiles) {
if (file.startsWith('parsed-') && file.endsWith('.json')) {
const filePath = path.join(dataDir, file);
console.log(`Removing: ${filePath}`);
fs.unlinkSync(filePath);
}
}
}
console.log(chalk.green('Cleanup completed successfully!'));
}
function createVirtualEnv(dir) {
const venvPath = path.join(dir, '.venv');
const pythonCommand = process.platform === 'win32' ? 'python' : 'python3';
console.log(chalk.blue(`Creating virtual environment in ${dir}...`));
execSync(`${pythonCommand} -m venv .venv`, { cwd: dir, stdio: 'inherit' });
// Install requirements
const pipCommand = process.platform === 'win32'
? '.venv\\Scripts\\pip'
: '.venv/bin/pip';
console.log(chalk.blue('Installing Python dependencies...'));
execSync(`"${pipCommand}" install -r requirements.txt`, { cwd: dir, stdio: 'inherit' });
}
function installNpmDependencies(dir) {
console.log(chalk.blue(`Installing npm dependencies in ${dir}...`));
execSync('npm install', { cwd: dir, stdio: 'inherit' });
}
async function installDependencies(dir) {
console.log(chalk.blue(`Processing directory: ${dir}`));
const hasPackageJson = fs.existsSync(path.join(dir, 'package.json'));
const hasRequirements = fs.existsSync(path.join(dir, 'requirements.txt'));
if (hasPackageJson) {
installNpmDependencies(dir);
}
if (hasRequirements) {
createVirtualEnv(dir);
}
if (!hasPackageJson && !hasRequirements) {
console.log(chalk.yellow(`No dependencies found in ${dir}`));
}
}
function getFunctionDirs() {
const functionsDir = path.join(process.cwd(), 'Functions');
if (!fs.existsSync(functionsDir)) return [];
return fs.readdirSync(functionsDir)
.filter(entry => {
const fullPath = path.join(functionsDir, entry);
return fs.statSync(fullPath).isDirectory() && /^\d+-/.test(entry);
})
.map(dir => path.join(functionsDir, dir));
}
function getToolDirs() {
const miscDir = path.join(process.cwd(), 'Misc');
if (!fs.existsSync(miscDir)) return [];
return fs.readdirSync(miscDir)
.filter(entry => {
const fullPath = path.join(miscDir, entry);
return fs.statSync(fullPath).isDirectory();
})
.map(dir => path.join(miscDir, dir));
}
function run(dir, extraArgs = []) {
console.log(chalk.blue(`Running ${dir}`));
const dirType = dir.includes('Functions') ? 'function' : 'tool';
const dirName = path.basename(dir);
const requiredFor = `${dirType}:${dirName}`;
checkEnvironment(requiredFor);
// Check that either .venv or node_modules directory exists
const venvExists = fs.existsSync(path.join(dir, '.venv'));
const nodeModulesExists = fs.existsSync(path.join(dir, 'node_modules'));
if (!venvExists && !nodeModulesExists) {
console.log(chalk.red(`Dependencies not installed in ${dir}.`), '\nPlease run', chalk.blue('npm run init'), 'first.');
process.exit(1);
}
const hasPackageJson = fs.existsSync(path.join(dir, 'package.json'));
const hasRequirements = fs.existsSync(path.join(dir, 'requirements.txt'));
if (hasPackageJson) {
const indexPath = path.join(dir, 'index.js');
if (fs.existsSync(indexPath)) {
console.log(chalk.blue(`Running Node.js: ${indexPath}`));
try {
// Join the extra arguments and escape them properly
const argsString = extraArgs.map(arg => `"${arg}"`).join(' ');
execSync(`node "${indexPath}" ${argsString}`, { stdio: 'inherit' });
} catch {
console.log(chalk.red('Finished with an error.'));
process.exit(1);
}
} else {
console.log(chalk.yellow(`index.js not found in ${dir}`));
}
}
if (hasRequirements) {
const mainPath = path.join(dir, 'main.py');
if (fs.existsSync(mainPath)) {
console.log(chalk.blue(`Running Python: ${mainPath}`));
if (process.platform === 'win32') {
const batchContent = `
@echo off
call ".venv\\Scripts\\activate.bat"
python main.py
deactivate
`.trim();
const batchPath = path.join(dir, 'temp-run.bat');
fs.writeFileSync(batchPath, batchContent);
try {
execSync(`"${batchPath}"`, {
cwd: dir,
stdio: 'inherit',
shell: true
});
} catch {
fs.unlinkSync(batchPath);
console.log(chalk.red('Finished with an error.'));
process.exit(1);
}
fs.unlinkSync(batchPath);
} else {
try {
execSync(`source .venv/bin/activate && python main.py`, {
cwd: dir,
stdio: 'inherit',
shell: true
});
} catch {
console.log(chalk.red('Script returned an error.'));
process.exit(1);
}
}
} else {
console.log(chalk.yellow(`main.py not found in ${dir}`));
}
}
if (!hasPackageJson && !hasRequirements) {
console.log(chalk.yellow(`No runnable scripts found in ${dir}`));
}
}
async function main() {
const [command, subCommand] = (process.argv[2] || '').split(':');
const args = process.argv.slice(3);
switch (command) {
case 'clean':
if (subCommand === 'all') {
await cleanup(true);
} else {
await cleanup();
}
break;
case 'validate':
const parentDirs = ['Functions', 'Misc'];
console.log('## Dependency Checks ##');
for (const parentDir of parentDirs) {
const parentPath = path.join(process.cwd(), parentDir);
if (fs.existsSync(parentPath)) {
const subDirs = fs.readdirSync(parentPath).filter(dir => fs.statSync(path.join(parentPath, dir)).isDirectory());
for (const dir of subDirs) {
const dirPath = path.join(parentPath, dir);
const venvPath = path.join(dirPath, '.venv');
const nodeModulesPath = path.join(dirPath, 'node_modules');
if (!fs.existsSync(venvPath) && !fs.existsSync(nodeModulesPath)) {
console.log(chalk.red('[CRITICAL]'), dir, 'Dependencies not found, please run', chalk.blue('npm run init'), 'first.');
process.exit(1);
} else {
console.log(chalk.green('[OK]'), dir);
}
}
}
}
console.log();
await checkEnvironment();
break;
case 'install':
switch (subCommand) {
case 'all':
const allDirs = [...getFunctionDirs(), ...getToolDirs()];
for (const dir of allDirs) {
await installDependencies(dir);
}
break;
case 'function':
const functionDirs = getFunctionDirs();
const targetFunctionDir = functionDirs.find(dir => path.basename(dir).includes(args[0]));
if (!targetFunctionDir) {
console.error(chalk.red(`Function "${args[0]}" not found`));
process.exit(1);
}
await installDependencies(targetFunctionDir);
break;
case 'tool':
const toolDirs = getToolDirs();
const targetToolDir = toolDirs.find(dir => path.basename(dir) === args[0]);
if (!targetToolDir) {
console.error(chalk.red(`Tool "${args[0]}" not found`));
process.exit(1);
}
await installDependencies(targetToolDir);
break;
default:
console.error(chalk.red('Invalid install command. Use install:all, install:function, or install:tool'));
process.exit(1);
}
break;
case 'run':
switch (subCommand) {
case 'function':
const functionDirs = getFunctionDirs();
// Get the function names (first argument, split by comma)
const functionNames = args[0].split(',');
// Get the rest of the arguments to pass to the scripts
const functionExtraArgs = args.slice(1);
for (const functionName of functionNames) {
const targetFunctionDir = functionDirs.find(dir => path.basename(dir).includes(functionName));
if (!targetFunctionDir) {
console.error(chalk.red(`Function "${functionName}" not found`));
process.exit(1);
}
console.log(chalk.blue(`\nProcessing function: ${functionName}`));
await run(targetFunctionDir, functionExtraArgs);
}
break;
case 'tool':
const toolDirs = getToolDirs();
// Get the tool names (first argument, split by comma)
const toolNames = args[0].split(',');
// Get the rest of the arguments to pass to the scripts
const toolExtraArgs = args.slice(1);
for (const toolName of toolNames) {
const targetToolDir = toolDirs.find(dir => path.basename(dir) === toolName);
if (!targetToolDir) {
console.error(chalk.red(`Tool "${toolName}" not found`));
process.exit(1);
}
console.log(chalk.blue(`\nProcessing tool: ${toolName}`));
await run(targetToolDir, toolExtraArgs);
}
break;
default:
console.error(chalk.red('Invalid run command. Use run:function or run:tool'));
process.exit(1);
}
break;
default:
console.error(chalk.red('Command not understood. Available commands: clean, validate, install:[all|function|tool], run:[function|tool]'));
process.exit(1);
}
}
// Run the script
main().catch(error => {
console.log(chalk.red('An unexpected error occurred:'), error);
process.exit(1);
});