我正在尝试查看 git 分支,使用 python 代码生成文件,然后使用 GitPython 库将更改推送到分支
以下是使用的代码
repo = git.Repo(build_agent_artifact_directory)
branch_name = source_branch_name.split('/')[-1]
if branch_name in repo.branches:
repo.git.checkout(branch_name)
**Python code to generate files and add it to the remote location**
repo.git.add('--all')
repo.index.commit("pushing generated files")
origin = repo.remote(name='origin')
origin.push()
执行脚本时出现以下错误。
git.exc.GitCommandError:Cmd('git')失败,原因是:退出代码(128) 命令行: git push --porcelain origin stderr: '致命:您当前不在分支上。'
它似乎没有成功签出您的目标分支。要检查远程仓库中是否存在一个分支,您可以使用
references
。请参阅下面的示例。
build_agent_artifact_directory = "{The path to your local repo}"
branch_name = "BranchA"
# Initialize the repository
repo = git.Repo(build_agent_artifact_directory)
ref_name = "origin/"+ branch_name
# Checkout target branch if it exists
for ref in repo.references:
if ref_name == ref.name:
print(f"Checkout: {branch_name}")
repo.git.checkout(branch_name)
# Python code to generate files and add it to the remote location**
if branch_name == repo.active_branch.name:
...
repo.index.add(file_name)
# Add all changes to the staging area
repo.git.add('--all')
# Commit the changes
repo.index.commit("pushing generated files")
# Push the changes to the remote repository
origin = repo.remote(name='origin')
origin.push()