wd.sh 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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.5.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
  52. local msg=$2
  53. if [[ $color == "" || $msg == "" ]]
  54. then
  55. print " ${WD_RED}*${WD_NOC} Could not print message. Sorry!"
  56. else
  57. print " ${color}*${WD_NOC} ${msg}"
  58. fi
  59. fi
  60. }
  61. wd_print_usage()
  62. {
  63. command cat <<- EOF
  64. Usage: wd [command] [point]
  65. Commands:
  66. <point> Warps to the directory specified by the warp point
  67. <point> <path> Warps to the directory specified by the warp point with path appended
  68. add <point> Adds the current working directory to your warp points
  69. add Adds the current working directory to your warp points with current directory's name
  70. rm <point> Removes the given warp point
  71. rm Removes the given warp point with current directory's name
  72. show <point> Print path to given warp point
  73. show Print warp points to current directory
  74. list Print all stored warp points
  75. ls <point> Show files from given warp point (ls)
  76. path <point> Show the path to given warp point (pwd)
  77. clean Remove points warping to nonexistent directories (will prompt unless --force is used)
  78. -v | --version Print version
  79. -d | --debug Exit after execution with exit codes (for testing)
  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_remove()
  177. {
  178. local point_list=$1
  179. if [[ "$point_list" == "" ]]
  180. then
  181. point_list=$(basename "$PWD")
  182. fi
  183. for point_name in $point_list ; do
  184. if [[ ${points[$point_name]} != "" ]]
  185. then
  186. local config_tmp=$(mktemp "${TMPDIR:-/tmp}/wd.XXXXXXXXXX")
  187. # Copy and delete in two steps in order to preserve symlinks
  188. if sed -n "/^${point_name}:.*$/!p" "$WD_CONFIG" >| "$config_tmp" && command cp "$config_tmp" "$WD_CONFIG" && command rm "$config_tmp"
  189. then
  190. wd_print_msg "$WD_GREEN" "Warp point removed"
  191. else
  192. wd_exit_fail "Something bad happened! Sorry."
  193. fi
  194. else
  195. wd_exit_fail "Warp point was not found"
  196. fi
  197. done
  198. }
  199. wd_list_all()
  200. {
  201. wd_print_msg "$WD_BLUE" "All warp points:"
  202. entries=$(sed "s:${HOME}:~:g" "$WD_CONFIG")
  203. max_warp_point_length=0
  204. while IFS= read -r line
  205. do
  206. arr=(${(s,:,)line})
  207. key=${arr[1]}
  208. length=${#key}
  209. if [[ length -gt max_warp_point_length ]]
  210. then
  211. max_warp_point_length=$length
  212. fi
  213. done <<< "$entries"
  214. while IFS= read -r line
  215. do
  216. if [[ $line != "" ]]
  217. then
  218. arr=(${(s,:,)line})
  219. key=${arr[1]}
  220. val=${line#"${arr[1]}:"}
  221. if [[ -z $wd_quiet_mode ]]
  222. then
  223. printf "%${max_warp_point_length}s -> %s\n" "$key" "$val"
  224. fi
  225. fi
  226. done <<< "$entries"
  227. }
  228. wd_ls()
  229. {
  230. wd_getdir "$1"
  231. ls "${dir/#\~/$HOME}"
  232. }
  233. wd_path()
  234. {
  235. wd_getdir "$1"
  236. echo "$(echo "$dir" | sed "s:~:${HOME}:g")"
  237. }
  238. wd_show()
  239. {
  240. local name_arg=$1
  241. # if there's an argument we look up the value
  242. if [[ -n $name_arg ]]
  243. then
  244. if [[ -z $points[$name_arg] ]]
  245. then
  246. wd_print_msg "$WD_BLUE" "No warp point named $name_arg"
  247. else
  248. wd_print_msg "$WD_GREEN" "Warp point: ${WD_GREEN}$name_arg${WD_NOC} -> $points[$name_arg]"
  249. fi
  250. else
  251. # hax to create a local empty array
  252. local wd_matches
  253. wd_matches=()
  254. # do a reverse lookup to check whether PWD is in $points
  255. PWD="${PWD/$HOME/~}"
  256. if [[ ${points[(r)$PWD]} == "$PWD" ]]
  257. then
  258. for name in ${(k)points}
  259. do
  260. if [[ $points[$name] == "$PWD" ]]
  261. then
  262. wd_matches[$(($#wd_matches+1))]=$name
  263. fi
  264. done
  265. wd_print_msg "$WD_BLUE" "$#wd_matches warp point(s) to current directory: ${WD_GREEN}$wd_matches${WD_NOC}"
  266. else
  267. wd_print_msg "$WD_YELLOW" "No warp point to $(echo "$PWD" | sed "s:$HOME:~:")"
  268. fi
  269. fi
  270. }
  271. wd_clean() {
  272. local force=$1
  273. local count=0
  274. local wd_tmp=""
  275. while read -r line
  276. do
  277. if [[ $line != "" ]]
  278. then
  279. arr=(${(s,:,)line})
  280. key=${arr[1]}
  281. val=${arr[2]}
  282. if [ -d "${val/#\~/$HOME}" ]
  283. then
  284. wd_tmp=$wd_tmp"\n"`echo "$line"`
  285. else
  286. wd_print_msg "$WD_YELLOW" "Nonexistent directory: ${key} -> ${val}"
  287. count=$((count+1))
  288. fi
  289. fi
  290. done < "$WD_CONFIG"
  291. if [[ $count -eq 0 ]]
  292. then
  293. wd_print_msg "$WD_BLUE" "No warp points to clean, carry on!"
  294. else
  295. if [ ! -z "$force" ] || wd_yesorno "Removing ${count} warp points. Continue? (y/n)"
  296. then
  297. echo "$wd_tmp" >! "$WD_CONFIG"
  298. wd_print_msg "$WD_GREEN" "Cleanup complete. ${count} warp point(s) removed"
  299. else
  300. wd_print_msg "$WD_BLUE" "Cleanup aborted"
  301. fi
  302. fi
  303. }
  304. wd_export_static_named_directories() {
  305. if [[ ! -z $WD_EXPORT ]]
  306. then
  307. command grep '^[0-9a-zA-Z_-]\+:' "$WD_CONFIG" | sed -e "s,~,$HOME," -e 's/:/=/' | while read -r warpdir ; do
  308. hash -d "$warpdir"
  309. done
  310. fi
  311. }
  312. local WD_CONFIG=${WD_CONFIG:-$HOME/.warprc}
  313. local WD_QUIET=0
  314. local WD_EXIT_CODE=0
  315. local WD_DEBUG=0
  316. # Parse 'meta' options first to avoid the need to have them before
  317. # other commands. The `-D` flag consumes recognized options so that
  318. # the actual command parsing won't be affected.
  319. zparseopts -D -E \
  320. c:=wd_alt_config -config:=wd_alt_config \
  321. q=wd_quiet_mode -quiet=wd_quiet_mode \
  322. v=wd_print_version -version=wd_print_version \
  323. d=wd_debug_mode -debug=wd_debug_mode \
  324. f=wd_force_mode -force=wd_force_mode
  325. if [[ ! -z $wd_print_version ]]
  326. then
  327. echo "wd version $WD_VERSION"
  328. fi
  329. if [[ ! -z $wd_alt_config ]]
  330. then
  331. WD_CONFIG=$wd_alt_config[2]
  332. fi
  333. # check if config file exists
  334. if [ ! -e "$WD_CONFIG" ]
  335. then
  336. # if not, create config file
  337. touch "$WD_CONFIG"
  338. else
  339. wd_export_static_named_directories
  340. fi
  341. # disable extendedglob for the complete wd execution time
  342. setopt | grep -q extendedglob
  343. wd_extglob_is_set=$?
  344. [[ $wd_extglob_is_set ]] && setopt noextendedglob
  345. # load warp points
  346. typeset -A points
  347. while read -r line
  348. do
  349. arr=(${(s,:,)line})
  350. key=${arr[1]}
  351. # join the rest, in case the path contains colons
  352. val=${(j,:,)arr[2,-1]}
  353. points[$key]=$val
  354. done < "$WD_CONFIG"
  355. # get opts
  356. args=$(getopt -o a:r:c:lhs -l add:,rm:,clean,list,ls:,path:,help,show -- $*)
  357. # check if no arguments were given, and that version is not set
  358. if [[ ($? -ne 0 || $#* -eq 0) && -z $wd_print_version ]]
  359. then
  360. wd_print_usage
  361. # check if config file is writeable
  362. elif [ ! -w "$WD_CONFIG" ]
  363. then
  364. # do nothing
  365. # can't run `exit`, as this would exit the executing shell
  366. wd_exit_fail "\'$WD_CONFIG\' is not writeable."
  367. else
  368. # parse rest of options
  369. local wd_o
  370. for wd_o
  371. do
  372. case "$wd_o"
  373. in
  374. "-a"|"--add"|"add")
  375. wd_add "$2" "$wd_force_mode"
  376. break
  377. ;;
  378. "-e"|"export")
  379. wd_export_static_named_directories
  380. break
  381. ;;
  382. "-r"|"--remove"|"rm")
  383. # Passes all the arguments as a single string separated by whitespace to wd_remove
  384. wd_remove "${@:2}"
  385. break
  386. ;;
  387. "-l"|"list")
  388. wd_list_all
  389. break
  390. ;;
  391. "-ls"|"ls")
  392. wd_ls "$2"
  393. break
  394. ;;
  395. "-p"|"--path"|"path")
  396. wd_path "$2"
  397. break
  398. ;;
  399. "-h"|"--help"|"help")
  400. wd_print_usage
  401. break
  402. ;;
  403. "-s"|"--show"|"show")
  404. wd_show "$2"
  405. break
  406. ;;
  407. "-c"|"--clean"|"clean")
  408. wd_clean "$wd_force_mode"
  409. break
  410. ;;
  411. *)
  412. wd_warp "$wd_o" "$2"
  413. break
  414. ;;
  415. --)
  416. break
  417. ;;
  418. esac
  419. done
  420. fi
  421. ## garbage collection
  422. # if not, next time warp will pick up variables from this run
  423. # remember, there's no sub shell
  424. [[ $wd_extglob_is_set ]] && setopt extendedglob
  425. unset wd_extglob_is_set
  426. unset wd_warp
  427. unset wd_add
  428. unset wd_remove
  429. unset wd_show
  430. unset wd_list_all
  431. unset wd_print_msg
  432. unset wd_yesorno
  433. unset wd_print_usage
  434. unset wd_alt_config
  435. unset wd_quiet_mode
  436. unset wd_print_version
  437. unset wd_export_static_named_directories
  438. unset wd_o
  439. unset args
  440. unset points
  441. unset val &> /dev/null # fixes issue #1
  442. if [[ -n $wd_debug_mode ]]
  443. then
  444. exit $WD_EXIT_CODE
  445. else
  446. unset wd_debug_mode
  447. fi