With GitPython
, I can create a new repo with the following:
from git.repo.base import Repo
Repo.init('/tmp/some-repo/')
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'
In the git docs, it states that the command for setting initial branch is --initial-branch
(https://git-scm.com/docs/git-init/2.28.0#Documentation/git-init.txt---initial-branchltbranch-namegt).
Judging by the error, I think that the additional kwargs feature of GitPython is not including the --
prefix.
According to the docs, init
takes the same arguments as git init
as keyword arguments. You do have to turn -
into _
.
from git import Repo
Repo.init('/tmp/some-repo/', initial_branch='main')
UPDATE
initial-branch
was added very recently in v2.28.0. You'll need to upgrade Git to use it.
If you can't, manually change the branch name with branch.rename(new_name)
. Unfortunately you can't do this until after the first commit, no branches truly exist yet. That's a Git limitation and why they added initial-branch
and also the init.defaultBranch
config option.