How to override a dependency in go modules?
Asked Answered
L

1

6

In dep you have the option to override a dependency and have it point to a different repo for example in the following https://github.com/kubermatic/glog-logrus library one needs to add the following lines to the Gopkg.toml file:

[[override]]
  name = "github.com/golang/glog"
  source = "github.com/kubermatic/glog-logrus"

Then in the codebase you import "github.com/golang/glog. However, in go modules I don't see such an option? which leads me to think the only solution is to change the import to github.com/kubermatic/glog-logrus.

Thanks!

Lurlinelusa answered 30/7, 2019 at 7:1 Comment(1)
Use the "replace" directive.Presentational
S
18

This is what the replace directive is for.

Quoting from wiki Go 1.11 Modules: When should I use the replace directive?

The replace directive allows you to supply another import path that might be another module located in VCS (GitHub or elsewhere), or on your local filesystem with a relative or absolute file path. The new import path from the replace directive is used without needing to update the import paths in the actual source code.

So add this to the go.mod file of your main module:

replace (
    github.com/golang/glog => github.com/kubermatic/glog-logrus v0.0.0
)

You can also instruct the go tool to make this edit for you:

go mod edit -replace github.com/golang/glog=github.com/kubermatic/[email protected]

(Use the version you're interested in.)

After this when you import github.com/golang/glog, github.com/kubermatic/glog-logrus will be used (without having to change import statements).

Social answered 30/7, 2019 at 7:13 Comment(1)
I added replace directive for one of my local modules in my project, but when I make changes in that "replaced" module, those changes are not reflected during runtime of my project. Where does "replaced" directive look into? The actual source? Or the module's binary?Rabblement

© 2022 - 2024 — McMap. All rights reserved.