Browse Source

added npmsearch script

DanielFGray 2 years ago
parent
commit
cf81c9cf18
1 changed files with 84 additions and 0 deletions
  1. 84
    0
      npmsearch

+ 84
- 0
npmsearch View File

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

Loading…
Cancel
Save