Search code examples
gogo-modulesgo-swagger

Is it possible to use "go mod tidy" to clear unused dependencies except indirect ones?


I understand that it is the expected behavior of go mod tidy to prune dependencies tree by removing the unnecessary ones, but part of my CI uses go-swagger to generate swagger JSON files. So, in the end. go mod tidy will remove the go-swagger packages from go.mod file because they're listed as //indirect (they're not used directly from the source code). Is there a workaround?

Here's my go.mod file:

...
require (
    github.com/go-openapi/errors v0.20.0 // indirect
    github.com/go-openapi/validate v0.20.2 // indirect
    github.com/go-swagger/go-swagger v0.26.1 // indirect
    github.com/gorilla/mux v1.8.0
    github.com/mailru/easyjson v0.7.7 // indirect
    github.com/spf13/afero v1.5.1 // indirect
    golang.org/x/mod v0.4.1 // indirect
    golang.org/x/net v0.0.0-20210220033124-5f55cee0dc0d // indirect
    golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43 // indirect
    golang.org/x/tools v0.1.0 // indirect
)

After I run go mod tidy, only this one remains:

    github.com/gorilla/mux v1.8.0

However, I have the following target on my Makefile that runs on production:

$ swagger generate spec -o ./internal/ui/swagger.json

I kind of wanted to avoid calling explictly go get on go-swagger globally after running go tidy. Do you guys have any suggestion on how to workaround this?


Solution

  • Use go install to install swagger without affecting go.mod.

    In your Makefile have a separate target that installs the swagger deps then runs it. Ours is arranged along these lines:

    ROOT := $(PWD)
    DIST := ${ROOT}/dist
    
    # Could be /go or ${HOME}/go depending on build environment
    export GOPATH := ${ROOT}/go
    
    .PHONY: swagger
    
    all: $(DIST)/app swagger
    
    swagger: $(GOPATH)
        go install -v github.com/go-swagger/go-swagger/cmd/swagger@latest
        $(GOPATH)/bin/swagger version
        $(GOPATH)/bin/swagger generate spec -o ./swagger-ui/swagger.json -m
    
    $(DIST)/app: $(DIST) $(GOPATH)
        go build -v -o $(DIST)/app ./cmd/...
    
    $(DIST):
        mkdir -p $(DIST)
    
    $(GOPATH):
        mkdir -p $(GOPATH)