fb524b8b59def0ba764a02193786d82c9033573688fc8ec75a18c7b7bf7673a701f895d8e05fa16a22226c0168b77a9a0992d2c9a31a359738b786168b9177 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. 'use strict'
  2. const fs = require('fs')
  3. const { PassThrough, pipeline } = require('readable-stream')
  4. const glob = require('glob')
  5. const defaults = {
  6. ext: '.txt',
  7. help: 'help'
  8. }
  9. function isDirectory (path) {
  10. try {
  11. const stat = fs.lstatSync(path)
  12. return stat.isDirectory()
  13. } catch (err) {
  14. return false
  15. }
  16. }
  17. function helpMe (opts) {
  18. opts = Object.assign({}, defaults, opts)
  19. if (!opts.dir) {
  20. throw new Error('missing dir')
  21. }
  22. if (!isDirectory(opts.dir)) {
  23. throw new Error(`${opts.dir} is not a directory`)
  24. }
  25. return {
  26. createStream: createStream,
  27. toStdout: toStdout
  28. }
  29. function createStream (args) {
  30. if (typeof args === 'string') {
  31. args = args.split(' ')
  32. } else if (!args || args.length === 0) {
  33. args = [opts.help]
  34. }
  35. const out = new PassThrough()
  36. const re = new RegExp(args.map(function (arg) {
  37. return arg + '[a-zA-Z0-9]*'
  38. }).join('[ /]+'))
  39. glob(opts.dir + '/**/*' + opts.ext, function (err, files) {
  40. if (err) return out.emit('error', err)
  41. files = files.map(function (path) {
  42. const relative = path.replace(opts.dir, '').replace(/^\//, '')
  43. return { path, relative }
  44. }).filter(function (file) {
  45. return file.relative.match(re)
  46. })
  47. if (files.length === 0) {
  48. return out.emit('error', new Error('no such help file'))
  49. } else if (files.length > 1) {
  50. const exactMatch = files.find((file) => file.relative === `${args[0]}${opts.ext}`)
  51. if (!exactMatch) {
  52. out.write('There are ' + files.length + ' help pages ')
  53. out.write('that matches the given request, please disambiguate:\n')
  54. files.forEach(function (file) {
  55. out.write(' * ')
  56. out.write(file.relative.replace(opts.ext, ''))
  57. out.write('\n')
  58. })
  59. out.end()
  60. return
  61. }
  62. files = [exactMatch]
  63. }
  64. pipeline(fs.createReadStream(files[0].path), out, () => {})
  65. })
  66. return out
  67. }
  68. function toStdout (args) {
  69. createStream(args)
  70. .on('error', function () {
  71. console.log('no such help file\n')
  72. toStdout()
  73. })
  74. .pipe(process.stdout)
  75. }
  76. }
  77. module.exports = helpMe