wd.sh 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. #!/bin/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.7.0
  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. -d | --debug Exit after execution with exit codes (for testing)
  81. -c | --config Specify config file (default ~/.warprc)
  82. -q | --quiet Suppress all output
  83. -f | --force Allows overwriting without warning (for add & clean)
  84. help Show this extremely helpful text
  85. EOF
  86. }
  87. wd_exit_fail()
  88. {
  89. local msg=$1
  90. wd_print_msg "$WD_RED" "$msg"
  91. WD_EXIT_CODE=1
  92. }
  93. wd_exit_warn()
  94. {
  95. local msg=$1
  96. wd_print_msg "$WD_YELLOW" "$msg"
  97. WD_EXIT_CODE=1
  98. }
  99. wd_getdir()
  100. {
  101. local name_arg=$1
  102. point=$(wd_show "$name_arg")
  103. dir=${point:28+$#name_arg+7}
  104. if [[ -z $name_arg ]]; then
  105. wd_exit_fail "You must enter a warp point"
  106. break
  107. elif [[ -z $dir ]]; then
  108. wd_exit_fail "Unknown warp point '${name_arg}'"
  109. break
  110. fi
  111. }
  112. # core
  113. wd_warp()
  114. {
  115. local point=$1
  116. local sub=$2
  117. if [[ $point =~ "^\.+$" ]]
  118. then
  119. if [[ $#1 < 2 ]]
  120. then
  121. wd_exit_warn "Warping to current directory?"
  122. else
  123. (( n = $#1 - 1 ))
  124. cd -$n > /dev/null
  125. fi
  126. elif [[ ${points[$point]} != "" ]]
  127. then
  128. if [[ $sub != "" ]]
  129. then
  130. cd ${points[$point]/#\~/$HOME}/$sub
  131. else
  132. cd ${points[$point]/#\~/$HOME}
  133. fi
  134. else
  135. wd_exit_fail "Unknown warp point '${point}'"
  136. fi
  137. }
  138. wd_add()
  139. {
  140. local point=$1
  141. local force=$2
  142. cmdnames=(add rm show list ls path clean help)
  143. if [[ $point == "" ]]
  144. then
  145. point=$(basename "$PWD")
  146. fi
  147. if [[ $point =~ "^[\.]+$" ]]
  148. then
  149. wd_exit_fail "Warp point cannot be just dots"
  150. elif [[ $point =~ "[[:space:]]+" ]]
  151. then
  152. wd_exit_fail "Warp point should not contain whitespace"
  153. elif [[ $point =~ : ]] || [[ $point =~ / ]]
  154. then
  155. wd_exit_fail "Warp point contains illegal character (:/)"
  156. elif (($cmdnames[(Ie)$point]))
  157. then
  158. wd_exit_fail "Warp point name cannot be a wd command (see wd -h for a full list)"
  159. elif [[ ${points[$point]} == "" ]] || [ ! -z "$force" ]
  160. then
  161. wd_remove "$point" > /dev/null
  162. printf "%q:%s\n" "${point}" "${PWD/#$HOME/~}" >> "$WD_CONFIG"
  163. if (whence sort >/dev/null); then
  164. local config_tmp=$(mktemp "${TMPDIR:-/tmp}/wd.XXXXXXXXXX")
  165. # use 'cat' below to ensure we respect $WD_CONFIG as a symlink
  166. command sort -o "${config_tmp}" "$WD_CONFIG" && command cat "${config_tmp}" >| "$WD_CONFIG" && command rm "${config_tmp}"
  167. fi
  168. wd_export_static_named_directories
  169. wd_print_msg "$WD_GREEN" "Warp point added"
  170. # override exit code in case wd_remove did not remove any points
  171. # TODO: we should handle this kind of logic better
  172. WD_EXIT_CODE=0
  173. else
  174. wd_exit_warn "Warp point '${point}' already exists. Use 'add --force' to overwrite."
  175. fi
  176. }
  177. wd_addcd() {
  178. local folder="$1"
  179. local point=$2
  180. local force=$3
  181. local currentdir=$PWD
  182. if [[ -z "$folder" ]]; then
  183. wd_exit_fail "You must specify a path"
  184. return
  185. fi
  186. if [[ ! -d "$folder" ]]; then
  187. wd_exit_fail "The directory does not exist"
  188. return
  189. fi
  190. cd "$folder" || return
  191. wd_add "$point" "$force"
  192. cd "$currentdir" || return
  193. }
  194. wd_remove()
  195. {
  196. local point_list=$1
  197. if [[ "$point_list" == "" ]]
  198. then
  199. point_list=$(basename "$PWD")
  200. fi
  201. for point_name in $point_list ; do
  202. if [[ ${points[$point_name]} != "" ]]
  203. then
  204. local config_tmp=$(mktemp "${TMPDIR:-/tmp}/wd.XXXXXXXXXX")
  205. # Copy and delete in two steps in order to preserve symlinks
  206. if sed -n "/^${point_name}:.*$/!p" "$WD_CONFIG" >| "$config_tmp" && command cp "$config_tmp" "$WD_CONFIG" && command rm "$config_tmp"
  207. then
  208. wd_print_msg "$WD_GREEN" "Warp point removed"
  209. else
  210. wd_exit_fail "Something bad happened! Sorry."
  211. fi
  212. else
  213. wd_exit_fail "Warp point was not found"
  214. fi
  215. done
  216. }
  217. wd_browse() {
  218. if ! command -v fzf >/dev/null; then
  219. echo "This functionality requires fzf. Please install fzf first."
  220. return 1
  221. fi
  222. local entries=("${(@f)$(sed "s:${HOME}:~:g" "$WD_CONFIG" | awk -F ':' '{print $1 " -> " $2}')}")
  223. local script_path="${${(%):-%x}:h}"
  224. local wd_remove_output=$(mktemp "${TMPDIR:-/tmp}/wd.XXXXXXXXXX")
  225. entries=("All warp points:" "Press enter to select. Press delete to remove" "${entries[@]}")
  226. local fzf_bind="delete:execute(echo {} | awk -F ' -> ' '{print \$1}' | xargs -I {} "$script_path/wd.sh" rm {} > "$wd_remove_output")+abort"
  227. local selected_entry=$(printf '%s\n' "${entries[@]}" | fzf --height 100% --reverse --header-lines=2 --bind="$fzf_bind")
  228. if [[ -e $wd_remove_output ]]; then
  229. cat "$wd_remove_output"
  230. rm "$wd_remove_output"
  231. fi
  232. if [[ -n $selected_entry ]]; then
  233. local selected_point="${selected_entry%% ->*}"
  234. selected_point=$(echo "$selected_point" | xargs)
  235. wd $selected_point
  236. fi
  237. }
  238. wd_browse_widget() {
  239. if [[ -e $WD_CONFIG ]]; then
  240. wd_browse
  241. saved_buffer=$BUFFER
  242. saved_cursor=$CURSOR
  243. BUFFER=
  244. zle redisplay
  245. zle accept-line
  246. fi
  247. }
  248. wd_restore_buffer() {
  249. if [[ -n $saved_buffer ]]; then
  250. BUFFER=$saved_buffer
  251. CURSOR=$saved_cursor
  252. fi
  253. saved_buffer=
  254. saved_cursor=1
  255. }
  256. wd_list_all()
  257. {
  258. wd_print_msg "$WD_BLUE" "All warp points:"
  259. entries=$(sed "s:${HOME}:~:g" "$WD_CONFIG")
  260. max_warp_point_length=0
  261. while IFS= read -r line
  262. do
  263. arr=(${(s,:,)line})
  264. key=${arr[1]}
  265. length=${#key}
  266. if [[ length -gt max_warp_point_length ]]
  267. then
  268. max_warp_point_length=$length
  269. fi
  270. done <<< "$entries"
  271. while IFS= read -r line
  272. do
  273. if [[ $line != "" ]]
  274. then
  275. arr=(${(s,:,)line})
  276. key=${arr[1]}
  277. val=${line#"${arr[1]}:"}
  278. if [[ -z $wd_quiet_mode ]]
  279. then
  280. printf "%${max_warp_point_length}s -> %s\n" "$key" "$val"
  281. fi
  282. fi
  283. done <<< "$entries"
  284. }
  285. wd_ls()
  286. {
  287. wd_getdir "$1"
  288. ls "${dir/#\~/$HOME}"
  289. }
  290. wd_path()
  291. {
  292. wd_getdir "$1"
  293. echo "$(echo "$dir" | sed "s:~:${HOME}:g")"
  294. }
  295. wd_show()
  296. {
  297. local name_arg=$1
  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. PWD="${PWD/$HOME/~}"
  313. if [[ ${points[(r)$PWD]} == "$PWD" ]]
  314. then
  315. for name in ${(k)points}
  316. do
  317. if [[ $points[$name] == "$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 $(echo "$PWD" | sed "s:$HOME:~:")"
  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. local WD_DEBUG=0
  373. # Parse 'meta' options first to avoid the need to have them before
  374. # other commands. The `-D` flag consumes recognized options so that
  375. # the actual command parsing won't be affected.
  376. zparseopts -D -E \
  377. c:=wd_alt_config -config:=wd_alt_config \
  378. q=wd_quiet_mode -quiet=wd_quiet_mode \
  379. v=wd_print_version -version=wd_print_version \
  380. d=wd_debug_mode -debug=wd_debug_mode \
  381. f=wd_force_mode -force=wd_force_mode
  382. if [[ ! -z $wd_print_version ]]
  383. then
  384. echo "wd version $WD_VERSION"
  385. fi
  386. if [[ ! -z $wd_alt_config ]]
  387. then
  388. WD_CONFIG=$wd_alt_config[2]
  389. fi
  390. # check if config file exists
  391. if [ ! -e "$WD_CONFIG" ]
  392. then
  393. # if not, create config file
  394. touch "$WD_CONFIG"
  395. else
  396. wd_export_static_named_directories
  397. fi
  398. # disable extendedglob for the complete wd execution time
  399. setopt | grep -q extendedglob
  400. wd_extglob_is_set=$?
  401. if (( wd_extglob_is_set == 0 )); then
  402. setopt noextendedglob
  403. fi
  404. # load warp points
  405. typeset -A points
  406. while read -r line
  407. do
  408. arr=(${(s,:,)line})
  409. key=${arr[1]}
  410. # join the rest, in case the path contains colons
  411. val=${(j,:,)arr[2,-1]}
  412. points[$key]=$val
  413. done < "$WD_CONFIG"
  414. # get opts
  415. args=$(getopt -o a:r:c:lhs -l add:,rm:,clean,list,ls:,path:,help,show -- $*)
  416. # check if no arguments were given, and that version is not set
  417. if [[ ($? -ne 0 || $#* -eq 0) && -z $wd_print_version ]]
  418. then
  419. wd_print_usage
  420. # check if config file is writeable
  421. elif [ ! -w "$WD_CONFIG" ]
  422. then
  423. # do nothing
  424. # can't run `exit`, as this would exit the executing shell
  425. wd_exit_fail "\'$WD_CONFIG\' is not writeable."
  426. else
  427. # parse rest of options
  428. local wd_o
  429. for wd_o
  430. do
  431. case "$wd_o"
  432. in
  433. "-a"|"--add"|"add")
  434. wd_add "$2" "$wd_force_mode"
  435. break
  436. ;;
  437. "-b"|"browse")
  438. wd_browse
  439. break
  440. ;;
  441. "-c"|"--addcd"|"addcd")
  442. wd_addcd "$2" "$3" "$wd_force_mode"
  443. break
  444. ;;
  445. "-e"|"export")
  446. wd_export_static_named_directories
  447. break
  448. ;;
  449. "-r"|"--remove"|"rm")
  450. # Passes all the arguments as a single string separated by whitespace to wd_remove
  451. wd_remove "${@:2}"
  452. break
  453. ;;
  454. "-l"|"list")
  455. wd_list_all
  456. break
  457. ;;
  458. "-ls"|"ls")
  459. wd_ls "$2"
  460. break
  461. ;;
  462. "-p"|"--path"|"path")
  463. wd_path "$2"
  464. break
  465. ;;
  466. "-h"|"--help"|"help")
  467. wd_print_usage
  468. break
  469. ;;
  470. "-s"|"--show"|"show")
  471. wd_show "$2"
  472. break
  473. ;;
  474. "-c"|"--clean"|"clean")
  475. wd_clean "$wd_force_mode"
  476. break
  477. ;;
  478. *)
  479. wd_warp "$wd_o" "$2"
  480. break
  481. ;;
  482. --)
  483. break
  484. ;;
  485. esac
  486. done
  487. fi
  488. ## garbage collection
  489. # if not, next time warp will pick up variables from this run
  490. # remember, there's no sub shell
  491. if (( wd_extglob_is_set == 0 )); then
  492. setopt extendedglob
  493. fi
  494. unset wd_extglob_is_set
  495. unset wd_warp
  496. unset wd_add
  497. unset wd_addcd
  498. unset wd_remove
  499. unset wd_show
  500. unset wd_list_all
  501. unset wd_print_msg
  502. unset wd_yesorno
  503. unset wd_print_usage
  504. unset wd_alt_config
  505. unset wd_quiet_mode
  506. unset wd_print_version
  507. unset wd_export_static_named_directories
  508. unset wd_o
  509. unset args
  510. unset points
  511. unset val &> /dev/null # fixes issue #1
  512. if [[ -n $wd_debug_mode ]]
  513. then
  514. exit $WD_EXIT_CODE
  515. else
  516. unset wd_debug_mode
  517. fi