wd.sh 11 KB

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