将本地分支推送到远程分支

7

我在Github上创建了一个新的代码库。

使用gitpython库,我可以获取这个代码库。然后我创建了一个新分支,添加了新文件,提交并尝试推送到新分支。

请查看下面的代码:

import git
import random
import os

repo_name = 'test'
branch_name = 'feature4'

remote_repo_addr_git = 'git@repo:DevOps/z_sandbox1.git'

no = random.randint(0,1000)
repo = git.Repo.clone_from(remote_repo_addr_git, repo_name)
new_branch = repo.create_head(branch_name)
repo.head.set_reference(new_branch)
os.chdir(repo_name)
open("parasol" + str(no), "w+").write(str(no)) # this is added
print repo.active_branch
repo.git.add(A=True)
repo.git.commit(m='okej')
repo.git.push(u='origin feature4')

一切都正常工作,直到最后一个推送方法。我遇到了这个错误:

stderr: 'fatal: 'origin feature4'似乎不是git存储库 致命错误:无法从远程存储库读取。

请确保您拥有正确的访问权限 并且存储库存在。

我能够从命令行运行此方法,并且它运行良好:

git puth -u origin feature4

但是在Python中它不起作用。

2个回答

4
这对我很有用:
repo.git.push("origin", "feature4")

1
有关使用gitpython进行fetch/pull/push操作的有用文档: https://gitpython.readthedocs.io/en/stable/reference.html?highlight=index.fetch#git.remote.Remote.fetch
from git import GitCommandError, Repo

repo_name = 'test'
branch_name = 'feature4'
remote_repo_addr_git = 'git@repo:DevOps/z_sandbox1.git'

# clone repo
repo = git.Repo.clone_from(remote_repo_addr_git, repo_name)

# refspec is a sort of mapping between remote:local references
refspec = f'refs/heads/{branch_name}:refs/heads/{branch_name}'

# get branch
try:
    # if exists pull the branch
    # the refspec here means: grab the {branch_name} branch head
    # from the remote repo and store it as my {branch_name} branch head
    repo.remotes.origin.pull(refspec)
except GitCommandError:
    # if not exists create it
    repo.create_head(branch_name)

# checkout branch
branch = repo.heads[branch_name]
branch.checkout()

# modify files
with open(f'{repo_name}/hello.txt', 'w') as file:
    file.write('hello')

# stage & commit & push
repo.index.add('**')
repo.index.commit('added good manners')
# refspec here means: publish my {branch_name} branch head
# as {branch_name} remote branch
repo.remotes.origin.push(refspec)

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