Merge remote-tracking branch 'upstream/master' into v22
diff --git a/README.md b/README.md
index 386ff83..a5e6100 100644
--- a/README.md
+++ b/README.md
@@ -8,13 +8,13 @@
 Installing
 ----------
 
-This project wraps the functionality provided by libgit2. If you're using a stable version, install it to your system via your system's package manger and then install git2go as usual.
+This project wraps the functionality provided by libgit2. If you're using a stable version, install it to your system via your system's package manaager and then install git2go as usual.
 
 Otherwise (`next` which tracks an unstable version), we need to build libgit2 as well. In order to build it, you need `cmake`, `pkg-config` and a C compiler. You will also need the development packages for OpenSSL and LibSSH2 installed if you want libgit2 to support HTTPS and SSH respectively.
 
 ### Stable version
 
-git2go has `master` which tracks the latest release of libgit2, and versioned branches which indicate which version of libgit2 they work against. Install the development package it on your system via your favourite package manager or from source and you can use a service like gopkg.in to use the appropriate version. For the libgit2 v0.22 case, you can use
+git2go has `master` which tracks the latest release of libgit2, and versioned branches which indicate which version of libgit2 they work against. Install the development package on your system via your favourite package manager or from source and you can use a service like gopkg.in to use the appropriate version. For the libgit2 v0.22 case, you can use
 
     import "gopkg.in/libgit2/git2go.v22"
 
@@ -28,15 +28,15 @@
 
 The `next` branch follows libgit2's master branch, which means there is no stable API or ABI to link against. git2go can statically link against a vendored version of libgit2.
 
-Run `go get -d github.com/libgit2/git2go` to download the code and go to your `$GOPATH/src/github.com/libgit2/git2go` dir. From there, we need to build the C code and put it into the resulting go binary.
+Run `go get -d github.com/libgit2/git2go` to download the code and go to your `$GOPATH/src/github.com/libgit2/git2go` directory. From there, we need to build the C code and put it into the resulting go binary.
 
     git checkout next
     git submodule update --init # get libgit2
     make install
 
-will compile libgit2 and run `go install` such that it's statically linked to the git2go package.
+will compile libgit2. Run `go install` so that it's statically linked to the git2go package.
 
-Paralellism and network operations
+Parallelism and network operations
 ----------------------------------
 
 libgit2 uses OpenSSL and LibSSH2 for performing encrypted network connections. For now, git2go asks libgit2 to set locking for OpenSSL. This makes HTTPS connections thread-safe, but it is fragile and will likely stop doing it soon. This may also make SSH connections thread-safe if your copy of libssh2 is linked against OpenSSL. Check libgit2's `THREADSAFE.md` for more information.
@@ -48,7 +48,7 @@
 
     make test
 
-alternatively, if you want to pass arguments to `go test`, you can use the script that sets it all up
+Alternatively, if you want to pass arguments to `go test`, you can use the script that sets it all up
 
     ./script/with-static.sh go test -v
 
diff --git a/branch.go b/branch.go
index 42e1216..8cf73b6 100644
--- a/branch.go
+++ b/branch.go
@@ -94,6 +94,7 @@
 
 	var ptr *C.git_reference
 	cBranchName := C.CString(branchName)
+	defer C.free(unsafe.Pointer(cBranchName))
 	cForce := cbool(force)
 
 	cSignature, err := signature.toC()
