help-me.js 2.0 KB

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