z.sh 8.6 KB

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