z.sh 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. # Copyright (c) 2009 rupa deadwyler. Licensed under the WTFPL license, Version 2
  2. # maintains a jump-list of the directories you actually use
  3. #
  4. # INSTALL:
  5. # * put something like this in your .bashrc/.zshrc:
  6. # . /path/to/z.sh
  7. # * cd around for a while to build up the db
  8. # * PROFIT!!
  9. # * optionally:
  10. # set $_Z_CMD in .bashrc/.zshrc to change the command (default z).
  11. # set $_Z_DATA in .bashrc/.zshrc to change the datafile (default ~/.z).
  12. # set $_Z_NO_RESOLVE_SYMLINKS to prevent symlink resolution.
  13. # set $_Z_NO_PROMPT_COMMAND if you're handling PROMPT_COMMAND yourself.
  14. # set $_Z_EXCLUDE_DIRS to an array of directories to exclude.
  15. # set $_Z_OWNER to your username if you want use z while sudo with $HOME kept
  16. #
  17. # USE:
  18. # * z foo # cd to most frecent dir matching foo
  19. # * z foo bar # cd to most frecent dir matching foo and bar
  20. # * z -r foo # cd to highest ranked dir matching foo
  21. # * z -t foo # cd to most recently accessed dir matching foo
  22. # * z -l foo # list matches instead of cd
  23. # * z -e foo # echo the best match, don't cd
  24. # * z -c foo # restrict matches to subdirs of $PWD
  25. [ -d "${_Z_DATA:-$HOME/.z}" ] && {
  26. echo "ERROR: z.sh's datafile (${_Z_DATA:-$HOME/.z}) is a directory."
  27. }
  28. _z() {
  29. local datafile="${_Z_DATA:-$HOME/.z}"
  30. # if symlink, dereference
  31. [ -h "$datafile" ] && datafile=$(readlink "$datafile")
  32. # bail if we don't own ~/.z and $_Z_OWNER not set
  33. [ -z "$_Z_OWNER" -a -f "$datafile" -a ! -O "$datafile" ] && return
  34. _z_dirs () {
  35. local line
  36. while read line; do
  37. # only count directories
  38. [ -d "${line%%\|*}" ] && echo "$line"
  39. done < "$datafile"
  40. return 0
  41. }
  42. # add entries
  43. if [ "$1" = "--add" ]; then
  44. shift
  45. # $HOME isn't worth matching
  46. [ "$*" = "$HOME" ] && return
  47. # don't track excluded directory trees
  48. local exclude
  49. for exclude in "${_Z_EXCLUDE_DIRS[@]}"; do
  50. case "$*" in "$exclude*") return;; esac
  51. done
  52. # maintain the data file
  53. local tempfile="$datafile.$RANDOM"
  54. _z_dirs | awk -v path="$*" -v now="$(date +%s)" -F"|" '
  55. BEGIN {
  56. rank[path] = 1
  57. time[path] = now
  58. }
  59. $2 >= 1 {
  60. # drop ranks below 1
  61. if( $1 == path ) {
  62. rank[$1] = $2 + 1
  63. time[$1] = now
  64. } else {
  65. rank[$1] = $2
  66. time[$1] = $3
  67. }
  68. count += $2
  69. }
  70. END {
  71. if( count > 9000 ) {
  72. # aging
  73. for( x in rank ) print x "|" 0.99*rank[x] "|" time[x]
  74. } else for( x in rank ) print x "|" rank[x] "|" time[x]
  75. }
  76. ' 2>/dev/null >| "$tempfile"
  77. # do our best to avoid clobbering the datafile in a race condition.
  78. if [ $? -ne 0 -a -f "$datafile" ]; then
  79. env rm -f "$tempfile"
  80. else
  81. [ "$_Z_OWNER" ] && chown $_Z_OWNER:"$(id -ng $_Z_OWNER)" "$tempfile"
  82. env mv -f "$tempfile" "$datafile" || env rm -f "$tempfile"
  83. fi
  84. # tab completion
  85. elif [ "$1" = "--complete" -a -s "$datafile" ]; then
  86. _z_dirs | awk -v q="$2" -F"|" '
  87. BEGIN {
  88. q = substr(q, 3)
  89. if( q == tolower(q) ) imatch = 1
  90. gsub(/ /, ".*", q)
  91. }
  92. {
  93. if( imatch ) {
  94. if( tolower($1) ~ q ) print $1
  95. } else if( $1 ~ q ) print $1
  96. }
  97. ' 2>/dev/null
  98. else
  99. # list/go
  100. local echo fnd last list opt typ
  101. while [ "$1" ]; do case "$1" in
  102. --) while [ "$1" ]; do shift; fnd="$fnd${fnd:+ }$1";done;;
  103. -*) opt=${1:1}; while [ "$opt" ]; do case ${opt:0:1} in
  104. c) fnd="^$PWD $fnd";;
  105. e) echo=1;;
  106. h) echo "${_Z_CMD:-z} [-cehlrtx] args" >&2; return;;
  107. l) list=1;;
  108. r) typ="rank";;
  109. t) typ="recent";;
  110. x) sed -i -e "\:^${PWD}|.*:d" "$datafile";;
  111. esac; opt=${opt:1}; done;;
  112. *) fnd="$fnd${fnd:+ }$1";;
  113. esac; last=$1; [ "$#" -gt 0 ] && shift; done
  114. [ "$fnd" -a "$fnd" != "^$PWD " ] || list=1
  115. # if we hit enter on a completion just go there
  116. case "$last" in
  117. # completions will always start with /
  118. /*) [ -z "$list" -a -d "$last" ] && builtin cd "$last" && return;;
  119. esac
  120. # no file yet
  121. [ -f "$datafile" ] || return
  122. local cd
  123. cd="$( < <( _z_dirs ) awk -v t="$(date +%s)" -v list="$list" -v typ="$typ" -v q="$fnd" -F"|" '
  124. function frecent(rank, time) {
  125. # relate frequency and time
  126. dx = t - time
  127. if( dx < 3600 ) return rank * 4
  128. if( dx < 86400 ) return rank * 2
  129. if( dx < 604800 ) return rank / 2
  130. return rank / 4
  131. }
  132. function output(matches, best_match, common) {
  133. # list or return the desired directory
  134. if( list ) {
  135. cmd = "sort -g >&2"
  136. for( x in matches ) {
  137. if( matches[x] ) {
  138. printf "%-10s %s\n", matches[x], x | cmd
  139. }
  140. }
  141. if( common ) {
  142. printf "%-10s %s\n", "common:", common > "/dev/stderr"
  143. }
  144. } else {
  145. if( common ) best_match = common
  146. print best_match
  147. }
  148. }
  149. function common(matches) {
  150. # find the common root of a list of matches, if it exists
  151. for( x in matches ) {
  152. if( matches[x] && (!short || length(x) < length(short)) ) {
  153. short = x
  154. }
  155. }
  156. if( short == "/" ) return
  157. for( x in matches ) if( matches[x] && index(x, short) != 1 ) {
  158. return
  159. }
  160. return short
  161. }
  162. BEGIN {
  163. gsub(" ", ".*", q)
  164. hi_rank = ihi_rank = -9999999999
  165. }
  166. {
  167. if( typ == "rank" ) {
  168. rank = $2
  169. } else if( typ == "recent" ) {
  170. rank = $3 - t
  171. } else rank = frecent($2, $3)
  172. if( $1 ~ q ) {
  173. matches[$1] = rank
  174. } else if( tolower($1) ~ tolower(q) ) imatches[$1] = rank
  175. if( matches[$1] && matches[$1] > hi_rank ) {
  176. best_match = $1
  177. hi_rank = matches[$1]
  178. } else if( imatches[$1] && imatches[$1] > ihi_rank ) {
  179. ibest_match = $1
  180. ihi_rank = imatches[$1]
  181. }
  182. }
  183. END {
  184. # prefer case sensitive
  185. if( best_match ) {
  186. output(matches, best_match, common(matches))
  187. } else if( ibest_match ) {
  188. output(imatches, ibest_match, common(imatches))
  189. }
  190. }
  191. ')"
  192. [ $? -eq 0 ] && [ "$cd" ] && {
  193. if [ "$echo" ]; then echo "$cd"; else builtin cd "$cd"; fi
  194. }
  195. fi
  196. }
  197. alias ${_Z_CMD:-z}='_z 2>&1'
  198. [ "$_Z_NO_RESOLVE_SYMLINKS" ] || _Z_RESOLVE_SYMLINKS="-P"
  199. if type compctl >/dev/null 2>&1; then
  200. # zsh
  201. [ "$_Z_NO_PROMPT_COMMAND" ] || {
  202. # populate directory list, avoid clobbering any other precmds.
  203. if [ "$_Z_NO_RESOLVE_SYMLINKS" ]; then
  204. _z_precmd() {
  205. (_z --add "${PWD:a}" &)
  206. # Reference $RANDOM to refresh its value inside the subshell
  207. # Otherwise, multiple runs get the same value
  208. : $RANDOM
  209. }
  210. else
  211. _z_precmd() {
  212. (_z --add "${PWD:A}" &)
  213. # Reference $RANDOM to refresh its value inside the subshell
  214. # Otherwise, multiple runs get the same value
  215. : $RANDOM
  216. }
  217. fi
  218. [[ -n "${precmd_functions[(r)_z_precmd]}" ]] || {
  219. precmd_functions[$(($#precmd_functions+1))]=_z_precmd
  220. }
  221. }
  222. _z_zsh_tab_completion() {
  223. # tab completion
  224. local compl
  225. read -l compl
  226. reply=(${(f)"$(_z --complete "$compl")"})
  227. }
  228. compctl -U -K _z_zsh_tab_completion _z
  229. elif type complete >/dev/null 2>&1; then
  230. # bash
  231. # tab completion
  232. complete -o filenames -C '_z --complete "$COMP_LINE"' ${_Z_CMD:-z}
  233. [ "$_Z_NO_PROMPT_COMMAND" ] || {
  234. # populate directory list. avoid clobbering other PROMPT_COMMANDs.
  235. grep "_z --add" <<< "$PROMPT_COMMAND" >/dev/null || {
  236. PROMPT_COMMAND="$PROMPT_COMMAND"$'\n''(_z --add "$(command pwd '$_Z_RESOLVE_SYMLINKS' 2>/dev/null)" 2>/dev/null &);'
  237. }
  238. }
  239. fi