使用 go-git 从 GitHub Enterprise 克隆存储库

Clone a repository from GitHub Enterprise with go-git

我正在尝试使用 go-git 从 GitHub Enterprise 克隆存储库。为此,我使用带有访问令牌的 HTTPS 协议,该令牌对我的存储库具有适当的权限(在命令行上验证)。 go-git 在进行 git-upload-pack RPC 调用时失败,因为服务器响应 400:

$ go run main.go
unexpected client error: unexpected requesting "https://github.mycompany.net/my-org/myrepo.git/info/refs?service=git-upload-pack" status code: 400

它发出的请求等同于:

GET /my-org/myrepo.git/info/refs?service=git-upload-pack HTTP/1.1
Host: github.mycompany.net
User-Agent: git/1.0
Accept: */*
Authorization: Bearer atokenthatisdefinitelyvalid

请求 header 中没有令牌,我从存储库中得到预期的 401 (Anonymous access denied) 响应。使用令牌,它以 400 响应。

我发现 non-Enterprise GitHub 上的 public 存储库也是如此;不同之处在于它(预期)在没有 Authorization header 的情况下工作,因为 none 是必需的。如果我包含一个有效的令牌,GitHub 就像它的企业版以 400 响应一样。

下面是一个最小的例子。有没有办法将 go-git 与需要身份验证的 GitHub 企业一起使用?理想情况下使用身份验证令牌?

package main

import (
    "fmt"
    "io/ioutil"

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

const (
    repoURL           = "https://github.mycompany.net/my-org/myrepo.git"
    githubAccessToken = "atokenthatisdefinitelyvalid"
)

func main() {
    dir, _ := ioutil.TempDir("", "temp_dir")

    options := &git.CloneOptions{
        Auth:          &http.TokenAuth{Token: githubAccessToken},
        URL:           repoURL,
        Depth:         500,
        ReferenceName: plumbing.ReferenceName("refs/heads/master"),
        SingleBranch:  true,
        Tags:          git.NoTags,
    }

    _, err := git.PlainClone(dir, false, options)
    fmt.Println(err)
}

他们有能力使用令牌:

https://github.com/src-d/go-git/blob/master/plumbing/transport/http/common.go#L204-L227

import (
  git "gopkg.in/src-d/go-git.v4"
  "gopkg.in/src-d/go-git.v4/plumbing/transport/http"
)

func main() {
  ...
  auth := http.TokenAuth{Token: "TOKEN_HERE"}
  opts := git.CloneOptions{
    URL:  "https://github.com/user/repo",
    Auth: &auth,
  }
  git.PlainClone("/tmp/cloneDir", false, &opts)
  ..
}

不能 100% 确定这是否会解决您的所有问题

原来 Github 使用令牌作为您用户的密码,因此它需要基本身份验证而不是 header:

中的令牌
options := &git.CloneOptions{
    Auth:          &http.BasicAuth{Username: "myusername", Token: "mytoken"},
    URL:           repoURL,
    Depth:         500,
    ReferenceName: plumbing.ReferenceName("refs/heads/master"),
    SingleBranch:  true,
    Tags:          git.NoTags,
}