Skip to content

Instantly share code, notes, and snippets.

@keithshep
Created November 5, 2016 04:58
Show Gist options
  • Save keithshep/2f7bb9b913e8ff6783dd7db97491d22a to your computer and use it in GitHub Desktop.
Save keithshep/2f7bb9b913e8ff6783dd7db97491d22a to your computer and use it in GitHub Desktop.
stuff I've appended to the end of my .zshrc file
# this function echos "true" when the first argument string starts
# with the second
function startswith() {
if [[ "${1[1, ${#2}]}" == "$2" ]]
then
echo 'true'
fi
}
# scan for and process .dirconf properties files where each lines is a
# key/value pair formatted like "key=value". Currently the only key
# allowed is:
# * venv: the value of this key should be the path to the python
# virtualenv that should be activated when you cd to the relevant
# dir or one of its subdirs
function dirconf() {
emulate -L zsh
# if we've cd'd out of a venv dir then we should deactivate
if [[ -n "$VENV_CONF_DIR" && "`startswith "$PWD" "$VENV_CONF_DIR"`" == '' ]]
then
deactivate
unset VENV_CONF_DIR
fi
# start with the current working dir and back our way down to '/' looking
# for .dirconf files to parse
curr_dir="$PWD"
prev_dir=""
while [[ -n "$curr_dir" && -x "$curr_dir" && "$curr_dir" != "$prev_dir" ]]
do
# if .dirconf is a normal readable file
if [[ -f "$curr_dir/.dirconf" && -r "$curr_dir/.dirconf" ]]
then
# iterate over lines in "$curr_dir/.dirconf"
while read line
do
# split the line formatted like: key=value
key="${line[(ws:=:)1]}"
value="${line[${#key} + 2, -1]}"
# the "venv" $key indicates that we should activate a
# python virtualenv corresponding to the path in $value
if [[ "$key" == 'venv' ]]
then
# don't proceed with virtualenv if we already processed
# a more (or equally) deeply nested venv setting
if [[ ${#curr_dir} -gt ${#VENV_CONF_DIR} ]]
then
# I don't want to do a full glob here but for
# convenience I replace '~' with "$HOME" at
# the start of a path
venvpath="$value"
if [[ "$venvpath" == '~' || "${venvpath[1, 2]}" == '~/' ]]
then
venvpath="${HOME}${venvpath[2, -1]}"
fi
# activate the virtualenv and remember which
# directory the venv key was processed from
source "$venvpath/bin/activate"
export VENV_CONF_DIR="${curr_dir}"
fi
fi
done <"$curr_dir/.dirconf"
fi
prev_dir=$curr_dir
curr_dir=`dirname "$curr_dir"`
done
}
chpwd_functions=(${chpwd_functions[@]} "dirconf")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment