webnovel-writer.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #!/usr/bin/env node
  2. import path from 'node:path'
  3. import { fileURLToPath } from 'node:url'
  4. const __dirname = path.dirname(fileURLToPath(import.meta.url))
  5. // 解析命令行参数
  6. const args = process.argv.slice(2)
  7. const command = args[0]
  8. if (!command || command === '--help') {
  9. console.log('用法:webnovel-writer <命令> [选项]')
  10. console.log('')
  11. console.log('可用命令:')
  12. console.log(' read-chapter <章号> [--front-matter|--tail=N|--head=N]')
  13. console.log(' read-thread <条目ID> [--fields=基本信息|--履历|--收尾计划|--描述]')
  14. console.log(' read-timeline [--current-and-prev|--卷=N|--在场=名]')
  15. console.log(' read-character <正名> [--front-matter|--section=标题]')
  16. console.log(' resolve-alias <别名>')
  17. console.log(' list-threads [--悬了太久|--type=<t>|--status=<s>]')
  18. console.log(' report-overdue-threads')
  19. console.log(' ... (更多命令见文档)')
  20. process.exit(0)
  21. }
  22. // 动态 import 命令模块
  23. try {
  24. const commandPath = path.join(__dirname, '../src/commands', `${command}.js`)
  25. const commandUrl = new URL(`file:///${commandPath.replace(/\\/g, '/')}`).href
  26. const commandModule = await import(commandUrl)
  27. // 解析选项(简化实现:--key=value 或 --flag)
  28. const options = {}
  29. const positionalArgs = []
  30. for (let i = 1; i < args.length; i++) {
  31. const arg = args[i]
  32. if (arg.startsWith('--')) {
  33. const match = arg.match(/^--([^=]+)(?:=(.*))?$/)
  34. if (match) {
  35. const key = match[1]
  36. const value = match[2] !== undefined ? match[2] : true
  37. options[key] = value
  38. }
  39. } else {
  40. positionalArgs.push(arg)
  41. }
  42. }
  43. // 执行命令
  44. await commandModule.execute(positionalArgs, options)
  45. } catch (err) {
  46. if (err.code === 'ERR_MODULE_NOT_FOUND' || err.code === 'ENOENT') {
  47. console.error(`未知命令「${command}」。`)
  48. console.error('运行 webnovel-writer --help 查看可用命令。')
  49. process.exit(1)
  50. }
  51. // 其他错误
  52. console.error(`执行命令「${command}」时出错:`)
  53. console.error(err.message)
  54. process.exit(1)
  55. }