I got a github repo github.com/user/somerepo.
I init it by doing go mod init **github.com/user/somerepo**
I need to change this dependecy and make it point to another github repository. Let say : github.com/user/a-different-repo.
Is there any go command that can update all the import statements in all the files?
The go mod edit -replace
is your friend for that.
From the doc (Source) :
The -replace=old[@v]=new[@v] flag adds a replacement of the given module path and version pair. If the @v in old@v is omitted, a replacement without a version on the left side is added,
Here is the important part :
which applies to all versions of the old module path. If the @v in new@v is omitted, the new path should be a local module root directory, not a module path. Note that -replace overrides any redundant replacements for old[@v], so omitting @v will drop existing replacements for specific versions.
Here is the AddReplace func which is responsible for the replacement.
Now to achieve it, each of your repository must be mapped to your GOPATH. A little recall on GOPATH :
When you want a repository to become a "go gettable" package you should map this repository to your GOPATH.
As explained here when you do go get
, it will first looks up in your $GOPATH
an take the latest version of the package (or the specific version if you specified it in your go.mod file)
Then you can achieve your edit by doing this command :
go mod edit -replace github.com/UserA/[email protected]=github.com/UserA/[email protected]
Another way (and maybe a better one) is to do this inside the go.mod file, like so :
module foo.bar
replace github.com/UserA/foo => github.com/UserA/bar
require (
github.com/UserA/foo v0.0.1
)
Of course, this will work only if each repository is mapped into your GOPATH.
See also here for further explanation: when-should-i-use-the-replace-directive