-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.js
More file actions
executable file
·430 lines (390 loc) · 11.7 KB
/
cli.js
File metadata and controls
executable file
·430 lines (390 loc) · 11.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
425
426
427
428
429
430
#!/usr/bin/env node
// cli.js
require('module-alias/register');
require('module-alias')(__dirname);
const { hideBin } = require('yargs/helpers');
const path = require('node:path');
const fs = require('node:fs');
const {
packageJsonPath,
loggerPath,
configFormatterPath,
configResolverPath,
pluginInstallerPath,
mainConfigLoaderPath,
configCommandPath,
pluginCommandPath,
convertCommandPath,
generateCommandPath,
enginePath,
} = require('@paths');
const logger = require(loggerPath);
const configCommand = require(configCommandPath);
const pluginCommand = require(pluginCommandPath);
const convertCommandModule = require(convertCommandPath);
const generateCommand = require(generateCommandPath);
const argvRaw = hideBin(process.argv);
const isCompletionScriptGeneration =
argvRaw.includes('completion') &&
!argvRaw.includes('--get-yargs-completions');
const sharedHelpOptionKeys = [
'config',
'debug',
'factory-defaults',
'plugins-root',
'stack',
];
const sharedHelpEpilogue =
"See 'oshea --help' for global usage and shared options.";
// Fast shims for simple operations using proper logging/formatting
if (argvRaw.includes('--version') || argvRaw.includes('-v')) {
const { version } = require(packageJsonPath);
logger.info(version);
process.exit(0);
}
function createBaseYargs() {
const yargs = require('yargs/yargs');
return yargs(hideBin(process.argv))
.parserConfiguration({ 'short-option-groups': false })
.scriptName('oshea')
.usage('Usage: $0 <command_or_markdown_file> [options]')
.option('config', {
alias: 'C',
describe: 'path to a project-specific YAML config file',
type: 'string',
normalize: true,
})
.option('debug', {
alias: 'D',
describe: 'enable detailed debug output with enhanced logging',
type: 'boolean',
default: false,
})
.option('factory-defaults', {
alias: 'F',
describe: 'use only bundled default config, ignores overrides',
type: 'boolean',
default: false,
})
.option('plugins-root', {
alias: 'R',
describe: 'overrides the managed plugins directory',
type: 'string',
normalize: true,
})
.option('stack', {
alias: 'S',
describe: 'show stack traces in debug output (implies --debug)',
type: 'boolean',
default: false,
})
.alias('h', 'help')
.alias('v', 'version')
.epilogue(
'For more information, refer to the README.md file.\n' +
'Tab-completion Tip:\n' +
" echo 'source <(oshea completion)' >> ~/.bashrc\n" +
" echo 'source <(oshea completion)' >> ~/.zshrc\n" +
'then run source ~/.bashrc or source ~/.zshrc\n' +
'oshea _tab_cache',
);
}
function collapseSharedHelp(yargs) {
for (const key of sharedHelpOptionKeys) {
yargs.hide(key);
}
return yargs.epilogue(sharedHelpEpilogue);
}
function registerCliCommands(argvBuilder, handlers = {}) {
return argvBuilder
.command({
command: 'completion',
describe: 'generate completion script',
builder: (yargs) => collapseSharedHelp(yargs),
handler: handlers.completion || (() => {}),
})
.command({
...convertCommandModule.defaultCommand,
handler:
handlers.defaultConvert || convertCommandModule.defaultCommand.handler,
})
.command({
...convertCommandModule.explicitConvert,
builder: (yargs) => {
const builtYargs =
convertCommandModule.explicitConvert.builder(yargs) ?? yargs;
return collapseSharedHelp(builtYargs);
},
handler:
handlers.explicitConvert ||
convertCommandModule.explicitConvert.handler,
})
.command({
...generateCommand,
builder: (yargs) => {
const builtYargs = generateCommand.builder(yargs) ?? yargs;
return collapseSharedHelp(builtYargs);
},
handler: handlers.generate || generateCommand.handler,
})
.command({
...pluginCommand,
handler: handlers.plugin || pluginCommand.handler,
})
.command({
...configCommand,
builder: (yargs) => {
const builtYargs = configCommand.builder(yargs) ?? yargs;
return collapseSharedHelp(builtYargs);
},
handler: handlers.config || configCommand.handler,
});
}
if (argvRaw.includes('--help') || argvRaw.includes('-h')) {
registerCliCommands(createBaseYargs()).showHelp((output) => {
logger.info(output);
process.exit(0);
});
}
// Lightweight config display shim using proper formatter
if (
argvRaw[0] === 'config' &&
argvRaw.length <= 3 &&
!argvRaw.includes('--plugin')
) {
const fs = require('node:fs');
const yaml = require('js-yaml');
const path = require('node:path');
const { formatGlobalConfig } = require(configFormatterPath);
try {
const configPath = path.join(__dirname, 'config.example.yaml');
const configContent = fs.readFileSync(configPath, 'utf8');
const config = yaml.load(configContent);
const sources = {
mainConfigPath: configPath,
loadReason: 'factory default fallback',
useFactoryDefaultsOnly: false,
factoryDefaultMainConfigPath: configPath,
};
formatGlobalConfig('info', '', {
configData: config,
sources,
isPure: argvRaw.includes('--pure'),
});
process.exit(0);
} catch {
// Fall through to full engine for complex config operations
}
}
// This block is a special case for shell completion.
if (
argvRaw.includes('--get-yargs-completions') &&
!isCompletionScriptGeneration
) {
const { getSuggestions } = require(enginePath);
const completionArgv = {
_: [],
'get-yargs-completions': true,
};
let currentWord = '';
for (let i = 0; i < argvRaw.length; i++) {
const arg = argvRaw[i];
if (arg === '--get-yargs-completions') {
continue;
}
if (arg.startsWith('-')) {
if (i === argvRaw.length - 1) {
currentWord = arg;
}
} else {
completionArgv._.push(arg);
if (i === argvRaw.length - 1) {
currentWord = arg;
}
}
}
if (
completionArgv._.length > 0 &&
completionArgv._[completionArgv._.length - 1] === currentWord &&
!currentWord.startsWith('-')
) {
completionArgv._.pop();
}
const suggestions = getSuggestions(completionArgv, currentWord);
console.log(suggestions.join('\n')); // console-ok
process.exit(0);
}
const { execSync } = require('node:child_process');
const ConfigResolver = require(configResolverPath);
const PluginInstaller = require(pluginInstallerPath);
const MainConfigLoader = require(mainConfigLoaderPath);
const {
commonCommandHandler,
executeConversion,
executeGeneration,
} = require('./index.js'); // relative-path-ok
async function main() {
let installerInstance;
const argvBuilder = createBaseYargs();
argvBuilder.middleware(async (argv) => {
// Configure enhanced debugging if --debug or --stack flag is used
if (argv.debug || argv.stack) {
logger.setDebugMode(true);
const debugConfig = {
showCaller: true,
enrichErrors: true,
showStack: argv.stack || false,
};
logger.configureLogger(debugConfig);
}
const mainConfigLoader = new MainConfigLoader(
path.resolve(__dirname, '..'),
argv.config,
argv.factoryDefaults,
);
const primaryConfig = await mainConfigLoader.getPrimaryMainConfig();
const pluginsRootFromMainConfig = primaryConfig.config.plugins_root || null;
const pluginsRootCliOverride = argv['plugins-root'] || null;
installerInstance = new PluginInstaller({
pluginsRootFromMainConfig: pluginsRootFromMainConfig,
pluginsRootCliOverride: pluginsRootCliOverride,
});
argv.manager = installerInstance;
const configResolver = new ConfigResolver(
argv.config,
argv.factoryDefaults,
false,
{
pluginsRoot: installerInstance.pluginsRoot,
pluginInstaller: installerInstance,
},
);
argv.configResolver = configResolver;
});
argvBuilder.completion();
argvBuilder.command({
command: '_tab_cache',
describe: false,
builder: (yargsCommand) => {
yargsCommand
.option('config', { type: 'string' })
.option('plugins-root', { type: 'string' });
},
handler: (args) => {
const {
generateCompletionCachePath,
generateCompletionDynamicCachePath,
} = require('@paths');
try {
// Regenerate static command tree cache
execSync(`node "${generateCompletionCachePath}"`, {
stdio: 'inherit',
env: { ...process.env, DEBUG: args.debug },
});
// Regenerate dynamic completion data cache
execSync(`node "${generateCompletionDynamicCachePath}"`, {
stdio: 'inherit',
env: { ...process.env, DEBUG: args.debug },
});
} catch (error) {
logger.error(`ERROR: Cache generation failed: ${error.message}`);
process.exit(1);
}
},
});
registerCliCommands(argvBuilder, {
defaultConvert: async (args) => {
const potentialFile = args.markdownFile;
if (potentialFile) {
if (
!fs.existsSync(potentialFile) &&
!potentialFile.endsWith('.md') &&
!potentialFile.endsWith('.mdx')
) {
logger.error(`Error: Unknown command: '${potentialFile}'`);
logger.warn(
'\nTo convert a file, provide a valid path. For other commands, see --help.',
);
process.exit(1);
}
args.isLazyLoad = true;
await commonCommandHandler(
args,
executeConversion,
'convert (implicit)',
);
} else {
argvBuilder.showHelp();
}
},
explicitConvert: async (args) => {
args.isLazyLoad = false;
await commonCommandHandler(args, executeConversion, 'convert (explicit)');
},
generate: async (args) => {
args.isLazyLoad = false;
await commonCommandHandler(args, executeGeneration, 'generate');
},
})
.strictCommands()
.fail((msg, err, yargsInstance) => {
if (err) {
logger.error(msg || err.message);
if (process.env.DEBUG === 'true' && err.stack) logger.error(err.stack);
yargsInstance.showHelp();
process.exit(1);
return;
}
if (msg?.includes('Unknown argument')) {
const firstArg = process.argv[2];
if (
firstArg &&
![
'convert',
'generate',
'plugin',
'config',
'--help',
'-h',
'--version',
'-v',
'--config',
'--factory-defaults',
'--plugins-root',
].includes(firstArg) &&
(fs.existsSync(path.resolve(firstArg)) || firstArg.endsWith('.md'))
) {
logger.error(`ERROR: ${msg}`);
logger.warn(
`\nIf you intended to convert '${firstArg}', ensure all options are valid for the convert command or the default command.`,
);
yargsInstance.showHelp();
process.exit(1);
return;
}
}
logger.error(msg || 'An error occurred.');
if (msg) logger.warn('For usage details, run with --help.');
process.exit(1);
});
await argvBuilder.argv;
}
process.on('unhandledRejection', (reason, promise) => {
logger.error('Unhandled Rejection at:', { promise, reason });
if (reason instanceof Error && reason.stack) {
logger.error(reason.stack);
}
process.exit(1);
});
process.on('uncaughtException', (error) => {
logger.error('Uncaught Exception:', { error });
if (error.stack) {
logger.error(error.stack);
}
process.exit(1);
});
if (require.main === module) {
main();
}
// CLI module - main functions now in index.js
module.exports = {};