Lon*_*Dev 5 python git gitpython
With GitPython, I can create a new repo with the following:
from git.repo.base import Repo
Repo.init('/tmp/some-repo/')
Run Code Online (Sandbox Code Playgroud)
The repo is created with the default branch master.
How can I modify this default branch?
Update: As suggested in the answers below, I have tried using Repo.init('/tmp/some-repo', initial_branch="main"), however it renders this exception:
Traceback (most recent call last):
File "/app/checker/tests.py", line 280, in test_alternative_compare_branch
comp_repo_main = Repo.init(
File "/usr/local/lib/python3.9/site-packages/git/repo/base.py", line 937, in init
git.init(**kwargs)
File "/usr/local/lib/python3.9/site-packages/git/cmd.py", line 542, in <lambda>
return lambda *args, **kwargs: self._call_process(name, *args, **kwargs)
File "/usr/local/lib/python3.9/site-packages/git/cmd.py", line 1005, in _call_process
return self.execute(call, **exec_kwargs)
File "/usr/local/lib/python3.9/site-packages/git/cmd.py", line 822, in execute
raise GitCommandError(command, status, stderr_value, stdout_value)
git.exc.GitCommandError: Cmd('git') failed due to: exit code(129)
cmdline: git init --initial-branch=main
stderr: 'error: unknown option `initial-branch=main'
Run Code Online (Sandbox Code Playgroud)
在 git 文档中,它指出设置初始分支的命令是--initial-branch(https://git-scm.com/docs/git-init/2.28.0#Documentation/git-init.txt---initial-branchltbranch-名称gt)。
从错误来看,我认为 GitPython 的附加 kwargs 功能不包括前缀--。
根据文档,init采用与关键字参数相同的参数git init。你确实必须-变成_.
from git import Repo
Repo.init('/tmp/some-repo/', initial_branch='main')
Run Code Online (Sandbox Code Playgroud)
更新
initial-branch最近在 v2.28.0 中添加。您需要升级 Git 才能使用它。
如果不能,请使用 手动更改分支名称branch.rename(new_name)。不幸的是,直到第一次提交之后你才能执行此操作,因为还没有分支真正存在。这是 Git 的限制,也是他们添加的原因initial-branch以及init.defaultBranch配置选项。