From 6dacfeb512c770f4d19c55827a17515919c8d4ce Mon Sep 17 00:00:00 2001 From: Adam Veldhousen Date: Fri, 20 Mar 2020 16:05:09 -0500 Subject: [PATCH] added draft of go mod edit replace how-to --- content/posts/go-mod-edit-replace.md | 57 ++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100755 content/posts/go-mod-edit-replace.md diff --git a/content/posts/go-mod-edit-replace.md b/content/posts/go-mod-edit-replace.md new file mode 100755 index 0000000..fd84df7 --- /dev/null +++ b/content/posts/go-mod-edit-replace.md @@ -0,0 +1,57 @@ +--- +title: "Go Modules: How to replace a dependency with a local copy" +date: 2020-03-20T20:35:25Z +draft: false +tags: [golang, modules] +--- + +Lets say you're working on a go package and you need to replace a dependency with a specific version for testing. You can use the awesome `go mod edit -replace old=new[@version]` command to do this. + +This command adds a `replace` directive to your `go.mod` that overrides any require statement versions for the matching module: + +```bash {hl_lines=[13]} +$ go mod edit -replace github.com/gobuffalo/packr=github.com/gobuffalo/packr@v2.8.0 +$ cat go.mod +module github.com/adamveld12/riffraff + +go 1.14 + +require ( + github.com/gobuffalo/packr v1.30.1 + github.com/golangci/golangci-lint v1.21.0 // indirect + github.com/satori/go.uuid v1.2.0 +) + +replace github.com/gobuffalo/packr => github.com/gobuffalo/packr v2.8.0 # now points at a different version +``` + +Now when you build your go app, it will use `v2.8.0` of packr in place of the version specified in the `require` block. + +But what if you want to use it similarly to `npm link`, where you want to replace a module with a local working copy? + +Run the same command but omit the `@version` on the new package like so: + +```bash {hl_lines=[16]} +# clone your own copy and make some edits at ~/projects/packr +$ cd ~/projects && git clone https://github.com/gobuffalo/packr +$ cd ~/projects/riffraff && go mod edit -replace github.com/gobuffalo/packr=../packr +$ cat go.mod +module github.com/adamveld12/riffraff + +go 1.14 + +require ( + github.com/gobuffalo/packr v1.30.1 + github.com/golangci/golangci-lint v1.21.0 // indirect + github.com/satori/go.uuid v1.2.0 +) + +replace github.com/gobuffalo/packr => ../packr #now points at your local copy +``` + + +When you're all finished up you can remove the `replace` directive with the following command: + +```bash +$ go mod edit -dropreplace github.com/gobuffalo/packr +```