-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
424 lines (406 loc) · 15.7 KB
/
index.js
File metadata and controls
424 lines (406 loc) · 15.7 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
const fs = require('fs');
const path = require('path');
const minimist = require('minimist');
// CLI options: --lang <lang>
const argv = minimist(process.argv.slice(2));
let lang = argv.lang || 'en';
const supportedLangs = ['en', 'uk'];
if (!supportedLangs.includes(lang)) lang = 'en';
const exercisesDir = path.join(__dirname, 'exercises');
const progressFile = path.join(__dirname, '.learnyoubash-progress.json');
const debugLogPath = path.join(__dirname, 'debug.log');
function logDebug(event, data) {
const ts = new Date().toISOString();
fs.appendFileSync(debugLogPath, `[${ts}] ${event}: ${JSON.stringify(data)}\n`);
}
function loadProgress() {
try {
return JSON.parse(fs.readFileSync(progressFile, 'utf8'));
} catch {
return { completed: [] };
}
}
function saveProgress(progress) {
fs.writeFileSync(progressFile, JSON.stringify(progress, null, 2));
}
function getExerciseList() {
return fs.readdirSync(exercisesDir)
.filter(f => fs.statSync(path.join(exercisesDir, f)).isDirectory())
.map(dir => {
// Use directory name as display name (can be improved with i18n/meta)
return {
name: dir.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase()),
value: dir,
};
});
}
function getExerciseTitle(dir) {
// Use directory name as fallback
return dir.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
}
function getProblemMarkdown(dir) {
const file = path.join(exercisesDir, dir, `problem.${lang}.md`);
if (fs.existsSync(file)) return fs.readFileSync(file, 'utf8');
// fallback to English
return fs.readFileSync(path.join(exercisesDir, dir, 'problem.en.md'), 'utf8');
}
function getSolutionMarkdown(dir) {
const file = path.join(exercisesDir, dir, 'solution', `solution.${lang}.md`);
if (fs.existsSync(file)) return fs.readFileSync(file, 'utf8');
// fallback to English
return fs.readFileSync(path.join(exercisesDir, dir, 'solution', 'solution.en.md'), 'utf8');
}
function getSolutionScript(dir) {
return path.join(exercisesDir, dir, 'solution', 'solution.bash');
}
function getTroubleshootingMarkdown() {
const file = path.join(__dirname, 'i18n', 'troubleshooting', `${lang}.md`);
if (fs.existsSync(file)) return fs.readFileSync(file, 'utf8');
return fs.readFileSync(path.join(__dirname, 'i18n', 'troubleshooting', 'en.md'), 'utf8');
}
async function runExerciseMenu(exercise, progress) {
logDebug('submenu_entry', { exercise });
const chalk = (await import('chalk')).default;
const { marked } = await import('marked');
const markedTerminal = (await import('marked-terminal')).default;
const boxen = (await import('boxen')).default;
const ansiEscapes = (await import('ansi-escapes')).default;
const readline = require('readline');
marked.setOptions({ renderer: new markedTerminal() });
const submenuOptions = [
'View Problem',
'Run Solution',
'Verify Your Script',
'View Solution',
'Back to Menu',
];
let selection = 0;
let running = true;
let done = false;
logDebug('submenu_loop_start', { exercise });
const renderSubmenu = () => {
let lines = [
chalk.cyanBright(getExerciseTitle(exercise)),
chalk.white('─'.repeat(50)),
];
for (let i = 0; i < submenuOptions.length; ++i) {
if (selection === i) {
lines.push(chalk.black.bgWhite(submenuOptions[i]));
} else {
lines.push(chalk.white(submenuOptions[i]));
}
}
return boxen(lines.join('\n'), {
padding: 1,
margin: 1,
borderStyle: 'round',
borderColor: 'white',
backgroundColor: 'blue',
align: 'center',
});
};
readline.emitKeypressEvents(process.stdin);
setRawModeWithDebug(true, 'runExerciseMenu start');
process.stdout.write(ansiEscapes.clearScreen);
process.stdout.write(renderSubmenu());
const onKeypress = (str, key) => {
logDebug('submenu_keypress', { exercise, str, key, selection, option: submenuOptions[selection], running, done });
if (!running) return;
if (key.name === 'down') {
selection = (selection + 1) % submenuOptions.length;
} else if (key.name === 'up') {
selection = (selection - 1 + submenuOptions.length) % submenuOptions.length;
} else if (key.name === 'return') {
logDebug('submenu_select', { exercise, action: submenuOptions[selection] });
running = false;
logDebug('submenu_running_set_false', { exercise });
process.stdin.removeListener('keypress', onKeypress);
process.stdout.write(ansiEscapes.clearScreen);
if (selection === 0) { // View Problem
logDebug('submenu_view_problem', { exercise });
console.log(marked(getProblemMarkdown(exercise)));
promptContinue(() => { done = true; logDebug('submenu_done_set_true', { exercise }); });
} else if (selection === 1) { // Run Solution
logDebug('submenu_run_solution', { exercise });
const solutionScript = getSolutionScript(exercise);
import(`file://${path.join(exercisesDir, exercise, 'exercise.js')}`).then(({ default: problemFactory }) => {
const problem = problemFactory;
problem.run([solutionScript, []], (err) => {
if (err) {
console.log(chalk.red('Error running solution.'));
}
// Always show output after running solution
try {
const fs = require('fs');
const output = fs.readFileSync(solutionScript, 'utf8');
if (output) console.log(output);
} catch {}
promptContinue(() => { done = true; logDebug('submenu_done_set_true', { exercise }); });
});
});
} else if (selection === 2) { // Verify Your Script
logDebug('submenu_verify_script', { exercise });
promptInput('Path to your script:', `./${exercise}.bash`, (script) => {
import(`file://${path.join(exercisesDir, exercise, 'exercise.js')}`).then(({ default: problemFactory }) => {
const problem = problemFactory;
problem.verify([script, []], (ok) => {
if (ok === true) {
logDebug('exercise_completed', { exercise, script });
console.log(chalk.greenBright('✔ Correct!'));
if (!progress.completed.includes(exercise)) {
progress.completed.push(exercise);
saveProgress(progress);
}
} else {
console.log(chalk.redBright('✖ Incorrect.'));
console.log(marked(getTroubleshootingMarkdown()));
}
promptContinue(() => { done = true; logDebug('submenu_done_set_true', { exercise }); });
});
});
});
} else if (selection === 3) { // View Solution
logDebug('submenu_view_solution', { exercise });
console.log(marked(getSolutionMarkdown(exercise)));
promptContinue(() => { done = true; logDebug('submenu_done_set_true', { exercise }); });
} else if (selection === 4) { // Back to Menu
logDebug('submenu_back_to_menu', { exercise });
setRawModeWithDebug(false, 'runExerciseMenu end');
done = true;
logDebug('submenu_done_set_true', { exercise });
}
} else if (key.ctrl && key.name === 'c') {
logDebug('submenu_ctrl_c', { exercise });
process.exit(0);
}
if (running) {
process.stdout.write(ansiEscapes.clearScreen);
process.stdout.write(renderSubmenu());
}
};
logDebug('submenu_attach_keypress', { exercise });
process.stdin.removeAllListeners('keypress');
process.stdin.on('keypress', onKeypress);
// Wait for menu to finish
await new Promise(resolve => {
const check = () => {
if (!running && done) {
logDebug('submenu_loop_exit', { exercise });
resolve();
}
else setTimeout(check, 50);
};
check();
});
setRawModeWithDebug(false, 'runExerciseMenu end');
logDebug('submenu_exit', { exercise });
}
function promptContinue(cb) {
setRawModeWithDebug(true, 'promptContinue (raw)');
logDebug('prompt_continue_raw_entry', {});
process.stdout.write('Press Enter to return to menu.');
function onKeypress(str, key) {
logDebug('prompt_continue_raw_keypress', { str, key });
if (key && key.name === 'return') {
process.stdin.removeListener('keypress', onKeypress);
process.stdout.write('\n');
logDebug('prompt_continue_raw_exit', {});
cb();
}
}
process.stdin.on('keypress', onKeypress);
}
function promptInput(message, def, cb) {
setRawModeWithDebug(true, 'promptInput (raw)');
logDebug('prompt_input_raw_entry', {});
let input = '';
process.stdout.write(`${message} (${def}): `);
function onKeypress(str, key) {
logDebug('prompt_input_raw_keypress', { str, key, input });
if (key && key.name === 'return') {
process.stdin.removeListener('keypress', onKeypress);
process.stdout.write('\n');
logDebug('prompt_input_raw_exit', { input });
cb(input.trim() ? input : def);
} else if (key && key.name === 'backspace') {
if (input.length > 0) {
input = input.slice(0, -1);
process.stdout.write('\b \b');
}
} else if (str && str.length === 1 && !key.ctrl && !key.meta) {
input += str;
process.stdout.write(str);
}
}
process.stdin.on('keypress', onKeypress);
}
async function chooseLanguage(cb) {
const chalk = (await import('chalk')).default;
setRawModeWithDebug(true, 'chooseLanguage (raw)');
logDebug('choose_language_raw_entry', {});
process.stdout.write(chalk.yellowBright('\nSelect language:\n'));
supportedLangs.forEach((l, i) => {
process.stdout.write(`${i + 1}. ${l}\n`);
});
process.stdout.write('Enter number: ');
function onKeypress(str, key) {
logDebug('choose_language_raw_keypress', { str, key });
if (key && key.name === 'return') {
// ignore
return;
}
if (str && /^[1-9]$/.test(str)) {
const idx = parseInt(str, 10) - 1;
if (idx >= 0 && idx < supportedLangs.length) {
lang = supportedLangs[idx];
process.stdin.removeListener('keypress', onKeypress);
process.stdout.write(`\nLanguage set to: ${lang}\n`);
logDebug('choose_language_raw_exit', { lang });
cb();
}
}
}
process.stdin.on('keypress', onKeypress);
}
async function mainMenu() {
let selection = 0;
let progress = loadProgress();
while (true) {
const result = await mainMenuLoop(selection, progress);
if (result && result.type === 'exercise') {
await runExerciseMenu(result.value, progress);
progress = loadProgress();
} else if (result && result.type === 'option') {
if (result.value === 'EXIT') {
const chalk = (await import('chalk')).default;
console.log(chalk.cyan('Goodbye!'));
process.exit(0);
} else if (result.value === 'HELP') {
const chalk = (await import('chalk')).default;
console.log(chalk.yellowBright('\nHelp: This is the Learn Bash workshop. Select an exercise to begin.'));
await new Promise(resolve => promptContinue(resolve));
} else if (result.value === 'CHECK FOR UPDATE') {
const chalk = (await import('chalk')).default;
console.log(chalk.yellowBright('\nYou are running the latest version of Learn Bash.'));
await new Promise(resolve => promptContinue(resolve));
} else if (result.value === 'CHOOSE LANGUAGE') {
await new Promise(resolve => chooseLanguage(resolve));
}
}
// preserve last selection
if (result && typeof result.selection === 'number') selection = result.selection;
}
}
async function mainMenuLoop(selection, progress) {
const chalk = (await import('chalk')).default;
const { marked } = await import('marked');
const markedTerminal = (await import('marked-terminal')).default;
const boxen = (await import('boxen')).default;
const ansiEscapes = (await import('ansi-escapes')).default;
const readline = require('readline');
marked.setOptions({ renderer: new markedTerminal() });
const menuOptions = ['HELP', 'CHOOSE LANGUAGE', 'CHECK FOR UPDATE', 'EXIT'];
logDebug('mainmenu_entry', { selection });
// Dynamically generate menu items from exercises directory
const exercises = getExerciseList();
const completed = progress.completed || [];
const menuItems = exercises.map(e =>
({
label: `${chalk.whiteBright('»')} ${chalk.white.bold(e.name.toUpperCase())}${completed.includes(e.value) ? chalk.green(' (completed)') : ''}`,
value: e.value,
type: 'exercise',
})
);
const separator = { label: chalk.white('─'.repeat(70)), type: 'separator' };
const menuOptionItems = menuOptions.map(opt => ({ label: chalk.white(opt), value: opt, type: 'option' }));
const allMenu = [...menuItems, separator, ...menuOptionItems];
const header = chalk.bold.whiteBright('Learn Bash');
const subtitle = chalk.italic.white('Bash is awesome!');
const hr = chalk.white('─'.repeat(70));
const totalChoices = allMenu.length;
// Clamp selection if menu size changed
if (selection >= totalChoices) {
logDebug('mainmenu_selection_clamped', { old: selection, new: totalChoices - 1 });
selection = totalChoices - 1;
}
const renderMenu = () => {
let lines = [header, subtitle, hr];
for (let i = 0; i < allMenu.length; ++i) {
if (allMenu[i].type === 'separator') {
lines.push(allMenu[i].label);
} else if (selection === i) {
lines.push(chalk.black.bgWhite(allMenu[i].label));
} else {
lines.push(allMenu[i].label);
}
}
return boxen(lines.join('\n'), {
padding: 1,
margin: 1,
borderStyle: 'round',
borderColor: 'white',
backgroundColor: 'blue',
align: 'center',
});
};
readline.emitKeypressEvents(process.stdin);
setRawModeWithDebug(true, 'mainMenuLoop start');
process.stdout.write(ansiEscapes.clearScreen);
process.stdout.write(renderMenu());
// Add a short delay to ensure raw mode is set before attaching keypress handler
await new Promise(res => setTimeout(res, 10));
let running = true;
logDebug('mainmenu_running_flag_start', { running });
let result = null;
function onKeypress(str, key) {
logDebug('mainmenu_keypress_start', { str, key, selection, running, item: allMenu[selection] });
if (!running) {
logDebug('mainmenu_keypress_ignored', { str, key, selection, running });
return;
}
if (key.name === 'down') {
do {
selection = (selection + 1) % totalChoices;
} while (allMenu[selection].type === 'separator');
} else if (key.name === 'up') {
do {
selection = (selection - 1 + totalChoices) % totalChoices;
} while (allMenu[selection].type === 'separator');
} else if (key.name === 'return') {
logDebug('mainmenu_select', { selection, item: allMenu[selection] });
running = false;
logDebug('mainmenu_remove_keypress', {});
process.stdin.removeListener('keypress', onKeypress);
process.stdout.write(ansiEscapes.clearScreen);
result = { ...allMenu[selection], selection };
} else if (key.ctrl && key.name === 'c') {
logDebug('mainmenu_ctrl_c', {});
process.exit(0);
}
if (running) {
process.stdout.write(ansiEscapes.clearScreen);
process.stdout.write(renderMenu());
}
logDebug('mainmenu_keypress_end', { str, key, selection, running });
}
logDebug('mainmenu_attach_keypress', {});
process.stdin.removeAllListeners('keypress');
process.stdin.on('keypress', onKeypress);
await new Promise(resolve => {
const check = () => {
if (!running) resolve();
else setTimeout(check, 50);
};
check();
});
logDebug('mainmenu_running_flag_end', { running });
setRawModeWithDebug(false, 'mainMenuLoop end');
return result;
}
function setRawModeWithDebug(mode, context) {
if (process.stdin.isTTY) {
process.stdin.setRawMode(mode);
logDebug('setRawMode', { mode, context, stack: new Error().stack });
}
}
mainMenu();