citadel

My dotfiles, scripts and nix configs
git clone git://jb55.com/citadel
Log | Files | Refs | README | LICENSE

z.sh (8891B)


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