【问题标题】:Push local git repository to a user's remote git repository using PyGithub and Python使用 PyGithub 和 Python 将本地 git 存储库推送到用户的远程 git 存储库
【发布时间】:2020-10-26 21:51:42
【问题描述】:

任务是

  1. 克隆公共存储库并将其存储在本地
  2. 使用您在本地下载的存储库内容初始化用户的新存储库(目标)。

CLI 命令完美运行,但我需要使用 python 来完成,当我运行此代码时,会打开一个 github 登录对话框,我输入凭据,然后推送工作,但什么都没有在远程仓库上看到的,我们可以什么都不推送吗?

我也尝试过使用 subprocess 模块,它不起作用。我检查了所有其他 stackoverflow 解决方案,但没有找到可行的解决方案。我需要一个新的解决方案或尽快对此进行更正。谢谢。

import git

git.Repo.clone_from('https://github.com/kristej/Uniform-Database-Management.git','Uniforms')

repo = git.Repo('Uniforms')
target_repo = "https://github.com/kristej/Jojorabit.git"

# List remotes
# Reference a remote by its name as part of the object
print(f'Remote name: {repo.remotes.origin.name}')
print(f'Remote URL: {repo.remotes.origin.url}')

# Delete a default remote if already present
if repo.remotes.origin.url != target_repo:
    repo.delete_remote(repo.remotes.origin.name)

# Create a new remote
try:
    remote = repo.create_remote('origin', url=target_repo)
except git.exc.GitCommandError as error:
    print(f'Error creating remote: {error}')
    
# Reference a remote by its name as part of the object
print(f'Remote name: {repo.remotes.origin.name}')
print(f'Remote URL: {repo.remotes.origin.url}')

#Push changes
print(repo.git.push("origin", "HEAD:refs/for/master"))

【问题讨论】:

    标签: python git pygithub


    【解决方案1】:

    我们可以什么都不推吗?

    是的。如果没有什么可以推送,那么推送就会成功。

    $ git status
    On branch master
    Your branch is up to date with 'origin/master'.
    
    nothing to commit, working tree clean
    
    $ git push
    Everything up-to-date
    

    但你正在推动一个奇怪的位置。 HEAD:refs/for/master 表示将 HEAD 推送到 refs/for/masterrefs/for/master 不是一回事。我想你的意思是refs/heads/master

    但你不应该指定目的地,除非你真的需要,HEAD 不是master?让 Git 找出源(当前签出的分支)和它的目的地(当前分支的上游,或者基于 push.default 的最佳猜测)。

    您只是经历了一堆工作来更改origin,您无需再次指定它。同样,让 push 根据本地分支配置确定推送到哪里更安全。

    print(repo.git.push())
    

    您也无需一键更改origin。您可以改为添加一个新的遥控器并推送到该遥控器。

    repo.create_remote('other_remote', url=target_repo)
    repo.git.push("other_remote")
    

    【讨论】:

    • 哦!我理解它,它就像一个魅力。我刚开始使用 git 并尝试了这个。感谢您的回答,我会阅读更多关于 git 的内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-24
    • 2010-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多