Search code examples
gitgogo-buildgo-toolchain

Checking to make sure project compiles before pushing to version control remote


I have a script for TypeScript projects that makes sure my code compiles before I push it to the remote:

simple_git_push_typescript(){
 (
    set -e

    top_level="$(git rev-parse --show-toplevel)"

    if [[ "$cm_ignore_tsc" != 'yes' ]]; then

        if [[ -f "$top_level/tsconfig.json" ]]; then
          (cd "$top_level" && tsc)  || { echo 'Could not compile with tsc. Did not push. Use "cm_ignore_tsc=yes" to override.'; exit 1; }
        fi
    fi

    git add -A

    if [[ "$cm_force_commit" == 'yes' ]]; then
       git commit --allow-empty -am "${1-tmp}"
    else
       git commit -am "${1-tmp}"  || echo 'Could not create new commit.';
    fi

    git push
 )
}

The script works really well when I went to push code to my feature branch at the end of the day, or right before a pull request - it helps prevent unnecessary commits, but also makes it easy.

With Go, I just want to check that everything compiles before I push a go project to the remote.

simple_git_push_go(){
  (
    set -e

    top_level="$(git rev-parse --show-toplevel)"

    (cd "$top_level" && go build -o '/dev/null' .)  # ?

     # ...
   )
}

is Go build the best choice to check for compilation of my whole project, or is the more generic way to find all the go packages and compile each package? I suppose for projects where there are multiple packages that are not linked together, then you would have to traverse each package and compile them separately?


Solution

  • Use go build ./... in the project root. This will recurse down into subfolders at any depth.

    If you also want to ensure test files compile as well (and tests pass), then run: go test ./...

    Note that folders starting with underscore _ or dot . are ignored.