我目前正在努力让 go-git 与 GitHub 上的私有存储库一起工作。尽管使用 git 命令行按预期工作 ( git push origin
),但下面的代码片段不起作用。最后一条日志命令返回以下结果:
Error during push error=repository not found
存储库本身确实存在,否则从命令行推送将不起作用。首先,我认为远程存储库为空可能与此有关。但即使不是这样,我也有同样的错误。凭据是有效的,我已经仔细检查了它们。
所以,一定有我遗漏的东西。但由于我是 Go 新手,我的专业知识太低,无法弄清楚。
package git
import (
"io/ioutil"
"path/filepath"
"time"
"github.com/apex/log"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/config"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/go-git/go-git/v5/plumbing/transport/http"
"github.com/spf13/viper"
)
const gitDataDirectory = "./data/"
const defaultRemoteName = "origin"
// Commit creates a commit in the current repository
func Commit() {
repo, err := git.PlainOpen(gitDataDirectory)
if err != nil {
// Repository does not exist yet, create it
log.Info("The Git repository does not exist yet and will be created.")
repo, err = git.PlainInit(gitDataDirectory, false)
}
if err != nil {
log.Warn("The data folder could not be converted into a Git repository. Therefore, the versioning does not work as expected.")
return
}
w, _ := repo.Worktree()
log.Info("Committing new changes...")
w.Add(".gitignore")
w.Add("info.json")
w.Commit("test", &git.CommitOptions{
Author: &object.Signature{
Name: "test",
Email: "test@localhost",
When: time.Now(),
},
})
_, err = repo.Remote(defaultRemoteName)
if err != nil {
log.Info("Creating new Git remote named " + defaultRemoteName)
_, err = repo.CreateRemote(&config.RemoteConfig{
Name: defaultRemoteName,
URLs: []string{"https://github.com/jlnostr/blub.git"},
})
if err != nil {
log.WithError(err).Warn("Error creating remote")
}
}
auth := &http.BasicAuth{
Username: "jlnostr",
Password: "[git_basic_auth_token]",
}
log.Info("Pushing changes to remote")
err = repo.Push(&git.PushOptions{
RemoteName: defaultRemoteName,
Auth: auth,
})
if err != nil {
log.WithError(err).Warn("Error during push")
}
}