如何使用golang在git仓库中签出特定的SHA

时间:2019-06-28 16:57:36

标签: go go-git

我需要帮助,以使用golang将代码检出到git repo的特定SHA编号

1 个答案:

答案 0 :(得分:0)

这实际上是一个Go问题,因为它是指go-git library

这样,您可以执行以下操作:

package main

import (
    "fmt"

     git "gopkg.in/src-d/go-git.v4"
     "gopkg.in/src-d/go-git.v4/plumbing"
)

// Basic example of how to checkout a specific commit.
func main() {
    // Clone the given repository to the given directory
    r, err := git.PlainClone("your-local-repo-name", false, &git.CloneOptions{
        URL: "your-repo-clone-URL",
    })
    // handle error

    // ... retrieving the commit being pointed by HEAD
    ref, err := r.Head()
    // handle error

    w, err := r.Worktree()
    // handle error

    // ... checking out to commit
    err = w.Checkout(&git.CheckoutOptions{
        Hash: plumbing.NewHash("your-specific-commit-hash"),
    })
    // handle error

    // ... retrieving the commit being pointed by HEAD, it shows that the
    // repository is pointing to the giving commit in detached mode
    ref, err = r.Head()
    // handle error

    fmt.Println(ref.Hash())
}

注意: 该代码的大部分来自go-gitexamples目录,并通过将存储库克隆到新的本地目录来启动整个过程;如果不适用于您的用例,请跳过此步骤。