toptal / gitignore.io

Create useful .gitignore files for your project
https://www.toptal.com/developers/gitignore
MIT License
8.21k stars 623 forks source link

Cache the api response into a file, to accelerate the completion. #586

Open fakeyanss opened 2 years ago

fakeyanss commented 2 years ago

Sorry I have not found the doc | Advanced Command Line source. So I can not submit a PR of it.

If we send a request to the server https://www.toptal.com/developers/gitignore/api/$argv each time, the network latency of command completion will be obvious.

We can save the api response into a file to cache it.

# generate .gitignore template
function gi() {
    curl -sL https://www.toptal.com/developers/gitignore/api/$@ ;
}

# Provides gi completion for zsh
_gitignoreio_get_command_list() {
    # gi cmd cache file
    cache=~/.config/.gi_cmd_list
    ls cache >/dev/null 2>&1
    if [[ $? == 0 ]]; then
        modify=$(date -j -f %c $(stat -x $cache|grep 'Modify: '|awk -F 'Modify: ' '{print $2}') +%s)
        expire=$(($(date +%s)-$modify))
        # check update once half a month
        if [[ expire > 1296000 ]]; then
            cat $cache
            exit 0
        fi
    fi
    curl -sL https://www.toptal.com/developers/gitignore/api/list | tr "," "\n" > $cache
    cat $cache
}

_gitignoreio () {
    compset -P '*,'
    compadd -S '' $(_gitignoreio_get_command_list)
}

compdef _gitignoreio gi