wd.sh 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  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.2
  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. WD_EXIT_CODE=$?
  125. fi
  126. elif [[ ${points[$point]} != "" ]]
  127. then
  128. if [[ $sub != "" ]]
  129. then
  130. cd ${points[$point]/#\~/$HOME}/$sub
  131. WD_EXIT_CODE=$?
  132. else
  133. cd ${points[$point]/#\~/$HOME}
  134. WD_EXIT_CODE=$?
  135. fi
  136. else
  137. wd_exit_fail "Unknown warp point '${point}'"
  138. fi
  139. }
  140. wd_add()
  141. {
  142. local point=$1
  143. local force=$2
  144. cmdnames=(add rm show list ls path clean help)
  145. if [[ $point == "" ]]
  146. then
  147. point=$(basename "$PWD")
  148. fi
  149. if [[ $point =~ "^[\.]+$" ]]
  150. then
  151. wd_exit_fail "Warp point cannot be just dots"
  152. elif [[ $point =~ "[[:space:]]+" ]]
  153. then
  154. wd_exit_fail "Warp point should not contain whitespace"
  155. elif [[ $point =~ : ]] || [[ $point =~ / ]]
  156. then
  157. wd_exit_fail "Warp point contains illegal character (:/)"
  158. elif (($cmdnames[(Ie)$point]))
  159. then
  160. wd_exit_fail "Warp point name cannot be a wd command (see wd -h for a full list)"
  161. elif [[ ${points[$point]} == "" ]] || [ ! -z "$force" ]
  162. then
  163. wd_remove "$point" > /dev/null
  164. printf "%q:%s\n" "${point}" "${PWD/#$HOME/~}" >> "$wd_config_file"
  165. if (whence sort >/dev/null); then
  166. local config_tmp=$(mktemp "${TMPDIR:-/tmp}/wd.XXXXXXXXXX")
  167. # use 'cat' below to ensure we respect $wd_config_file as a symlink
  168. command sort -o "${config_tmp}" "$wd_config_file" && command cat "${config_tmp}" >| "$wd_config_file" && command rm "${config_tmp}"
  169. fi
  170. wd_export_static_named_directories
  171. wd_print_msg "$WD_GREEN" "Warp point added"
  172. # override exit code in case wd_remove did not remove any points
  173. # TODO: we should handle this kind of logic better
  174. WD_EXIT_CODE=0
  175. else
  176. wd_exit_warn "Warp point '${point}' already exists. Use 'add --force' to overwrite."
  177. fi
  178. }
  179. wd_addcd() {
  180. local folder="$1"
  181. local point=$2
  182. local force=$3
  183. local currentdir=$PWD
  184. if [[ -z "$folder" ]]; then
  185. wd_exit_fail "You must specify a path"
  186. return
  187. fi
  188. if [[ ! -d "$folder" ]]; then
  189. wd_exit_fail "The directory does not exist"
  190. return
  191. fi
  192. cd "$folder" || return
  193. wd_add "$point" "$force"
  194. cd "$currentdir" || return
  195. }
  196. wd_remove()
  197. {
  198. local point_list=$1
  199. if [[ "$point_list" == "" ]]
  200. then
  201. point_list=$(basename "$PWD")
  202. fi
  203. for point_name in $point_list ; do
  204. if [[ ${points[$point_name]} != "" ]]
  205. then
  206. local config_tmp=$(mktemp "${TMPDIR:-/tmp}/wd.XXXXXXXXXX")
  207. # Copy and delete in two steps in order to preserve symlinks
  208. if sed -n "/^${point_name}:.*$/!p" "$wd_config_file" >| "$config_tmp" && command cp "$config_tmp" "$wd_config_file" && command rm "$config_tmp"
  209. then
  210. wd_print_msg "$WD_GREEN" "Warp point removed"
  211. else
  212. wd_exit_fail "Something bad happened! Sorry."
  213. fi
  214. else
  215. wd_exit_fail "Warp point was not found"
  216. fi
  217. done
  218. }
  219. wd_browse() {
  220. if ! command -v fzf >/dev/null; then
  221. echo "This functionality requires fzf. Please install fzf first."
  222. return 1
  223. fi
  224. local entries=("${(@f)$(sed "s:${HOME}:~:g" "$wd_config_file" | awk -F ':' '{print $1 " -> " $2}')}")
  225. local script_path="${${(%):-%x}:h}"
  226. local wd_remove_output=$(mktemp "${TMPDIR:-/tmp}/wd.XXXXXXXXXX")
  227. entries=("All warp points:" "Press enter to select. Press delete to remove" "${entries[@]}")
  228. local fzf_bind="delete:execute(echo {} | awk -F ' -> ' '{print \$1}' | xargs -I {} "$script_path/wd.sh" rm {} > "$wd_remove_output")+abort"
  229. local selected_entry=$(printf '%s\n' "${entries[@]}" | fzf --height 100% --reverse --header-lines=2 --bind="$fzf_bind")
  230. if [[ -e $wd_remove_output ]]; then
  231. cat "$wd_remove_output"
  232. rm "$wd_remove_output"
  233. fi
  234. if [[ -n $selected_entry ]]; then
  235. local selected_point="${selected_entry%% ->*}"
  236. selected_point=$(echo "$selected_point" | xargs)
  237. wd $selected_point
  238. fi
  239. }
  240. wd_browse_widget() {
  241. if [[ -e $wd_config_file ]]; then
  242. wd_browse
  243. saved_buffer=$BUFFER
  244. saved_cursor=$CURSOR
  245. BUFFER=
  246. zle redisplay
  247. zle accept-line
  248. fi
  249. }
  250. wd_restore_buffer() {
  251. if [[ -n $saved_buffer ]]; then
  252. BUFFER=$saved_buffer
  253. CURSOR=$saved_cursor
  254. fi
  255. saved_buffer=
  256. saved_cursor=1
  257. }
  258. wd_list_all()
  259. {
  260. wd_print_msg "$WD_BLUE" "All warp points:"
  261. entries=$(sed "s:${HOME}:~:g" "$wd_config_file")
  262. max_warp_point_length=0
  263. while IFS= read -r line
  264. do
  265. arr=(${(s,:,)line})
  266. key=${arr[1]}
  267. length=${#key}
  268. if [[ length -gt max_warp_point_length ]]
  269. then
  270. max_warp_point_length=$length
  271. fi
  272. done <<< "$entries"
  273. while IFS= read -r line
  274. do
  275. if [[ $line != "" ]]
  276. then
  277. arr=(${(s,:,)line})
  278. key=${arr[1]}
  279. val=${line#"${arr[1]}:"}
  280. if [[ -z $wd_quiet_mode ]]
  281. then
  282. printf "%${max_warp_point_length}s -> %s\n" "$key" "$val"
  283. fi
  284. fi
  285. done <<< "$entries"
  286. }
  287. wd_ls()
  288. {
  289. wd_getdir "$1"
  290. ls "${dir/#\~/$HOME}"
  291. }
  292. wd_path()
  293. {
  294. wd_getdir "$1"
  295. echo "$(echo "$dir" | sed "s:~:${HOME}:g")"
  296. }
  297. wd_show()
  298. {
  299. local name_arg=$1
  300. local show_pwd
  301. # if there's an argument we look up the value
  302. if [[ -n $name_arg ]]
  303. then
  304. if [[ -z $points[$name_arg] ]]
  305. then
  306. wd_print_msg "$WD_BLUE" "No warp point named $name_arg"
  307. else
  308. wd_print_msg "$WD_GREEN" "Warp point: ${WD_GREEN}$name_arg${WD_NOC} -> $points[$name_arg]"
  309. fi
  310. else
  311. # hax to create a local empty array
  312. local wd_matches
  313. wd_matches=()
  314. # do a reverse lookup to check whether PWD is in $points
  315. show_pwd="${PWD/$HOME/~}"
  316. if [[ ${points[(r)$show_pwd]} == "$show_pwd" ]]
  317. then
  318. for name in ${(k)points}
  319. do
  320. if [[ $points[$name] == "$show_pwd" ]]
  321. then
  322. wd_matches[$(($#wd_matches+1))]=$name
  323. fi
  324. done
  325. wd_print_msg "$WD_BLUE" "$#wd_matches warp point(s) to current directory: ${WD_GREEN}$wd_matches${WD_NOC}"
  326. else
  327. wd_print_msg "$WD_YELLOW" "No warp point to $show_pwd"
  328. fi
  329. fi
  330. }
  331. wd_clean() {
  332. local force=$1
  333. local count=0
  334. local wd_tmp=""
  335. while read -r line
  336. do
  337. if [[ $line != "" ]]
  338. then
  339. arr=(${(s,:,)line})
  340. key=${arr[1]}
  341. val=${arr[2]}
  342. if [ -d "${val/#\~/$HOME}" ]
  343. then
  344. wd_tmp=$wd_tmp"\n"`echo "$line"`
  345. else
  346. wd_print_msg "$WD_YELLOW" "Nonexistent directory: ${key} -> ${val}"
  347. count=$((count+1))
  348. fi
  349. fi
  350. done < "$wd_config_file"
  351. if [[ $count -eq 0 ]]
  352. then
  353. wd_print_msg "$WD_BLUE" "No warp points to clean, carry on!"
  354. else
  355. if [ ! -z "$force" ] || wd_yesorno "Removing ${count} warp points. Continue? (y/n)"
  356. then
  357. echo "$wd_tmp" >! "$wd_config_file"
  358. wd_print_msg "$WD_GREEN" "Cleanup complete. ${count} warp point(s) removed"
  359. else
  360. wd_print_msg "$WD_BLUE" "Cleanup aborted"
  361. fi
  362. fi
  363. }
  364. wd_export_static_named_directories() {
  365. if [[ ! -z $WD_EXPORT ]]
  366. then
  367. command grep '^[0-9a-zA-Z_-]\+:' "$wd_config_file" | sed -e "s,~,$HOME," -e 's/:/=/' | while read -r warpdir ; do
  368. hash -d "$warpdir"
  369. done
  370. fi
  371. }
  372. WD_CONFIG=${WD_CONFIG:-$HOME/.warprc}
  373. local WD_QUIET=0
  374. local WD_EXIT_CODE=0
  375. # Parse 'meta' options first to avoid the need to have them before
  376. # other commands. The `-D` flag consumes recognized options so that
  377. # the actual command parsing won't be affected.
  378. zparseopts -D -E \
  379. c:=wd_alt_config -config:=wd_alt_config \
  380. q=wd_quiet_mode -quiet=wd_quiet_mode \
  381. v=wd_print_version -version=wd_print_version \
  382. f=wd_force_mode -force=wd_force_mode
  383. if [[ ! -z $wd_print_version ]]
  384. then
  385. echo "wd version $WD_VERSION"
  386. fi
  387. # set the config file from variable or default
  388. typeset wd_config_file=${WD_CONFIG:-$HOME/.warprc}
  389. if [[ ! -z $wd_alt_config ]]
  390. then
  391. # prefer the flag if provided
  392. wd_config_file=$wd_alt_config[2]
  393. fi
  394. # check if config file exists
  395. if [ ! -e "$wd_config_file" ]
  396. then
  397. # if not, create config file
  398. touch "$wd_config_file"
  399. else
  400. wd_export_static_named_directories
  401. fi
  402. # disable extendedglob for the complete wd execution time
  403. setopt | grep -q extendedglob
  404. wd_extglob_is_set=$?
  405. if (( wd_extglob_is_set == 0 )); then
  406. setopt noextendedglob
  407. fi
  408. # load warp points
  409. typeset -A points
  410. while read -r line
  411. do
  412. arr=(${(s,:,)line})
  413. key=${arr[1]}
  414. # join the rest, in case the path contains colons
  415. val=${(j,:,)arr[2,-1]}
  416. points[$key]=$val
  417. done < "$wd_config_file"
  418. # get opts
  419. args=$(getopt -o a:r:c:lhs -l add:,rm:,clean,list,ls:,path:,help,show -- $*)
  420. # check if no arguments were given, and that version is not set
  421. if [[ ($? -ne 0 || $#* -eq 0) && -z $wd_print_version ]]
  422. then
  423. wd_print_usage
  424. # check if config file is writeable
  425. elif [ ! -w "$wd_config_file" ]
  426. then
  427. # do nothing
  428. # can't run `exit`, as this would exit the executing shell
  429. wd_exit_fail "\'$wd_config_file\' is not writeable."
  430. else
  431. # parse rest of options
  432. local wd_o
  433. for wd_o
  434. do
  435. case "$wd_o"
  436. in
  437. "-a"|"--add"|"add")
  438. wd_add "$2" "$wd_force_mode"
  439. break
  440. ;;
  441. "-b"|"browse")
  442. wd_browse
  443. break
  444. ;;
  445. "-c"|"--addcd"|"addcd")
  446. wd_addcd "$2" "$3" "$wd_force_mode"
  447. break
  448. ;;
  449. "-e"|"export")
  450. wd_export_static_named_directories
  451. break
  452. ;;
  453. "-r"|"--remove"|"rm")
  454. # Passes all the arguments as a single string separated by whitespace to wd_remove
  455. wd_remove "${@:2}"
  456. break
  457. ;;
  458. "-l"|"list")
  459. wd_list_all
  460. break
  461. ;;
  462. "-ls"|"ls")
  463. wd_ls "$2"
  464. break
  465. ;;
  466. "-p"|"--path"|"path")
  467. wd_path "$2"
  468. break
  469. ;;
  470. "-h"|"--help"|"help")
  471. wd_print_usage
  472. break
  473. ;;
  474. "-s"|"--show"|"show")
  475. wd_show "$2"
  476. break
  477. ;;
  478. "-c"|"--clean"|"clean")
  479. wd_clean "$wd_force_mode"
  480. break
  481. ;;
  482. *)
  483. wd_warp "$wd_o" "$2"
  484. break
  485. ;;
  486. --)
  487. break
  488. ;;
  489. esac
  490. done
  491. fi
  492. ## garbage collection
  493. # if not, next time warp will pick up variables from this run
  494. # remember, there's no sub shell
  495. if (( wd_extglob_is_set == 0 )); then
  496. setopt extendedglob
  497. fi
  498. unset wd_extglob_is_set
  499. unset wd_warp
  500. unset wd_add
  501. unset wd_addcd
  502. unset wd_remove
  503. unset wd_show
  504. unset wd_list_all
  505. unset wd_print_msg
  506. unset wd_yesorno
  507. unset wd_print_usage
  508. unset wd_alt_config
  509. unset wd_config_file
  510. unset wd_quiet_mode
  511. unset wd_print_version
  512. unset wd_force_mode
  513. unset wd_export_static_named_directories
  514. unset wd_o
  515. unset args
  516. unset points
  517. unset val &> /dev/null # fixes issue #1
  518. return $WD_EXIT_CODE