z.sh 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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. while [ "$1" ]; do case "$1" in
  101. --) while [ "$1" ]; do shift; local fnd="$fnd${fnd:+ }$1";done;;
  102. -*) local opt=${1:1}; while [ "$opt" ]; do case ${opt:0:1} in
  103. c) local fnd="^$PWD $fnd";;
  104. e) local echo=1;;
  105. h) echo "${_Z_CMD:-z} [-cehlrtx] args" >&2; return;;
  106. l) local list=1;;
  107. r) local typ="rank";;
  108. t) local typ="recent";;
  109. x) sed -i -e "\:^${PWD}|.*:d" "$datafile";;
  110. esac; opt=${opt:1}; done;;
  111. *) local fnd="$fnd${fnd:+ }$1";;
  112. esac; local last=$1; [ "$#" -gt 0 ] && shift; done
  113. [ "$fnd" -a "$fnd" != "^$PWD " ] || local list=1
  114. # if we hit enter on a completion just go there
  115. case "$last" in
  116. # completions will always start with /
  117. /*) [ -z "$list" -a -d "$last" ] && builtin cd "$last" && return;;
  118. esac
  119. # no file yet
  120. [ -f "$datafile" ] || return
  121. local cd
  122. cd="$( < <( _z_dirs ) awk -v t="$(date +%s)" -v list="$list" -v typ="$typ" -v q="$fnd" -F"|" '
  123. function frecent(rank, time) {
  124. # relate frequency and time
  125. dx = t - time
  126. if( dx < 3600 ) return rank * 4
  127. if( dx < 86400 ) return rank * 2
  128. if( dx < 604800 ) return rank / 2
  129. return rank / 4
  130. }
  131. function output(matches, best_match, common) {
  132. # list or return the desired directory
  133. if( list ) {
  134. cmd = "sort -n >&2"
  135. for( x in matches ) {
  136. if( matches[x] ) {
  137. printf "%-10s %s\n", matches[x], x | cmd
  138. }
  139. }
  140. if( common ) {
  141. printf "%-10s %s\n", "common:", common > "/dev/stderr"
  142. }
  143. } else {
  144. if( common ) best_match = common
  145. print best_match
  146. }
  147. }
  148. function common(matches) {
  149. # find the common root of a list of matches, if it exists
  150. for( x in matches ) {
  151. if( matches[x] && (!short || length(x) < length(short)) ) {
  152. short = x
  153. }
  154. }
  155. if( short == "/" ) return
  156. for( x in matches ) if( matches[x] && index(x, short) != 1 ) {
  157. return
  158. }
  159. return short
  160. }
  161. BEGIN {
  162. gsub(" ", ".*", q)
  163. hi_rank = ihi_rank = -9999999999
  164. }
  165. {
  166. if( typ == "rank" ) {
  167. rank = $2
  168. } else if( typ == "recent" ) {
  169. rank = $3 - t
  170. } else rank = frecent($2, $3)
  171. if( $1 ~ q ) {
  172. matches[$1] = rank
  173. } else if( tolower($1) ~ tolower(q) ) imatches[$1] = rank
  174. if( matches[$1] && matches[$1] > hi_rank ) {
  175. best_match = $1
  176. hi_rank = matches[$1]
  177. } else if( imatches[$1] && imatches[$1] > ihi_rank ) {
  178. ibest_match = $1
  179. ihi_rank = imatches[$1]
  180. }
  181. }
  182. END {
  183. # prefer case sensitive
  184. if( best_match ) {
  185. output(matches, best_match, common(matches))
  186. } else if( ibest_match ) {
  187. output(imatches, ibest_match, common(imatches))
  188. }
  189. }
  190. ')"
  191. [ $? -eq 0 ] && [ "$cd" ] && {
  192. if [ "$echo" ]; then echo "$cd"; else builtin cd "$cd"; fi
  193. }
  194. fi
  195. }
  196. alias ${_Z_CMD:-z}='_z 2>&1'
  197. [ "$_Z_NO_RESOLVE_SYMLINKS" ] || _Z_RESOLVE_SYMLINKS="-P"
  198. if type compctl >/dev/null 2>&1; then
  199. # zsh
  200. [ "$_Z_NO_PROMPT_COMMAND" ] || {
  201. # populate directory list, avoid clobbering any other precmds.
  202. if [ "$_Z_NO_RESOLVE_SYMLINKS" ]; then
  203. _z_precmd() {
  204. (_z --add "${PWD:a}" &)
  205. }
  206. else
  207. _z_precmd() {
  208. (_z --add "${PWD:A}" &)
  209. }
  210. fi
  211. [[ -n "${precmd_functions[(r)_z_precmd]}" ]] || {
  212. precmd_functions[$(($#precmd_functions+1))]=_z_precmd
  213. }
  214. }
  215. _z_zsh_tab_completion() {
  216. # tab completion
  217. local compl
  218. read -l compl
  219. reply=(${(f)"$(_z --complete "$compl")"})
  220. }
  221. compctl -U -K _z_zsh_tab_completion _z
  222. elif type complete >/dev/null 2>&1; then
  223. # bash
  224. # tab completion
  225. complete -o filenames -C '_z --complete "$COMP_LINE"' ${_Z_CMD:-z}
  226. [ "$_Z_NO_PROMPT_COMMAND" ] || {
  227. # populate directory list. avoid clobbering other PROMPT_COMMANDs.
  228. grep "_z --add" <<< "$PROMPT_COMMAND" >/dev/null || {
  229. PROMPT_COMMAND="$PROMPT_COMMAND"$'\n''(_z --add "$(command pwd '$_Z_RESOLVE_SYMLINKS' 2>/dev/null)" 2>/dev/null &);'
  230. }
  231. }
  232. fi