auto-fallback.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. 'use strict'
  2. const Y = require('./y.js')
  3. function mkPosix (opts) {
  4. return `
  5. command_not_found_${opts.isBash ? 'handle' : 'handler'}() {
  6. # Do not run within a pipe
  7. if test ! -t 1; then
  8. >&2 echo "${Y`command not found: ${'$1'}`}"
  9. return 127
  10. fi
  11. if which npx > /dev/null; then
  12. echo "${Y`${'$1'} not found. Trying with npx...`}" >&2
  13. else
  14. return 127
  15. fi
  16. if ! [[ $1 =~ @ ]]; then
  17. npx --no-install "$@"
  18. else
  19. npx "$@"
  20. fi
  21. return $?
  22. }`
  23. }
  24. function mkFish (opts) {
  25. return `
  26. function __fish_command_not_found_on_interactive --on-event fish_prompt
  27. functions --erase __fish_command_not_found_handler
  28. functions --erase __fish_command_not_found_setup
  29. function __fish_command_not_found_handler --on-event fish_command_not_found
  30. if which npx > /dev/null
  31. echo "${Y`${'$argv[1]'} not found. Trying with npx...`}" >&2
  32. else
  33. return 127
  34. end
  35. if string match -q -r @ $argv[1]
  36. npx $argv
  37. else
  38. npx --no-install $argv
  39. end
  40. end
  41. functions --erase __fish_command_not_found_on_interactive
  42. end`
  43. }
  44. module.exports = autoFallback
  45. function autoFallback (shell, fromEnv, opts) {
  46. if (shell.includes('bash')) {
  47. return mkPosix({isBash: true, install: opts.install})
  48. }
  49. if (shell.includes('zsh')) {
  50. return mkPosix({isBash: false, install: opts.install})
  51. }
  52. if (shell.includes('fish')) {
  53. return mkFish(opts)
  54. }
  55. if (fromEnv) {
  56. return autoFallback(fromEnv, null, opts)
  57. }
  58. console.error(Y`Only Bash, Zsh, and Fish shells are supported :(`)
  59. }