Skip to content

Instantly share code, notes, and snippets.

@wbailey
Last active May 26, 2022 03:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wbailey/88983f497089de5f09b8 to your computer and use it in GitHub Desktop.
Save wbailey/88983f497089de5f09b8 to your computer and use it in GitHub Desktop.
Automatically add the current directory to the GOPATH when changing into it
# GOPATH helper
goPathFile="$HOME/.gopathsrc"
if [ -f "$goPathFile" ]; then
source "$goPathFile"
fi
CHECK_FILENAME=.gopath
setGoPath() {
if [ -f "$PWD/$CHECK_FILENAME" ]; then
if ! [[ "$GOPATH" =~ (^|:)"$PWD"(:|$) ]]; then
echo "Adding $PWD to GOPATH"
export GOPATH=$GOPATH:$PWD
echo $GOPATH
fi
fi
}
if [ "$PROMPT_COMMAND" != "*setGoPath*" ]; then
export PREV_PROMPT_COMMAND=$PROMPT_COMMAND
export PROMPT_COMMAND="$PROMPT_COMMAND; setGoPath"
fi
@wbailey
Copy link
Author

wbailey commented Jun 9, 2015

GOPATH Helper

Setup your shell to automatically add a directory to the GOPATH environment variable when you change directories

I got tired of setting the GOPATH in an unintelligent way for my projects so I created these helpers.

  • Add the contents of the first file to your .bash_profile
12:22 $ cat .bash_profile
...
fi

# GOPATH helper

goPathFile="$HOME/.gopath"

if [ -f "$goPathFile" ]; then
    source "$goPathFile"
fi
...
  • Install the .gopathsrc file into your $HOME directory
12:24 $ cat .gopathsrc 
CHECK_FILENAME=.gopath

setGoPath() {
...
  • source your profile
12:24 $ source ~/.bash_profile
✔ ~ 
  • Add your .gopath file to your project directory:
13:30 $ echo $GOPATH

✔ ~ 
13:31 $ touch work/gotut/.gopath
✔ ~ 
13:31 $ cd work/gotut/
Adding /Users/wes/work/gotut to GOPATH
:/Users/wes/work/gotut
✔ ~/work/gotut [master|✚ 2…14] 
13:31 $ cd ../bashy/
✔ ~/work/bashy [master|✔] 
13:31 $ cd -
/Users/wes/work/gotut
✔ ~/work/gotut [master|✚ 2…14] 

@minherz
Copy link

minherz commented Dec 19, 2020

This solution will constantly increase the number of paths within GOPATH. You need to modify it by keeping a "constant" part of the GOPATH in a separate environment and exporting GOPATH in setGoPath() by concatenating the "constant" path with $PWD.

@wbailey
Copy link
Author

wbailey commented Dec 20, 2020

@minherz There is no downside to having repeated elements in the path while foregoing the complexity of maintaining the unique elements you are suggesting.

@minherz
Copy link

minherz commented Dec 20, 2020

As you wish. I would not dispute about the "foregoing maintenance complexity" because it depends on the observer. Mind though that the longer the path the more time is required to process things and more chances for ambiguity.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment