首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用基本身份验证推送到远程

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

Stack Overflow用户
提问于 2020-05-08 10:48:33
回答 2查看 2.1K关注 0票数 0

目前,我很难让git在GitHub上使用私有存储库。尽管使用git命令行的工作方式与预期的(git push origin)相同,但下面的代码片段不起作用。最后一个log命令返回以下结果:

代码语言:javascript
复制
 Error during push     error=repository not found

存储库本身确实存在,否则命令行的推送将无法工作。首先,我想,远程存储库是空的,这可能是相关的。但即使不是这样,我也犯了同样的错误。证件是有效的,我已经查过了。

所以,一定有什么东西我错过了。但由于我是新来的,我的专业知识太低,无法弄清楚这一点。

代码语言:javascript
复制
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")
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-05-11 11:26:35

有几个问题:

  1. GitHub令牌只能访问公共存储库,但我尝试将其推入私有存储库。使用repo权限(而不仅仅是repo:public)有所帮助。回购程序
  2. 尚未“真正”初始化。就像@peakle提到的那样,在这种情况下,推手前的拉力起了作用。

因此,下面是一个使用go-git v5初始化私有存储库的完整工作示例。

代码语言:javascript
复制
package git

import (
    "io/ioutil"
    "path/filepath"
    "time"

    "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 = "./data/"
const defaultRemoteName = "origin"

var auth = &http.BasicAuth{
    Username: "<username>",
    Password: "<git_basic_auth_token>",
}

func createCommitOptions() *git.CommitOptions {
    return &git.CommitOptions{
        Author: &object.Signature{
            Name:  "Rick Astley",
            Email: "never.gonna.give.you.up@localhost",
            When:  time.Now(),
        },
    }
}

// Commit creates a commit in the current repository
func Commit() {
    err := initializeGitRepository()
    if err != nil {
        // logging: The folder could not be converted into a Git repository.
        return
    }

    // Open after initialization
    repo, _ := git.PlainOpen(gitDataDirectory)
    w, _ := repo.Worktree()

    status, _ := w.Status()
    if status.IsClean() {
        return
    }

    // Committing new changes
    w.Add("<your_file>.txt")
    w.Commit("test", createCommitOptions())

    // Pushing to remote
    err = repo.Push(&git.PushOptions{
        RemoteName: defaultRemoteName,
        Auth:       auth,
    })
}

func initializeGitRepository() error {
    _, err := git.PlainOpen(gitDataDirectory)
    if err == nil {
        return nil
    }

    // The Git repository does not exist yet and will be created.

    repo, err := git.PlainInit(gitDataDirectory, false)

    if err != nil {
        return err
    }

    // Writing default .gitignore with "media/" as first line
    filename := filepath.Join(gitDataDirectory, ".gitignore")
    err = ioutil.WriteFile(filename, []byte("media/"), 0644)

    if err != nil {
        return err
    }

    w, _ := repo.Worktree()
    w.Add(".gitignore")
    w.Commit("Initial commit", createCommitOptions())

    return initializeRemote()
}

func initializeRemote() error {
    repo, err := git.PlainOpen(gitDataDirectory)
    if err != nil {
        return err
    }

    _, err = repo.Remote(defaultRemoteName)
    if err == nil {
        // Repo already exists, skipping
        return nil
    }

    w, err := repo.Worktree()
    if err != nil {
        return err
    }

    refspec := config.RefSpec("+refs/heads/*:refs/remotes/origin/*")

    // Creating default remote
    _, err = repo.CreateRemote(&config.RemoteConfig{
        Name:  defaultRemoteName,
        URLs:  []string{"https://github.com/<user>/<repo>.git"},
        Fetch: []config.RefSpec{refspec},
    })

    if err != nil {
        // TODO
    }

    // Pulling from remote
    w.Pull(&git.PullOptions{
        RemoteName: defaultRemoteName,
        Auth:       auth,
    })

    return err
}
票数 0
EN

Stack Overflow用户

发布于 2020-05-09 20:21:46

我尝试了几次代码,并进行了如下所示的最小更改,当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-not-found,我认为您在回购名称上有错误,或者类似于上面的链接中描述的情况。

另外,对于将来对代码库的增强,我在git尚未输入的情况下遇到了问题,我添加了一些代码和TODO块,并给出了一些建议,也许它可以在将来帮助您:)

代码语言:javascript
复制
package main

import (
    "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 repository
func 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")
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61677396

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档