使用基本身份验证推送到远程

我目前正在努力让 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]",

    }


守着星空守着你
浏览 90回答 2
2回答

慕莱坞森

我尝试了几次您的代码,并进行了如下的最小更改,并且在 repo 也克隆和 git 启动的情况下工作正常,提交消息以批准:https ://github.com/peakle/iptables-http-services/commit/56eba2fcc4fac790ad573942ab1b926ddadf0875我无法重现您的问题,但也许它可以帮助您解决您的案例中发生的 git 错误:https ://help.github.com/en/github/creating-cloning-and-archiving-repositories/error-repository-未找到,我认为您在 repo 名称上有拼写错误或类似于上面链接中描述的情况。并且为了将来增强您的代码库,我在 git 尚未启动的情况下遇到问题,我添加了一些代码和 TODO 块并提供建议,也许它可以在将来帮助您:)package mainimport (    "fmt"    _ "io/ioutil"    "os"    _ "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")const gitDataDirectory = "/Users/peakle/projects/tests/iptables-http-services"const defaultRemoteName = "origin"func main() {    filename := "kek.txt"    file, _ := os.Create(fmt.Sprintf("%s/%s", gitDataDirectory, filename))    _, _ = file.Write([]byte("test string2"))    Commit(filename)}// Commit creates a commit in the current repositoryfunc Commit(filename string) {    var isNewInit bool    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)        isNewInit = true    }    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...")    if isNewInit {        err = w.AddGlob("*")        if err != nil {            fmt.Println(err)        }        //TODO if its new git init, need to add `git pull` command  with remote branch    } else {        _, _ = w.Add(filename)    }    _, _ = w.Commit("test", &git.CommitOptions{        Author: &object.Signature{            Name:  "peakle",            Email: "test@mail.com",            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/Peakle/iptables-http-services.git"},        })        if err != nil {            log.WithError(err).Warn("Error creating remote")        }    }    auth := &http.BasicAuth{        Username: "peakle",        Password: "authtoken",    }    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")    }}

茅侃侃

有几个问题:GitHub 令牌只能访问公共存储库,但我尝试推送到私有存储库。使用repo权限(而不仅仅是repo:public)有所帮助。回购尚未“真正”初始化。正如@peakle 所提到的,在这种情况下,先拉后推会有所帮助。因此,下面是使用 go-git v5 初始化私有存储库的完整工作示例。package gitimport (&nbsp; &nbsp; "io/ioutil"&nbsp; &nbsp; "path/filepath"&nbsp; &nbsp; "time"&nbsp; &nbsp; "github.com/go-git/go-git/v5"&nbsp; &nbsp; "github.com/go-git/go-git/v5/config"&nbsp; &nbsp; "github.com/go-git/go-git/v5/plumbing/object"&nbsp; &nbsp; "github.com/go-git/go-git/v5/plumbing/transport/http")const gitDataDirectory = "./data/"const defaultRemoteName = "origin"var auth = &http.BasicAuth{&nbsp; &nbsp; Username: "<username>",&nbsp; &nbsp; Password: "<git_basic_auth_token>",}func createCommitOptions() *git.CommitOptions {&nbsp; &nbsp; return &git.CommitOptions{&nbsp; &nbsp; &nbsp; &nbsp; Author: &object.Signature{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Name:&nbsp; "Rick Astley",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Email: "never.gonna.give.you.up@localhost",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; When:&nbsp; time.Now(),&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; }}// Commit creates a commit in the current repositoryfunc Commit() {&nbsp; &nbsp; err := initializeGitRepository()&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; // logging: The folder could not be converted into a Git repository.&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; }&nbsp; &nbsp; // Open after initialization&nbsp; &nbsp; repo, _ := git.PlainOpen(gitDataDirectory)&nbsp; &nbsp; w, _ := repo.Worktree()&nbsp; &nbsp; status, _ := w.Status()&nbsp; &nbsp; if status.IsClean() {&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; }&nbsp; &nbsp; // Committing new changes&nbsp; &nbsp; w.Add("<your_file>.txt")&nbsp; &nbsp; w.Commit("test", createCommitOptions())&nbsp; &nbsp; // Pushing to remote&nbsp; &nbsp; err = repo.Push(&git.PushOptions{&nbsp; &nbsp; &nbsp; &nbsp; RemoteName: defaultRemoteName,&nbsp; &nbsp; &nbsp; &nbsp; Auth:&nbsp; &nbsp; &nbsp; &nbsp;auth,&nbsp; &nbsp; })}func initializeGitRepository() error {&nbsp; &nbsp; _, err := git.PlainOpen(gitDataDirectory)&nbsp; &nbsp; if err == nil {&nbsp; &nbsp; &nbsp; &nbsp; return nil&nbsp; &nbsp; }&nbsp; &nbsp; // The Git repository does not exist yet and will be created.&nbsp; &nbsp; repo, err := git.PlainInit(gitDataDirectory, false)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return err&nbsp; &nbsp; }&nbsp; &nbsp; // Writing default .gitignore with "media/" as first line&nbsp; &nbsp; filename := filepath.Join(gitDataDirectory, ".gitignore")&nbsp; &nbsp; err = ioutil.WriteFile(filename, []byte("media/"), 0644)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return err&nbsp; &nbsp; }&nbsp; &nbsp; w, _ := repo.Worktree()&nbsp; &nbsp; w.Add(".gitignore")&nbsp; &nbsp; w.Commit("Initial commit", createCommitOptions())&nbsp; &nbsp; return initializeRemote()}func initializeRemote() error {&nbsp; &nbsp; repo, err := git.PlainOpen(gitDataDirectory)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return err&nbsp; &nbsp; }&nbsp; &nbsp; _, err = repo.Remote(defaultRemoteName)&nbsp; &nbsp; if err == nil {&nbsp; &nbsp; &nbsp; &nbsp; // Repo already exists, skipping&nbsp; &nbsp; &nbsp; &nbsp; return nil&nbsp; &nbsp; }&nbsp; &nbsp; w, err := repo.Worktree()&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return err&nbsp; &nbsp; }&nbsp; &nbsp; refspec := config.RefSpec("+refs/heads/*:refs/remotes/origin/*")&nbsp; &nbsp; // Creating default remote&nbsp; &nbsp; _, err = repo.CreateRemote(&config.RemoteConfig{&nbsp; &nbsp; &nbsp; &nbsp; Name:&nbsp; defaultRemoteName,&nbsp; &nbsp; &nbsp; &nbsp; URLs:&nbsp; []string{"https://github.com/<user>/<repo>.git"},&nbsp; &nbsp; &nbsp; &nbsp; Fetch: []config.RefSpec{refspec},&nbsp; &nbsp; })&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; // TODO&nbsp; &nbsp; }&nbsp; &nbsp; // Pulling from remote&nbsp; &nbsp; w.Pull(&git.PullOptions{&nbsp; &nbsp; &nbsp; &nbsp; RemoteName: defaultRemoteName,&nbsp; &nbsp; &nbsp; &nbsp; Auth:&nbsp; &nbsp; &nbsp; &nbsp;auth,&nbsp; &nbsp; })&nbsp; &nbsp; return err}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go