Skip to content

Commit

Permalink
Add bash support
Browse files Browse the repository at this point in the history
  • Loading branch information
seanyeh committed Nov 5, 2014
1 parent db19a07 commit db7d6e3
Show file tree
Hide file tree
Showing 2 changed files with 111 additions and 2 deletions.
15 changes: 13 additions & 2 deletions README.md
@@ -1,14 +1,25 @@
# autosrc
Script for zsh to automatically run commands based on which directory you are in. An example of this being useful is managing multiple Python virtual environments.
Script for zsh/bash to automatically run commands based on which directory you are in. An example of this being useful is managing multiple Python virtual environments.


### Usage
### Installation

#### zsh
Add to your `~/.zshrc`:
```
source /path/to/autosrc.zsh
```

#### bash
Add to your `~/.bashrc`:
```
source /path/to/autosrc.bash
```
(This is not as well tested since I don't use bash often. Please let me know if
you find a bug.)

### Usage

Then, create a file called `.autosrc` in the directory/directories you want to use autosrc. Specify `autosrc_enter()` and `autosrc_exit()` functions to be called on enter and exit events.

Here is an example `.autosrc` file for Python venv:
Expand Down
98 changes: 98 additions & 0 deletions autosrc.bash
@@ -0,0 +1,98 @@
AUTOSRC=".autosrc"

AUTOSRC_IGNORE=0

autosrc_clear(){
unset -f "autosrc_enter" 2>/dev/null
unset -f "autosrc_exit" 2>/dev/null
}

autosrc_find(){
local curpath="$1"

while [ "$curpath" != "/" ]; do
local temp_file="$curpath/$AUTOSRC"
if [ -r "$temp_file" ]; then
autosrc_file="$temp_file"
return 0
fi

curpath=$(dirname "$curpath")
done

return 1
}

autosrc_is_func() {
declare -f "$1" > /dev/null; return $?
}

autosrc_call(){
local autosrc_file="$1"
local autosrc_func="autosrc_$2"

# Clear temp functions/variables
autosrc_clear

local cur_dir="$(pwd)"
source "$autosrc_file"


if autosrc_is_func "$autosrc_func"; then
AUTOSRC_IGNORE=1
cd $(dirname "$autosrc_file")

$autosrc_func

cd "$cur_dir"

AUTOSRC_IGNORE=0
fi
}

autosrc_run() {
if [ "$AUTOSRC_IGNORE" -eq 1 ]; then
return
fi

local cur_pwd="$(pwd)"

# If same dir, exit
if [ "$OLDPWD" = "$cur_pwd" ]; then
return
fi

autosrc_find "$OLDPWD" && local prev_autosrc="$autosrc_file"
autosrc_find "$cur_pwd" && local cur_autosrc="$autosrc_file"

# If same autosrc, return
if [ "$prev_autosrc" = "$cur_autosrc" ]; then
return
fi

# Call exit for previous .autosrc
if [ -n "$prev_autosrc" ]; then
autosrc_call "$prev_autosrc" "exit"
fi

# Call enter for current .autosrc
if [ -n "$cur_autosrc" ]; then
autosrc_call "$cur_autosrc" "enter"
fi
}

autosrc_bash_chpwd() {
# Check if working directory has changed
local cur_pwd="$(pwd)"
if [ "$OLDPWD" != "$cur_pwd" ]; then
autosrc_run
fi

OLDPWD="$cur_pwd"
}

OLDPWD="$(pwd)"
export PROMPT_COMMAND="autosrc_bash_chpwd"

# Call on startup as well
autosrc_find "$(pwd)" && autosrc_call "$autosrc_file" "enter"

0 comments on commit db7d6e3

Please sign in to comment.