src-d / go-git

Project has been moved to: https://github.com/go-git/go-git
https://github.com/go-git/go-git
Apache License 2.0
4.91k stars 541 forks source link

How to GetTree for a commit hash ? #1227

Closed alexisvisco closed 4 years ago

alexisvisco commented 4 years ago

Hello, I am wondering how to get tree changes from two commits hashes ?

Currently I am just doing this:

func main() {
    repo, err := git.PlainOpen(".")
    if err != nil {
        log.Fatal("can't open from path: ", err)
    }

    oldTree, e := object.GetTree(repo.Storer, plumbing.NewHash("82381fd4160e109a64e0d37688eb67a600a37a24"))
    newTree, f := object.GetTree(repo.Storer, plumbing.NewHash("d70914c1c1c57bc07f0975760db125878cc675c7"))

    changes, g := oldTree.Diff(newTree)

    fmt.Println(changes.String(), e, f, g)

}

local git log output:

gta on  master [!?] via 🐹 v1.12.4 
❯ git log
commit 2adaec054efb50ff678b50c7f55e08a5d32253b9 (HEAD -> master)
Author: Alexis <alexis@batch.com>
Date:   Wed Oct 16 11:41:32 2019 +0200

    init 3

commit d70914c1c1c57bc07f0975760db125878cc675c7
Author: Alexis <alexis@batch.com>
Date:   Wed Oct 16 11:38:08 2019 +0200

    init 2

commit 82381fd4160e109a64e0d37688eb67a600a37a24
Author: Alexis <alexis@batch.com>
Date:   Wed Oct 16 10:53:39 2019 +0200

    init

And the output of the program is: [] object not found object not found <nil>

So the two first errors are fill with that, I don't understand at all how to use GetTree.

Someone can help me ?

alexisvisco commented 4 years ago

Attempt 2:

Regarding the source code of GetTree it is using EncodeObject with plumbing.TreeObject, changing to CommitObject resolve to unsupported object typeerror.

Attempt 3:

changing DecodeTree with DecodeCommit works but I didn't have a Tree which is my objective.

alexisvisco commented 4 years ago

Solved solution is:

    oldEncodeObject, err := repo.Storer.EncodedObject(plumbing.CommitObject, plumbing.NewHash("82381fd4160e109a64e0d37688eb67a600a37a24"))
    if err != nil {
        log.Fatal("can'tget old encode object: ", err)

    }

    newEncodeObject, err := repo.Storer.EncodedObject(plumbing.CommitObject, plumbing.NewHash("d70914c1c1c57bc07f0975760db125878cc675c7"))
    if err != nil {
        log.Fatal("can'tget new encode object: ", err)
    }

    old, _ := object.DecodeCommit(repo.Storer, oldEncodeObject)
    new, _ := object.DecodeCommit(repo.Storer, newEncodeObject)

    oldTree, _ := old.Tree()
    newTree, _ := new.Tree()

    changes, err := oldTree.Diff(newTree)
    if err != nil {
        log.Fatal(err)
    }