How to fork Go packages

Sašo Matejina
3 min readMay 27, 2017

--

Go makes it really easy to use packages and all you need to do is…

$ go get github.com/org/magic

but what do you do when you find a bug or want to extend the package? Usually on Github you fork, do some changes, submit a PR to upstream and then use your forked project until your code gets merged to upstream/master. With Go packages that is a bit harder because you can’t just do this

$ go get github.com/fork/magic

It is incorrect, because if you fork a repository that has import statements referring to itself, they will be broken in the fork.

One of the solutions you can use is setting a different remote and pulling the code

$ go get github.com/org/magic
$ cd $GOPATH/src/github.com/org/magic
$ git remote -v
origin https://github.com/org/magic.git (fetch)
origin https://github.com/org/magic (push)

you can then set your remote fork and pull your code…

$ git remote add fork https://github.com/fork/magic.git
$ git pull fork master

This will allow you to test and run your code with your app. This is fairly easy, but it comes with some maintenance problems that can easily break your app in the future. For example if you run

$ go get -u github.com/org/magic

it will update your package back to master branch and your changes will be gone, also if you don’t vendor packages and want to use your package in Dockerfile for example, you will need to write some magic there to use your forked package.

Best solution that I found so far is using Glide: Vendor Package Management for Golang.

First you need to install glide and then glide init command can be use to setup a new project, glide update regenerates the dependency versions using scanning and rules, and glide install will install the versions listed in the glide.lock file, skipping scanning, unless the glide.lock file is not found in which case it will perform an update.

But how can glide help me with my fork problem? The magic is in the glide.yaml config.

package: github.com/sasso/my-project
import:
- package: github.com/org/magic
repo: https://github.com/fork/magic.git

by adding the repo glide will always pull the code from your fork and allow any build system to always use forked package. When your code change is accepted to upstream/master the only thing you need to do now is remove the repo and run glide update again.

This is just one of the features glide has to offer and I encourage you to check glide docs and try it out.

Also remember to always submit a PR to upstream/master with your code changes. It will benefit the community in same way you benefited when using the package!

…and now back to go-ding

--

--