Check actuality of go.mod and go.sum


It happens in practice that you have to revise a merge request and see suspicious changes in go.mod and go.sum, maybe only one file is changed, and a legitimate question arises, whether these changes are necessary, or whether it was accidentally added to a commit, maybe a colleague forgot to add another file to the commit or to run go mod tidy after removing a dependency? Or maybe it was you yourself who added extra changes in previous commits?

In general, questions arise, and to make them fewer, you can automate the check if the go.mod and go.sum files are actually up-to-date.

Using Gitlab CI as an example, such a job could look like this:

image: golang:1.21.5

stages:
  - check

check-go-dependencies:
  stage: check
  script:
    - go mod tidy
    - git diff --exit-code
  • go mod tidy - this command will check if the module source code matches the go.mod and go.sum files.
  • git diff --exit-code - this command will show the differences in the files that have been committed and those that will be obtained after the the previous command, outputting a non-zero exit code if there are any differences.

This job is simple to implement, but if it crashes with an error, it is not clear what to do about it, and it would be good to add useful information for colleagues or yourself from the future on how this problem can be solved. So let’s make some refinements to the test:

image: golang:1.21.5

stages:
  - check

check-go-dependencies:
  stage: check
  script:
    - go mod tidy
    - |
      git diff --exit-code && exit 0 || true
      echo -e "\033[0;31m"
      echo '######################################################################'
      echo
      echo "ERROR: go.mod or go.sum is different from the committed version"
      echo "Try using 'go mod tidy' to fix the go.mod and go.sum files"
      echo "Also, don't forget to commit and push changes"
      echo
      echo '######################################################################'
      exit 1

At the beginning it’s the same go mod tidy, and then it’s more interesting, since the pipline terminates at the first error it’s hard to break the check into separate command calls, that’s why we describe a multiline script using the syntax - |. Further, if git diff finds nothing, we exit with zero code, but if the exit code is not zero, we intercept it and skip it due to the true command. Then we set the red color for the message, generate the necessary message and exit with a non-zero code so that the job ends with an error.

In principle, this covers the basic needs of checking the relevance of go.mod and go.sum, and the output of a detailed error message will help us and our colleagues to learn about the option to fix the problem with the go mod tidy command. This in turn should improve the user experience and reduce the number of questions arising when such a job crashes.

golang  go  gitlab  ci