2
0

wd.sh 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. #!/usr/bin/env zsh
  2. # WARP DIRECTORY
  3. # ==============
  4. # Jump to custom directories in terminal
  5. # because `cd` takes too long...
  6. #
  7. # @github.com/mfaerevaag/wd
  8. # version
  9. readonly WD_VERSION=0.9.1
  10. # colors
  11. readonly WD_BLUE="\033[96m"
  12. readonly WD_GREEN="\033[92m"
  13. readonly WD_YELLOW="\033[93m"
  14. readonly WD_RED="\033[91m"
  15. readonly WD_NOC="\033[m"
  16. ## functions
  17. # helpers
  18. wd_yesorno()
  19. {
  20. # variables
  21. local question="${1}"
  22. local prompt="${question} "
  23. local yes_RETVAL="0"
  24. local no_RETVAL="3"
  25. local RETVAL=""
  26. local answer=""
  27. # read-eval loop
  28. while true ; do
  29. printf $prompt
  30. read -r answer
  31. case ${answer:=${default}} in
  32. "Y"|"y"|"YES"|"yes"|"Yes" )
  33. RETVAL=${yes_RETVAL} && \
  34. break
  35. ;;
  36. "N"|"n"|"NO"|"no"|"No" )
  37. RETVAL=${no_RETVAL} && \
  38. break
  39. ;;
  40. * )
  41. echo "Please provide a valid answer (y or n)"
  42. ;;
  43. esac
  44. done
  45. return ${RETVAL}
  46. }
  47. wd_print_msg()
  48. {
  49. if [[ -z $wd_quiet_mode ]]
  50. then
  51. local color="${1:-$WD_BLUE}" # Default to blue if no color is provided
  52. local msg="$2"
  53. if [[ -z "$msg" ]]; then
  54. print "${WD_RED}*${WD_NOC} Could not print message. Sorry!"
  55. else
  56. print " ${color}*${WD_NOC} ${msg}"
  57. fi
  58. fi
  59. }
  60. wd_print_usage()
  61. {
  62. command cat <<- EOF
  63. Usage: wd [command] [point]
  64. Commands:
  65. <point> Warps to the directory specified by the warp point
  66. <point> <path> Warps to the directory specified by the warp point with path appended
  67. add <point> Adds the current working directory to your warp points
  68. add Adds the current working directory to your warp points with current directory's name
  69. addcd <path> Adds a path to your warp points with the directory's name
  70. addcd <path> <point> Adds a path to your warp points with a custom name
  71. rm <point> Removes the given warp point
  72. rm Removes the given warp point with current directory's name
  73. show <point> Print path to given warp point
  74. show Print warp points to current directory
  75. list Print all stored warp points
  76. ls <point> Show files from given warp point (ls)
  77. path <point> Show the path to given warp point (pwd)
  78. clean Remove points warping to nonexistent directories (will prompt unless --force is used)
  79. -v | --version Print version
  80. -c | --config Specify config file (default ~/.warprc)
  81. -q | --quiet Suppress all output
  82. -f | --force Allows overwriting without warning (for add & clean)
  83. help Show this extremely helpful text
  84. EOF
  85. }
  86. wd_exit_fail()
  87. {
  88. local msg=$1
  89. wd_print_msg "$WD_RED" "$msg"
  90. WD_EXIT_CODE=1
  91. }
  92. wd_exit_warn()
  93. {
  94. local msg=$1
  95. wd_print_msg "$WD_YELLOW" "$msg"
  96. WD_EXIT_CODE=1
  97. }
  98. wd_getdir()
  99. {
  100. local name_arg=$1
  101. point=$(wd_show "$name_arg")
  102. dir=${point:28+$#name_arg+7}
  103. if [[ -z $name_arg ]]; then
  104. wd_exit_fail "You must enter a warp point"
  105. break
  106. elif [[ -z $dir ]]; then
  107. wd_exit_fail "Unknown warp point '${name_arg}'"
  108. break
  109. fi
  110. }
  111. # core
  112. wd_warp()
  113. {
  114. local point=$1
  115. local sub=$2
  116. if [[ $point =~ "^\.+$" ]]
  117. then
  118. if [[ $#1 < 2 ]]
  119. then
  120. wd_exit_warn "Warping to current directory?"
  121. else
  122. (( n = $#1 - 1 ))
  123. cd -$n > /dev/null
  124. fi
  125. elif [[ ${points[$point]} != "" ]]
  126. then
  127. if [[ $sub != "" ]]
  128. then
  129. cd ${points[$point]/#\~/$HOME}/$sub
  130. else
  131. cd ${points[$point]/#\~/$HOME}
  132. fi
  133. else
  134. wd_exit_fail "Unknown warp point '${point}'"
  135. fi
  136. }
  137. wd_add()
  138. {
  139. local point=$1
  140. local force=$2
  141. cmdnames=(add rm show list ls path clean help)
  142. if [[ $point == "" ]]
  143. then
  144. point=$(basename "$PWD")
  145. fi
  146. if [[ $point =~ "^[\.]+$" ]]
  147. then
  148. wd_exit_fail "Warp point cannot be just dots"
  149. elif [[ $point =~ "[[:space:]]+" ]]
  150. then
  151. wd_exit_fail "Warp point should not contain whitespace"
  152. elif [[ $point =~ : ]] || [[ $point =~ / ]]
  153. then
  154. wd_exit_fail "Warp point contains illegal character (:/)"
  155. elif (($cmdnames[(Ie)$point]))
  156. then
  157. wd_exit_fail "Warp point name cannot be a wd command (see wd -h for a full list)"
  158. elif [[ ${points[$point]} == "" ]] || [ ! -z "$force" ]
  159. then
  160. wd_remove "$point" > /dev/null
  161. printf "%q:%s\n" "${point}" "${PWD/#$HOME/~}" >> "$WD_CONFIG"
  162. if (whence sort >/dev/null); then
  163. local config_tmp=$(mktemp "${TMPDIR:-/tmp}/wd.XXXXXXXXXX")
  164. # use 'cat' below to ensure we respect $WD_CONFIG as a symlink
  165. command sort -o "${config_tmp}" "$WD_CONFIG" && command cat "${config_tmp}" >| "$WD_CONFIG" && command rm "${config_tmp}"
  166. fi
  167. wd_export_static_named_directories
  168. wd_print_msg "$WD_GREEN" "Warp point added"
  169. # override exit code in case wd_remove did not remove any points
  170. # TODO: we should handle this kind of logic better
  171. WD_EXIT_CODE=0
  172. else
  173. wd_exit_warn "Warp point '${point}' already exists. Use 'add --force' to overwrite."
  174. fi
  175. }
  176. wd_addcd() {
  177. local folder="$1"
  178. local point=$2
  179. local force=$3
  180. local currentdir=$PWD
  181. if [[ -z "$folder" ]]; then
  182. wd_exit_fail "You must specify a path"
  183. return
  184. fi
  185. if [[ ! -d "$folder" ]]; then
  186. wd_exit_fail "The directory does not exist"
  187. return
  188. fi
  189. cd "$folder" || return
  190. wd_add "$point" "$force"
  191. cd "$currentdir" || return
  192. }
  193. wd_remove()
  194. {
  195. local point_list=$1
  196. if [[ "$point_list" == "" ]]
  197. then
  198. point_list=$(basename "$PWD")
  199. fi
  200. for point_name in $point_list ; do
  201. if [[ ${points[$point_name]} != "" ]]
  202. then
  203. local config_tmp=$(mktemp "${TMPDIR:-/tmp}/wd.XXXXXXXXXX")
  204. # Copy and delete in two steps in order to preserve symlinks
  205. if sed -n "/^${point_name}:.*$/!p" "$WD_CONFIG" >| "$config_tmp" && command cp "$config_tmp" "$WD_CONFIG" && command rm "$config_tmp"
  206. then
  207. wd_print_msg "$WD_GREEN" "Warp point removed"
  208. else
  209. wd_exit_fail "Something bad happened! Sorry."
  210. fi
  211. else
  212. wd_exit_fail "Warp point was not found"
  213. fi
  214. done
  215. }
  216. wd_browse() {
  217. if ! command -v fzf >/dev/null; then
  218. echo "This functionality requires fzf. Please install fzf first."
  219. return 1
  220. fi
  221. local entries=("${(@f)$(sed "s:${HOME}:~:g" "$WD_CONFIG" | awk -F ':' '{print $1 " -> " $2}')}")
  222. local script_path="${${(%):-%x}:h}"
  223. local wd_remove_output=$(mktemp "${TMPDIR:-/tmp}/wd.XXXXXXXXXX")
  224. entries=("All warp points:" "Press enter to select. Press delete to remove" "${entries[@]}")
  225. local fzf_bind="delete:execute(echo {} | awk -F ' -> ' '{print \$1}' | xargs -I {} "$script_path/wd.sh" rm {} > "$wd_remove_output")+abort"
  226. local selected_entry=$(printf '%s\n' "${entries[@]}" | fzf --height 100% --reverse --header-lines=2 --bind="$fzf_bind")
  227. if [[ -e $wd_remove_output ]]; then
  228. cat "$wd_remove_output"
  229. rm "$wd_remove_output"
  230. fi
  231. if [[ -n $selected_entry ]]; then
  232. local selected_point="${selected_entry%% ->*}"
  233. selected_point=$(echo "$selected_point" | xargs)
  234. wd $selected_point
  235. fi
  236. }
  237. wd_browse_widget() {
  238. if [[ -e $WD_CONFIG ]]; then
  239. wd_browse
  240. saved_buffer=$BUFFER
  241. saved_cursor=$CURSOR
  242. BUFFER=
  243. zle redisplay
  244. zle accept-line
  245. fi
  246. }
  247. wd_restore_buffer() {
  248. if [[ -n $saved_buffer ]]; then
  249. BUFFER=$saved_buffer
  250. CURSOR=$saved_cursor
  251. fi
  252. saved_buffer=
  253. saved_cursor=1
  254. }
  255. wd_list_all()
  256. {
  257. wd_print_msg "$WD_BLUE" "All warp points:"
  258. entries=$(sed "s:${HOME}:~:g" "$WD_CONFIG")
  259. max_warp_point_length=0
  260. while IFS= read -r line
  261. do
  262. arr=(${(s,:,)line})
  263. key=${arr[1]}
  264. length=${#key}
  265. if [[ length -gt max_warp_point_length ]]
  266. then
  267. max_warp_point_length=$length
  268. fi
  269. done <<< "$entries"
  270. while IFS= read -r line
  271. do
  272. if [[ $line != "" ]]
  273. then
  274. arr=(${(s,:,)line})
  275. key=${arr[1]}
  276. val=${line#"${arr[1]}:"}
  277. if [[ -z $wd_quiet_mode ]]
  278. then
  279. printf "%${max_warp_point_length}s -> %s\n" "$key" "$val"
  280. fi
  281. fi
  282. done <<< "$entries"
  283. }
  284. wd_ls()
  285. {
  286. wd_getdir "$1"
  287. ls "${dir/#\~/$HOME}"
  288. }
  289. wd_path()
  290. {
  291. wd_getdir "$1"
  292. echo "$(echo "$dir" | sed "s:~:${HOME}:g")"
  293. }
  294. wd_show()
  295. {
  296. local name_arg=$1
  297. local show_pwd
  298. # if there's an argument we look up the value
  299. if [[ -n $name_arg ]]
  300. then
  301. if [[ -z $points[$name_arg] ]]
  302. then
  303. wd_print_msg "$WD_BLUE" "No warp point named $name_arg"
  304. else
  305. wd_print_msg "$WD_GREEN" "Warp point: ${WD_GREEN}$name_arg${WD_NOC} -> $points[$name_arg]"
  306. fi
  307. else
  308. # hax to create a local empty array
  309. local wd_matches
  310. wd_matches=()
  311. # do a reverse lookup to check whether PWD is in $points
  312. show_pwd="${PWD/$HOME/~}"
  313. if [[ ${points[(r)$show_pwd]} == "$show_pwd" ]]
  314. then
  315. for name in ${(k)points}
  316. do
  317. if [[ $points[$name] == "$show_pwd" ]]
  318. then
  319. wd_matches[$(($#wd_matches+1))]=$name
  320. fi
  321. done
  322. wd_print_msg "$WD_BLUE" "$#wd_matches warp point(s) to current directory: ${WD_GREEN}$wd_matches${WD_NOC}"
  323. else
  324. wd_print_msg "$WD_YELLOW" "No warp point to $show_pwd"
  325. fi
  326. fi
  327. }
  328. wd_clean() {
  329. local force=$1
  330. local count=0
  331. local wd_tmp=""
  332. while read -r line
  333. do
  334. if [[ $line != "" ]]
  335. then
  336. arr=(${(s,:,)line})
  337. key=${arr[1]}
  338. val=${arr[2]}
  339. if [ -d "${val/#\~/$HOME}" ]
  340. then
  341. wd_tmp=$wd_tmp"\n"`echo "$line"`
  342. else
  343. wd_print_msg "$WD_YELLOW" "Nonexistent directory: ${key} -> ${val}"
  344. count=$((count+1))
  345. fi
  346. fi
  347. done < "$WD_CONFIG"
  348. if [[ $count -eq 0 ]]
  349. then
  350. wd_print_msg "$WD_BLUE" "No warp points to clean, carry on!"
  351. else
  352. if [ ! -z "$force" ] || wd_yesorno "Removing ${count} warp points. Continue? (y/n)"
  353. then
  354. echo "$wd_tmp" >! "$WD_CONFIG"
  355. wd_print_msg "$WD_GREEN" "Cleanup complete. ${count} warp point(s) removed"
  356. else
  357. wd_print_msg "$WD_BLUE" "Cleanup aborted"
  358. fi
  359. fi
  360. }
  361. wd_export_static_named_directories() {
  362. if [[ ! -z $WD_EXPORT ]]
  363. then
  364. command grep '^[0-9a-zA-Z_-]\+:' "$WD_CONFIG" | sed -e "s,~,$HOME," -e 's/:/=/' | while read -r warpdir ; do
  365. hash -d "$warpdir"
  366. done
  367. fi
  368. }
  369. WD_CONFIG=${WD_CONFIG:-$HOME/.warprc}
  370. local WD_QUIET=0
  371. local WD_EXIT_CODE=0
  372. # Parse 'meta' options first to avoid the need to have them before
  373. # other commands. The `-D` flag consumes recognized options so that
  374. # the actual command parsing won't be affected.
  375. zparseopts -D -E \
  376. c:=wd_alt_config -config:=wd_alt_config \
  377. q=wd_quiet_mode -quiet=wd_quiet_mode \
  378. v=wd_print_version -version=wd_print_version \
  379. f=wd_force_mode -force=wd_force_mode
  380. if [[ ! -z $wd_print_version ]]
  381. then
  382. echo "wd version $WD_VERSION"
  383. fi
  384. if [[ ! -z $wd_alt_config ]]
  385. then
  386. WD_CONFIG=$wd_alt_config[2]
  387. fi
  388. # check if config file exists
  389. if [ ! -e "$WD_CONFIG" ]
  390. then
  391. # if not, create config file
  392. touch "$WD_CONFIG"
  393. else
  394. wd_export_static_named_directories
  395. fi
  396. # disable extendedglob for the complete wd execution time
  397. setopt | grep -q extendedglob
  398. wd_extglob_is_set=$?
  399. if (( wd_extglob_is_set == 0 )); then
  400. setopt noextendedglob
  401. fi
  402. # load warp points
  403. typeset -A points
  404. while read -r line
  405. do
  406. arr=(${(s,:,)line})
  407. key=${arr[1]}
  408. # join the rest, in case the path contains colons
  409. val=${(j,:,)arr[2,-1]}
  410. points[$key]=$val
  411. done < "$WD_CONFIG"
  412. # get opts
  413. args=$(getopt -o a:r:c:lhs -l add:,rm:,clean,list,ls:,path:,help,show -- $*)
  414. # check if no arguments were given, and that version is not set
  415. if [[ ($? -ne 0 || $#* -eq 0) && -z $wd_print_version ]]
  416. then
  417. wd_print_usage
  418. # check if config file is writeable
  419. elif [ ! -w "$WD_CONFIG" ]
  420. then
  421. # do nothing
  422. # can't run `exit`, as this would exit the executing shell
  423. wd_exit_fail "\'$WD_CONFIG\' is not writeable."
  424. else
  425. # parse rest of options
  426. local wd_o
  427. for wd_o
  428. do
  429. case "$wd_o"
  430. in
  431. "-a"|"--add"|"add")
  432. wd_add "$2" "$wd_force_mode"
  433. break
  434. ;;
  435. "-b"|"browse")
  436. wd_browse
  437. break
  438. ;;
  439. "-c"|"--addcd"|"addcd")
  440. wd_addcd "$2" "$3" "$wd_force_mode"
  441. break
  442. ;;
  443. "-e"|"export")
  444. wd_export_static_named_directories
  445. break
  446. ;;
  447. "-r"|"--remove"|"rm")
  448. # Passes all the arguments as a single string separated by whitespace to wd_remove
  449. wd_remove "${@:2}"
  450. break
  451. ;;
  452. "-l"|"list")
  453. wd_list_all
  454. break
  455. ;;
  456. "-ls"|"ls")
  457. wd_ls "$2"
  458. break
  459. ;;
  460. "-p"|"--path"|"path")
  461. wd_path "$2"
  462. break
  463. ;;
  464. "-h"|"--help"|"help")
  465. wd_print_usage
  466. break
  467. ;;
  468. "-s"|"--show"|"show")
  469. wd_show "$2"
  470. break
  471. ;;
  472. "-c"|"--clean"|"clean")
  473. wd_clean "$wd_force_mode"
  474. break
  475. ;;
  476. *)
  477. wd_warp "$wd_o" "$2"
  478. break
  479. ;;
  480. --)
  481. break
  482. ;;
  483. esac
  484. done
  485. fi
  486. ## garbage collection
  487. # if not, next time warp will pick up variables from this run
  488. # remember, there's no sub shell
  489. if (( wd_extglob_is_set == 0 )); then
  490. setopt extendedglob
  491. fi
  492. unset wd_extglob_is_set
  493. unset wd_warp
  494. unset wd_add
  495. unset wd_addcd
  496. unset wd_remove
  497. unset wd_show
  498. unset wd_list_all
  499. unset wd_print_msg
  500. unset wd_yesorno
  501. unset wd_print_usage
  502. unset wd_alt_config
  503. unset wd_quiet_mode
  504. unset wd_print_version
  505. unset wd_export_static_named_directories
  506. unset wd_o
  507. unset args
  508. unset points
  509. unset val &> /dev/null # fixes issue #1
  510. return $WD_EXIT_CODE