grep.zsh 1.43 KB
Newer Older
Marc Cornellà's avatar
Marc Cornellà committed
1
2
3
4
__GREP_CACHE_FILE="$ZSH_CACHE_DIR"/grep-alias

# See if there's a cache file modified in the last day
__GREP_ALIAS_CACHES=("$__GREP_CACHE_FILE"(Nm-1))
5
6
7
if [[ -n "$__GREP_ALIAS_CACHES" ]]; then
    source "$__GREP_CACHE_FILE"
else
8
    grep-flags-available() {
Marc Cornellà's avatar
Marc Cornellà committed
9
        command grep "$@" "" &>/dev/null <<< ""
mattmc3's avatar
mattmc3 committed
10
    }
nXqd's avatar
nXqd committed
11

Marc Cornellà's avatar
Marc Cornellà committed
12
    # Ignore these folders (if the necessary grep flags are available)
mattmc3's avatar
mattmc3 committed
13
    EXC_FOLDERS="{.bzr,CVS,.git,.hg,.svn,.idea,.tox}"
14

Marc Cornellà's avatar
Marc Cornellà committed
15
16
    # Check for --exclude-dir, otherwise check for --exclude. If --exclude
    # isn't available, --color won't be either (they were released at the same
17
    # time (v2.5): https://git.savannah.gnu.org/cgit/grep.git/tree/NEWS?id=1236f007
18
    if grep-flags-available --color=auto --exclude-dir=.cvs; then
Marc Cornellà's avatar
Marc Cornellà committed
19
        GREP_OPTIONS="--color=auto --exclude-dir=$EXC_FOLDERS"
20
    elif grep-flags-available --color=auto --exclude=.cvs; then
Marc Cornellà's avatar
Marc Cornellà committed
21
        GREP_OPTIONS="--color=auto --exclude=$EXC_FOLDERS"
mattmc3's avatar
mattmc3 committed
22
    fi
23

24
25
26
27
28
29
30
31
32
    if [[ -n "$GREP_OPTIONS" ]]; then
        # export grep, egrep and fgrep settings
        alias grep="grep $GREP_OPTIONS"
        alias egrep="egrep $GREP_OPTIONS"
        alias fgrep="fgrep $GREP_OPTIONS"

        # write to cache file if cache directory is writable
        if [[ -w "$ZSH_CACHE_DIR" ]]; then
            alias -L grep egrep fgrep >| "$__GREP_CACHE_FILE"
33
        fi
34
    fi
Marc Cornellà's avatar
Marc Cornellà committed
35

Marc Cornellà's avatar
Marc Cornellà committed
36
    # Clean up
mattmc3's avatar
mattmc3 committed
37
    unset GREP_OPTIONS EXC_FOLDERS
38
    unfunction grep-flags-available
mattmc3's avatar
mattmc3 committed
39
fi
Marc Cornellà's avatar
Marc Cornellà committed
40
41

unset __GREP_CACHE_FILE __GREP_ALIAS_CACHES