@@ -134,6 +135,7 @@
 func (b *Branch) Move(newBranchName string, force bool, signature *Signature, msg string) (*Branch, error) {
 	var ptr *C.git_reference
 	cNewBranchName := C.CString(newBranchName)
+	defer C.free(unsafe.Pointer(cNewBranchName))
 	cForce := cbool(force)
 
 	cSignature, err := signature.toC()
@@ -180,6 +182,7 @@
 	var ptr *C.git_reference
 
 	cName := C.CString(branchName)
+	defer C.free(unsafe.Pointer(cName))
 
 	runtime.LockOSThread()
 	defer runtime.UnlockOSThread()
@@ -208,6 +211,7 @@
 
 func (repo *Repository) RemoteName(canonicalBranchName string) (string, error) {
 	cName := C.CString(canonicalBranchName)
+	defer C.free(unsafe.Pointer(cName))
 
 	nameBuf := C.git_buf{}
 
@@ -225,6 +229,7 @@
 
 func (b *Branch) SetUpstream(upstreamName string) error {
 	cName := C.CString(upstreamName)
+	defer C.free(unsafe.Pointer(cName))
 
 	runtime.LockOSThread()
 	defer runtime.UnlockOSThread()
@@ -251,6 +256,7 @@
 
 func (repo *Repository) UpstreamName(canonicalBranchName string) (string, error) {
 	cName := C.CString(canonicalBranchName)
+	defer C.free(unsafe.Pointer(cName))
 
 	nameBuf := C.git_buf{}
 
diff --git a/clone.go b/clone.go
index 4de4aea..1265d7f 100644
--- a/clone.go
+++ b/clone.go
@@ -3,6 +3,7 @@
 /*
 #include <git2.h>
 
+extern void _go_git_populate_remote_cb(git_clone_options *opts);
 */
 import "C"
 import (
@@ -10,13 +11,14 @@
 	"unsafe"
 )
 
+type RemoteCreateCallback func(repo Repository, name, url string) (*Remote, ErrorCode)
+
 type CloneOptions struct {
 	*CheckoutOpts
 	*RemoteCallbacks
 	Bare                 bool
 	CheckoutBranch       string
-	RemoteCreateCallback C.git_remote_create_cb
-	RemoteCreatePayload  unsafe.Pointer
+	RemoteCreateCallback RemoteCreateCallback
 }
 
 func Clone(url string, path string, options *CloneOptions) (*Repository, error) {
@@ -30,6 +32,7 @@
 
 	copts := (*C.git_clone_options)(C.calloc(1, C.size_t(unsafe.Sizeof(C.git_clone_options{}))))
 	populateCloneOptions(copts, options)
+	defer freeCloneOptions(copts)
 
 	if len(options.CheckoutBranch) != 0 {
 		copts.checkout_branch = C.CString(options.CheckoutBranch)
@@ -38,9 +41,6 @@
 	runtime.LockOSThread()
 	defer runtime.UnlockOSThread()
 	ret := C.git_clone(&repo.ptr, curl, cpath, copts)
-	freeCheckoutOpts(&copts.checkout_opts)
-	C.free(unsafe.Pointer(copts.checkout_branch))
-	C.free(unsafe.Pointer(copts))
 
 	if ret < 0 {
 		return nil, MakeGitError(ret)
@@ -50,6 +50,32 @@
 	return repo, nil
 }
 
+//export remoteCreateCallback
+func remoteCreateCallback(cremote unsafe.Pointer, crepo unsafe.Pointer, cname, curl *C.char, payload unsafe.Pointer) C.int {
+	name := C.GoString(cname)
+	url := C.GoString(curl)
+	repo := Repository{(*C.git_repository)(crepo)}
+
+	if opts, ok := pointerHandles.Get(payload).(CloneOptions); ok {
+		remote, err := opts.RemoteCreateCallback(repo, name, url)
+
+		if err == ErrOk && remote != nil {
+			// clear finalizer as the calling C function will
+			// free the remote itself
+			runtime.SetFinalizer(remote, nil)
+
+			cptr := (**C.git_remote)(cremote)
+			*cptr = remote.ptr
+		} else if err == ErrOk && remote == nil {
+			panic("no remote created by callback")
+		}
+
+		return C.int(err)
+	} else {
+		panic("invalid remote create callback")
+	}
+}
+
 func populateCloneOptions(ptr *C.git_clone_options, opts *CloneOptions) {
 	C.git_clone_init_options(ptr, C.GIT_CLONE_OPTIONS_VERSION)
 
@@ -61,12 +87,23 @@
 	ptr.bare = cbool(opts.Bare)
 
 	if opts.RemoteCreateCallback != nil {
-		ptr.remote_cb = opts.RemoteCreateCallback
-		defer C.free(unsafe.Pointer(opts.RemoteCreateCallback))
-
-		if opts.RemoteCreatePayload != nil {
-			ptr.remote_cb_payload = opts.RemoteCreatePayload
-			defer C.free(opts.RemoteCreatePayload)
-		}
+		// Go v1.1 does not allow to assign a C function pointer
+		C._go_git_populate_remote_cb(ptr)
+		ptr.remote_cb_payload = pointerHandles.Track(*opts)
 	}
 }
+
+func freeCloneOptions(ptr *C.git_clone_options) {
+	if ptr == nil {
+		return
+	}
+
+	freeCheckoutOpts(&ptr.checkout_opts)
+
+	if ptr.remote_cb_payload != nil {
+		pointerHandles.Untrack(ptr.remote_cb_payload)
+	}
+
+	C.free(unsafe.Pointer(ptr.checkout_branch))
+	C.free(unsafe.Pointer(ptr))
+}
diff --git a/clone_test.go b/clone_test.go
index fd83fec..86fced8 100644
--- a/clone_test.go
+++ b/clone_test.go
@@ -5,8 +5,11 @@
 	"testing"
 )
 
-func TestClone(t *testing.T) {
+const (
+	REMOTENAME = "testremote"
+)
 
+func TestClone(t *testing.T) {
 	repo := createTestRepo(t)
 	defer cleanupTestRepo(t, repo)
 
@@ -20,3 +23,43 @@
 
 	checkFatal(t, err)
 }
+
+func TestCloneWithCallback(t *testing.T) {
+	testPayload := 0
+
+	repo := createTestRepo(t)
+	defer cleanupTestRepo(t, repo)
+
+	seedTestRepo(t, repo)
+
+	path, err := ioutil.TempDir("", "git2go")
+	checkFatal(t, err)
+
+	opts := CloneOptions{
+		Bare: true,
+		RemoteCreateCallback: func(r Repository, name, url string) (*Remote, ErrorCode) {
+			testPayload += 1
+
+			remote, err := r.CreateRemote(REMOTENAME, url)
+			if err != nil {
+				return nil, ErrGeneric
+			}
+
+			return remote, ErrOk
+		},
+	}
+
+	repo2, err := Clone(repo.Path(), path, &opts)
+	defer cleanupTestRepo(t, repo2)
+
+	checkFatal(t, err)
+
+	if testPayload != 1 {
+		t.Fatal("Payload's value has not been changed")
+	}
+
+	remote, err := repo2.LookupRemote(REMOTENAME)
+	if err != nil || remote == nil {
+		t.Fatal("Remote was not created properly")
+	}
+}
diff --git a/merge.go b/merge.go
index 5b68a8b..183305c 100644
--- a/merge.go
+++ b/merge.go
@@ -10,6 +10,7 @@
 */
 import "C"
 import (
+	"reflect"
 	"runtime"
 	"unsafe"
 )
@@ -243,6 +244,36 @@
 	return newOidFromC(&oid), nil
 }
 
+// MergeBases retrieves the list of merge bases between two commits.
+//
+// If none are found, an empty slice is returned and the error is set
+// approprately
+func (r *Repository) MergeBases(one, two *Oid) ([]*Oid, error) {
+	runtime.LockOSThread()
+	defer runtime.UnlockOSThread()
+
+	var coids C.git_oidarray
+	ret := C.git_merge_bases(&coids, r.ptr, one.toC(), two.toC())
+	if ret < 0 {
+		return make([]*Oid, 0), MakeGitError(ret)
+	}
+
+	oids := make([]*Oid, coids.count)
+	hdr := reflect.SliceHeader {
+		Data: uintptr(unsafe.Pointer(coids.ids)),
+		Len: int(coids.count),
+		Cap: int(coids.count),
+	}
+
+	goSlice := *(*[]C.git_oid)(unsafe.Pointer(&hdr))
+
+	for i, cid := range goSlice {
+		oids[i] = newOidFromC(&cid)
+	}
+
+	return oids, nil
+}
+
 //TODO: int git_merge_base_many(git_oid *out, git_repository *repo, size_t length, const git_oid input_array[]);
 //TODO: GIT_EXTERN(int) git_merge_base_octopus(git_oid *out,git_repository *repo,size_t length,const git_oid input_array[]);
 
@@ -363,6 +394,7 @@
 			return nil, MakeGitError(ecode)
 		}
 		populateCMergeFileOptions(copts, *options)
+		defer freeCMergeFileOptions(copts)
 	}
 
 	runtime.LockOSThread()
diff --git a/merge_test.go b/merge_test.go
index 0b1faca..c09deed 100644
--- a/merge_test.go
+++ b/merge_test.go
@@ -2,6 +2,7 @@
 
 import (
 	"testing"
+	"time"
 )
 
 func TestMergeWithSelf(t *testing.T) {
@@ -88,6 +89,64 @@
 
 }
 
+func appendCommit(t *testing.T, repo *Repository) (*Oid, *Oid) {
+	loc, err := time.LoadLocation("Europe/Berlin")
+	checkFatal(t, err)
+	sig := &Signature{
+		Name:  "Rand Om Hacker",
+		Email: "random@hacker.com",
+		When:  time.Date(2013, 03, 06, 14, 30, 0, 0, loc),
+	}
+
+	idx, err := repo.Index()
+	checkFatal(t, err)
+	err = idx.AddByPath("README")
+	checkFatal(t, err)
+	treeId, err := idx.WriteTree()
+	checkFatal(t, err)
+
+	message := "This is another commit\n"
+	tree, err := repo.LookupTree(treeId)
+	checkFatal(t, err)
+
+	ref, err := repo.LookupReference("HEAD")
+	checkFatal(t, err)
+
+	parent, err := ref.Peel(ObjectCommit)
+	checkFatal(t, err)
+
+	commitId, err := repo.CreateCommit("HEAD", sig, sig, message, tree, parent.(*Commit))
+	checkFatal(t, err)
+
+	return commitId, treeId
+}
+
+func TestMergeBase(t *testing.T) {
+	repo := createTestRepo(t)
+	defer cleanupTestRepo(t, repo)
+
+	commitAId, _ := seedTestRepo(t, repo)
+	commitBId, _ := appendCommit(t, repo)
+
+	mergeBase, err := repo.MergeBase(commitAId, commitBId)
+	checkFatal(t, err)
+
+	if mergeBase.Cmp(commitAId) != 0 {
+		t.Fatalf("unexpected merge base")
+	}
+
+	mergeBases, err := repo.MergeBases(commitAId, commitBId)
+	checkFatal(t, err)
+
+	if len(mergeBases) != 1 {
+		t.Fatalf("expected merge bases len to be 1, got %v", len(mergeBases))
+	}
+
+	if mergeBases[0].Cmp(commitAId) != 0 {
+		t.Fatalf("unexpected merge base")
+	}
+}
+
 func compareBytes(t *testing.T, expected, actual []byte) {
 	for i, v := range expected {
 		if actual[i] != v {
diff --git a/walk.go b/walk.go
index d02044a..c314f60 100644
--- a/walk.go
+++ b/walk.go
@@ -173,6 +173,10 @@
 			return nil
 		}
 		if err != nil {
+			if err.(GitError).Code == ErrIterOver {
+				err = nil
+			}
+
 			return err
 		}
 
diff --git a/wrapper.c b/wrapper.c
index 017168d..3b88f93 100644
--- a/wrapper.c
+++ b/wrapper.c
@@ -5,6 +5,11 @@
 
 typedef int (*gogit_submodule_cbk)(git_submodule *sm, const char *name, void *payload);
 
+void _go_git_populate_remote_cb(git_clone_options *opts)
+{
+	opts->remote_cb = (git_remote_create_cb)remoteCreateCallback;
+}
+
 int _go_git_visit_submodule(git_repository *repo, void *fct)
 {
 	  return git_submodule_foreach(repo, (gogit_submodule_cbk)&SubmoduleVisitor, fct);