Skip to content

Log: Object not found when using git worktree #394

@psh-baxter

Description

@psh-baxter

This is an upstream git worktree, as created with git worktree add. .git is a file with a gitdir: pointer to the base repo. git log works fine, however git.Log(repo, ...) exits with the error Object not found.
Here's a minimal reproduction:

package main

import (
	"io/ioutil"
	"log"
	"os"
	"os/exec"

	"github.com/go-git/go-git/v5"
	"github.com/go-git/go-git/v5/plumbing/object"
	"github.com/google/shlex"
)

func mkdir(path string) {
	_ = os.MkdirAll(path, 0o755)
}

func write(path string, text string) {
	_ = ioutil.WriteFile(path, []byte(text), 0o644)
}

func run(cwd string, command string) {
	parts, _ := shlex.Split(command)
	cmd := exec.Command(parts[0], parts[1:]...)
	cmd.Dir = cwd
	_ = cmd.Run()
}

func main() {
	mkdir("temp_repo")
	run("temp_repo", "git init")
	write("temp_repo/a.txt", "hi")
	run("temp_repo", "git add a.txt")
	run("temp_repo", "git commit -a -m 'commit 1' -n")
	write("temp_repo/a.txt", "hi 2")
	run("temp_repo", "git commit -a -m 'commit 2' -n")
	write("temp_repo/a.txt", "hi 3")
	run("temp_repo", "git commit -a -m 'commit 3' -n")
	mkdir("temp_worktree")
	run("temp_repo", "git worktree add -b mybranch ../temp_worktree master")

	rawRepo, err := git.PlainOpen("temp_worktree")
	if err != nil {
		log.Panic(err)
	}

	iter, err := rawRepo.Log(&git.LogOptions{})
	if err != nil {
		log.Panic(err)
	}
	err = iter.ForEach(func(c *object.Commit) error {
		log.Print(c)
		return nil
	})
	if err != nil {
		log.Panic(err)
	}
}

Run output:

$ ./a
2021/10/13 20:49:38 reference not found
panic: reference not found

goroutine 1 [running]:
log.Panic(0xc0000f1f28, 0x1, 0x1)
	/usr/lib/go-1.15/src/log/log.go:351 +0xae
main.main()
	/home/.../gogittest/main.go:49 +0x3f6

go.mod:

	github.com/go-git/go-git/v5 v5.4.2
	github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions