Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

npmsearch 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #!/usr/bin/env bash
  2. declare -a args
  3. declare -a packages
  4. declare -A colors
  5. colors[red]=$(tput setaf 1)
  6. colors[green]=$(tput setaf 2)
  7. colors[blue]=$(tput setaf 4)
  8. colors[reset]=$(tput sgr0)
  9. color() {
  10. local color="$1"; shift
  11. printf '%s' "${colors[$color]}"
  12. printf '%s\n' "$@"
  13. printf '%s' "${colors[reset]}"
  14. }
  15. err() { color red "$@" >&2; return 1; }
  16. die() {
  17. (( $# > 0 )) && err "$@"
  18. exit 1
  19. }
  20. has() {
  21. local v=0
  22. if [[ $1 = '-v' ]]; then
  23. v=1
  24. shift
  25. fi
  26. for c; do c="${c%% *}"
  27. if ! command -v "$c" &> /dev/null; then
  28. (( v > 0 )) && err "$c not found"
  29. return 1
  30. fi
  31. done
  32. }
  33. has -v npm fzf || die
  34. while true; do
  35. case "$1" in
  36. -*) args+=( "$1" ) ; shift ;;
  37. *) break
  38. esac
  39. done
  40. printf "searching...\r"
  41. search=$(npm search --json "$*") || exit
  42. printf "formatting...\r"
  43. search=$(jq -r '.[] | "\(.name)|\(.version)|\(.description)"' <<< "$search" | column -t -s'|')
  44. if has jq; then
  45. preview='npm view --json {1} | jq -C "."'
  46. else
  47. preview='npm view {1}'
  48. fi
  49. mapfile -t packages < <(fzf --multi --ansi --reverse \
  50. --bind='Ctrl-X:toggle-preview' \
  51. --expect='Ctrl-d,enter' \
  52. --preview-window='hidden' \
  53. --preview="$preview" \
  54. <<< "$search" || exit 1)
  55. key="${packages[0]}"
  56. case "${key,,}" in
  57. ctrl-d) args+=( -D ) ;;
  58. esac
  59. packages=( $(printf '%s\n' "${packages[@]:1}" | cut -d' ' -f1) )
  60. printf "installing...\r"
  61. if (( ${#packages[@]} > 0 )); then
  62. if has yarn; then
  63. yarn add "${args[@]}" "${packages[@]}"
  64. else
  65. npm i "${args[@]}" "${packages[@]}"
  66. fi
  67. else
  68. exit 1
  69. fi