GitPython uses a keyword args transformation under the hood:
# cmd.py
def transform_kwarg(self, name: str, value: Any, split_single_char_options: bool) -> List[str]:
if len(name) == 1:
if value is True:
return ["-%s" % name]
elif value not in (False, None):
if split_single_char_options:
return ["-%s" % name, "%s" % value]
else:
return ["-%s%s" % (name, value)]
else:
if value is True:
return ["--%s" % dashify(name)]
elif value is not False and value is not None:
return ["--%s=%s" % (dashify(name), value)]
return []
A resulting list of command parts is fed into subprocess.Popen
, so you do not want to add --single-branch
to the repo URL. If you do, a strange list will be passed to Popen. For example:
['-v', '--branch=my-branch', 'https://github.com/me/my-project.git --single-branch', '/tmp/clone/here']
However, armed with this new information, you can pass any git
CLI flags you like just by using the kwargs
. You may then ask yourself, "How do I pass in a dash to a keyword like single-branch
?" That's a no-go in Python. You will see a dashify
function in the above code which transforms any flag from, say, single_branch=True
to single-branch
, and then to --single-branch
.
Full Example:
Here is a useful example for cloning a single, shallow branch using a personal access token from GitHub:
repo_url = "https://github.com/me/private-project.git"
branch = "wip-branch"
# Notice the trailing : below
credentials = base64.b64encode(f"{GHE_TOKEN}:".encode("latin-1")).decode("latin-1")
Repo.clone_from(
url=repo_url,
c=f"http.{repo_url}/.extraheader=AUTHORIZATION: basic {credentials}",
single_branch=True,
depth=1,
to_path=f"/clone/to/here",
branch=branch,
)
The command list sent to Popen
then looks like this:
['git', 'clone', '-v', '-c', 'http.https://github.com/me/private-project.git/.extraheader=AUTHORIZATION: basic XTE...UwNTo=', '--single-branch', '--depth=1', '--bare', '--branch=wip-branch', 'https://github.com/me/private-project.git', '/clone/to/here']
(PSA: Please do not actually send your personal tokens as part of the URL before the @
.)
clone -b
does is, after cloning the entire repo, it checks out the specific branch instead of the default branch (which is usuallymaster
). So instead of looking for something exotic, why not just do a branch checkout after the clone? – Ardgit clone --single-branch
– Henshawclone -b
does not clone a particular branch. It checks out a particular branch. – Ard