Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

npmsearch 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. #!/usr/bin/env bash
  2. declare -a args
  3. declare -a packages
  4. declare savedev=0
  5. declare -A colors
  6. colors[red]=$(tput setaf 1)
  7. colors[green]=$(tput setaf 2)
  8. colors[blue]=$(tput setaf 4)
  9. colors[reset]=$(tput sgr0)
  10. color() {
  11. local color="$1"; shift
  12. printf '%s' "${colors[$color]}"
  13. printf '%s\n' "$@"
  14. printf '%s' "${colors[reset]}"
  15. }
  16. err() { color red "$@" >&2; return 1; }
  17. die() {
  18. (( $# > 0 )) && err "$@"
  19. exit 1
  20. }
  21. has() {
  22. local v=0
  23. if [[ $1 = '-v' ]]; then
  24. v=1
  25. shift
  26. fi
  27. for c; do c="${c%% *}"
  28. if ! command -v "$c" &> /dev/null; then
  29. (( v > 0 )) && err "$c not found"
  30. return 1
  31. fi
  32. done
  33. }
  34. has -v npm fzf || die
  35. select_from() {
  36. local cmd='command -v'
  37. for a; do
  38. case "$a" in
  39. -c)
  40. cmd="$2"
  41. shift 2
  42. ;;
  43. esac
  44. done
  45. for c; do
  46. if $cmd "${c%% *}" &> /dev/null; then
  47. echo "$c"
  48. return 0
  49. fi
  50. done
  51. return 1
  52. }
  53. npm=$(select_from npm5 npm) || die 'npm not found'
  54. while true; do
  55. case "$1" in
  56. -*) args+=( "$1" ) ; shift ;;
  57. *) break
  58. esac
  59. done
  60. printf "searching...\r"
  61. search=$($npm search --json "$*") || exit
  62. printf "formatting...\r"
  63. search=$(jq -r '.[] | "\(.name)|\(.version)|\(.description)"' <<< "$search" | column -t -s'|')
  64. mapfile -t packages < <(fzf --inline-info --multi --ansi --reverse \
  65. --bind='Ctrl-X:toggle-preview' \
  66. --expect='Ctrl-d,enter' \
  67. --preview-window='hidden:down' \
  68. --preview="$npm -s --json view {1} | jq -C \"del(.users, .time, .versions)\"" \
  69. --header='enter to save, Ctrl-D saves as dev-dependency, Ctrl-X for extra info, tab to select multiple' \
  70. <<< "$search" || exit 1)
  71. key="${packages[0]}"
  72. case "${key,,}" in
  73. ctrl-d) savedev=1 ;;
  74. esac
  75. packages=( $(printf '%s\n' "${packages[@]:1}" | cut -d' ' -f1) )
  76. printf "installing...\r"
  77. if (( ${#packages[@]} > 0 )); then
  78. if has yarn; then
  79. (( savedev > 0 )) && args+=( -D )
  80. yarn add "${args[@]}" "${packages[@]}"
  81. else
  82. if (( savedev > 0 )); then
  83. args+=( -D )
  84. else
  85. args+=( -S )
  86. fi
  87. $npm i "${args[@]}" "${packages[@]}"
  88. fi
  89. else
  90. exit 1
  91. fi