如何使用go-git将特定分支推送到远程仓库

3

使用go-git将特定本地分支推送到特定远程仓库的规范方式是什么?

我已经用go-git检出并打开了一个本地仓库。

repo, err := git.PlainOpen("my-repo")

该仓库具有默认的origin远程。

我正在尝试将此存储库的内容同步到另一个mirror远程,因此我正在添加远程。

repo.CreateRemote(&config.RemoteConfig{
                Name: "mirror",
                URLs: []string{"git@github.com:foo/mirror.git"},
            })

首先,我从origin获取存储库内容

err = remote.Fetch(&git.FetchOptions{
                RemoteName: "origin",
                Tags:       git.AllTags,
            })

...使用remote.List()进行所有感兴趣的分支和标签的发现。

最后一步是将分支推送到mirror,同时根据映射重写分支名称。例如,检出为refs/heads/masterrefs/remotes/origin/master应该被推送到mirror远程作为main。因此,我正在迭代分支并尝试逐个推送它们:

refSpec := config.RefSpec(fmt.Sprintf(
                "+%s:refs/remotes/mirror/%s",
                localBranch.Name().String(),
                // map branch names, e.g. master -> main
                mapBranch(remoteBranch.Name().Short()),
            ))
err = repo.Push(&git.PushOptions{
                RemoteName: "mirror",
                Force:      true,
                RefSpecs:   []config.RefSpec{refSpec},
                Atomic:     true,
            })

但这会导致 git.NoErrAlreadyUpToDate,并且在 mirror 远程上没有任何动作发生。

从我深入研究的地方 - https://github.com/go-git/go-git/blob/master/remote.go#L741 - cmd.Old == cmd.New - 这些哈希值是相等的,因此推送命令不会被添加到队列中。 - David Lukac
localBranch 是指什么?你不想将 refs/remotes/origin/* 推送到你的镜像吗? - LeGEC
话虽如此:我觉得 git-go 在本地进行检查并选择不发送看起来“最新”的内容是令人惊讶的。这实际上可能是一个问题。 - LeGEC
1个回答

2

refSpec在将单个分支推送到远程时,应该以格式+refs/heads/localBranchName:refs/remotes/remoteName/remoteBranchName表示,例如在此处指示:

// RefSpec is a mapping from local branches to remote references.
...
// eg.: "+refs/heads/*:refs/remotes/origin/*"
//
// https://git-scm.com/book/en/v2/Git-Internals-The-Refspec
type RefSpec string

但是作为

"+refs/heads/localBranchName:refs/heads/remoteBranchName"

而不是。请参见示例

    refSpecStr := fmt.Sprintf(
        "+%s:refs/heads/%s",
        localBranch.Name().String(),
        mapBranch(remoteBranch.Name().Short()),
    )
    refSpec := config.RefSpec(refSpecStr)
    log.Infof("Pushing %s", refSpec)
    err = repo.Push(&git.PushOptions{
        RemoteName: "mirror",
        Force:      true,
        RefSpecs:   []config.RefSpec{refSpec},
        Atomic:     true,
    })

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接