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 ( v0.20.0 // indirect v0.20.2 // indirect v0.26.1 // indirect v1.8.0 v0.7.7 // indirect v1.5.1 // indirect v0.4.1 // indirect v0.0.0-20210220033124-5f55cee0dc0d // indirect v0.0.0-20210220050731-9a76102bfb43 // indirect v0.1.0 // indirect

After I run go mod tidy, only this one remains: 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?


I suspect one workaround would be to:

  • import explicitly in one of your project source .go file the package
  • define a dummy variable
    var _ = scan.Parse

That way, your sources would directly "use", which would no longer pruned by go mod tidy.

I would do that in a go file named externalTools.go, just to remember why this fake import is needed.

Answered By – VonC

Answer Checked By – Mildred Charles (GoLangFix Admin)

Leave a Reply

Your email address will not be published.