Go and Github

Francesc Campoy recently posted about how to work on someone else’s Go repo from github.  His description was correct, but I think there’s an easier way, and also one that might be slightly less confusing.

Let’s say you want to work on your own branch of github.com/natefinch/gocog - here’s the easiest way to do it:

  1. Fork github.com/natefinch/gocog on github
  2. mkdir -p $GOPATH/src/github.com/natefinch/gocog
  3. cd $GOPATH/src/github.com/natefinch/gocog
  4. git clone https://github.com/YOURNAME/gocog .
  5. (optional) go get github.com/natefinch/gocog

That’s it.  Now you can work on the code, push/pull etc from your github repo as normal, and submit a pull request when you’re done.

go get is useful for getting code that you want to use, but it’s not very useful for getting code that you want to work on.  It doesn’t set up source control.  git clone does.  What go get is handy for is getting the dependencies of a project, which is what step 5 does (only needed if the project relies on outside repos you don’t already have).  (thanks to a post on G+ for reminding me that git clone won’t get the dependencies)

Also note, the path on disk is the same as the original repo’s URL, not your branch’s URL.  That’s intentional, and it’s the key to making this work.  go get is the only thing that actually cares if the repo URL is the same as the path on disk.  Once the code is on disk, go build etc just expects import paths to be directories under $GOPATH.  The code expects to be under $GOPATH/src/github.com/natefinch/gocog because that’s what the import statements say it should be.  There’s no need to change import paths or anything wacky like that (though it does mean that you can’t have both the original version of the code and your branch coexisting in the same $GOPATH).

Note that this is actually the same procedure that you’d use to work on your own code from github, you just change step 1 to “create the repo in github”.  I prefer making the repo in github first because it lets me set up the license, the readme, and the .gitignore with just a few checkboxes, though obviously that’s optional if you want to hack locally first.  In that case, just make sure to set up the path under gopath where it would go if you used go get, so that go get will work correctly when you decide to push up to github.

(updated to mention using go get after git clone)