Skip to content

Instantly share code, notes, and snippets.

@nlf
Last active August 29, 2015 14:07
Show Gist options
  • Save nlf/d54dd2a5aae15e95b4b6 to your computer and use it in GitHub Desktop.
Save nlf/d54dd2a5aae15e95b4b6 to your computer and use it in GitHub Desktop.
function go() {
CMD=$1
GOBIN=`/usr/bin/which go`
OLDPATH="$GOPATH"
GOMODS=`pwd`/go_modules
if [ $CMD == "init" ]; then
echo "Initializing project $(basename `pwd`)..."
# Get a list of all (recursive) packages we depend on
DEPS=`go list -f '{{ join .Deps "\n" }}' 2>&1`
# If we failed to get a list, it's because there's no go source so just create the dir and stop here
if [ $? != 0 ]; then
mkdir -p $GOMODS/src
return 0
fi
MISSING_DEPS=()
COPY_DEPS=()
# Loop over our dependencies
for DEP in $DEPS; do
# Check to see if they're part of the standard lib
STANDARD=`go list -f '{{.Standard}}' "$DEP" 2>&1`
# If we get a non-zero exit code, the package isn't installed copy it to MISSING_DEPS
# Otherwise, check the value returned. If it's "false" copy it to COPY_DEPS
if [ $? != 0 ]; then
MISSING_DEPS+=("$DEP")
else
if [ "$STANDARD" == "false" ]; then
COPY_DEPS+=("$DEP")
fi
fi
done
# Make the go_modules directory if it doesn't exist
mkdir -p "$GOMODS/src"
# Hijack the GOPATH
export GOPATH="$GOMODS"
# Copy dependencies we already had
for DEP in "${COPY_DEPS[@]}"; do
echo "Copying dependency $DEP..."
DEP_ROOT=${DEP%/*}
mkdir -p "$GOMODS/src/$DEP_ROOT"
cp -r "$OLDPATH/src/$DEP" "$GOMODS/src/$DEP_ROOT/"
done
# Install dependencies that we're missing
for DEP in "${MISSING_DEPS[@]}"; do
echo "Installing dependency $DEP..."
$GOBIN get -d "$DEP"
done
# Restore the GOPATH and exit
export GOPATH="$OLDPATH"
echo "Done!"
return 0
fi
if [ -d "$GOMODS" ]; then
export GOPATH="$GOMODS"
$GOBIN "$@"
EXITCODE=$?
export GOPATH="$OLDPATH"
return $EXITCODE
fi
$GOBIN "$@"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment