libvcs.cmd.gitΒΆ
For git(1).
Compare to: fabtools.git,
salt.modules.git,
ansible.builtin.git
Managers and CommandsΒΆ
libvcs provides Managers and Commands for git subcommands:
Managers (
git.branches,git.tags, etc.) let you traverse repository entities intuitively with ORM-like filtering via QueryListCommands are contextual ways to run git commands against a specific target entity
Git instance
βββ branches: GitBranchManager
β βββ ls() -> QueryList[GitBranchCmd]
β βββ get() -> GitBranchCmd
β βββ create()
βββ tags: GitTagManager
βββ remotes: GitRemoteManager
βββ stashes: GitStashManager
βββ worktrees: GitWorktreeManager
βββ notes: GitNotesManager
βββ submodules: GitSubmoduleManager
βββ reflog: GitReflogManager
Quick ExampleΒΆ
from libvcs.cmd.git import Git
git = Git(path='/path/to/repo')
# List all branches
branches = git.branches.ls()
# Filter to remote branches only
remote_branches = git.branches.ls(remotes=True)
# Get a specific branch and rename it
branch = git.branches.get(branch_name='old-name')
branch.rename('new-name')
# Create and manage tags
git.tags.create(name='v1.0.0', message='Release 1.0')
tag = git.tags.get(tag_name='v1.0.0')
tag.delete()
Run git commands directly against a local git repo.
Bases:
objectRun commands directly on a git repository.
Lite, typed, pythonic wrapper for git(1).
- Parameters:
path (StrPath) β Operates as PATH in the corresponding git subcommand.
progress_callback (ProgressCallbackProtocol | None)
- Return type:
Examples
>>> git = Git(path=example_git_repo.path) >>> git <Git path=...>
Subcommands:
>>> git.remotes.show() 'origin'
>>> git.remotes.add( ... name='my_remote', url=f'file:///dev/null' ... ) ''
>>> git.remotes.show() 'my_remote\norigin'
>>> git.stash.save(message="Message") 'No local changes to save'
>>> git.submodule.init() ''
# Additional tests
>>> git.remotes.get(remote_name='my_remote').remove() '' >>> git.remotes.show() 'origin'
>>> git.stash.ls() ''
>>> git.stashes.ls() []
>>> git.tags.create(name='v1.0.0', message='Version 1.0.0') ''
>>> any(t.tag_name == 'v1.0.0' for t in git.tags.ls()) True
-
attribute
-
attribute
-
attribute
-
attribute
-
attribute
-
attribute
-
attribute
-
attribute
-
attribute
-
attribute
-
attribute
-
run(args, *, version=None, _help=None, html_path=None, man_path=None, info_path=None, C=None, cwd=None, git_dir=None, work_tree=None, namespace=None, super_prefix=None, exec_path=None, bare=None, no_replace_objects=None, literal_pathspecs=None, global_pathspecs=None, noglob_pathspecs=None, icase_pathspecs=None, no_optional_locks=None, config=None, config_env=None, log_in_real_time=False, **kwargs)ΒΆmethod[source]
Run a command for this git repository.
Passing None to a subcommand option, the flag wonβt be passed unless otherwise stated.
git help and git help [cmd]
Wraps gitβs Options.
- Parameters:
cwd (
libvcs._internal.types.StrOrBytesPath, optional, passed to) β subprocessβscwdthe command runs from. Defaults tocwd.C (
libvcs._internal.types.StrOrBytesPath, optional) β-C <path>git_dir (
libvcs._internal.types.StrOrBytesPath, optional) β--git-dir <path>work_tree (
libvcs._internal.types.StrOrBytesPath, optional) β--work-tree <path>namespace (
libvcs._internal.types.StrOrBytesPath, optional) β--namespace <path>super_prefix (
libvcs._internal.types.StrOrBytesPath, optional) β--super-prefix <path>exec_path (
libvcs._internal.types.StrOrBytesPath, optional) β--exec-path=<path>bare (bool) β
--bareno_replace_objects (bool) β
--no-replace-objectsliteral_pathspecs (bool) β
--literal-pathspecsglobal_pathspecs (bool) β
--glob-pathspecsnoglob_pathspecs (bool) β
--noglob-pathspecsicase_pathspecs (bool) β
--icase-pathspecsno_optional_locks (bool) β
--no-optional-locksversion (bool) β
--versionhtml_path (bool) β
--html-pathman_path (bool) β
--man-pathinfo_path (bool) β
--info-path_help (bool) β
-h / --helppager (bool) β
-p --pagerno_pager (bool) β
-P / --no-pagerargs (_CMD)
log_in_real_time (bool)
kwargs (Any)
- Return type:
Examples
>>> git = Git(path=tmp_path) >>> git.run(['help']) "usage: git [...--version] [...--help] [-C <path>]..."
-
clone(*, url, separate_git_dir=None, template=None, depth=None, branch=None, origin=None, upload_pack=None, shallow_since=None, shallow_exclude=None, reference=None, reference_if_able=None, server_option=None, jobs=None, force=None, local=None, _all=None, no_hardlinks=None, hardlinks=None, shared=None, progress=None, no_checkout=None, no_reject_shallow=None, reject_shallow=None, sparse=None, shallow_submodules=None, no_shallow_submodules=None, remote_submodules=None, no_remote_submodules=None, verbose=None, quiet=None, config=None, log_in_real_time=False, check_returncode=None, make_parents=True, **kwargs)ΒΆmethod[source]
Clone a working copy from an git repo.
Wraps git clone.
- Parameters:
url (str)
directory (str)
separate_git_dir (StrOrBytesPath) β Separate repository (.git/ ) from working tree
force (bool, optional) β force operation to run
make_parents (bool, default: True) β Creates checkout directory (:attr:`self.path) if it doesnβt already exist.
log_in_real_time (bool)
kwargs (Any)
- Return type:
Examples
>>> git = Git(path=tmp_path) >>> git_remote_repo = create_git_remote_repo() >>> git.clone(url=f'file://{git_remote_repo}') '' >>> git.path.exists() True
-
fetch(*, reftag=None, deepen=None, depth=None, upload_pack=None, shallow_since=None, shallow_exclude=None, negotiation_tip=None, jobs=None, server_option=None, recurse_submodules=None, recurse_submodules_default=None, submodule_prefix=None, _all=None, force=None, keep=None, multiple=None, dry_run=None, append=None, atomic=None, ipv4=None, ipv6=None, progress=None, quiet=None, verbose=None, unshallow=None, update_shallow=None, negotiate_tip=None, no_write_fetch_head=None, write_fetch_head=None, no_auto_maintenance=None, auto_maintenance=None, no_write_commit_graph=None, write_commit_graph=None, prefetch=None, prune=None, prune_tags=None, no_tags=None, tags=None, no_recurse_submodules=None, set_upstream=None, update_head_ok=None, show_forced_updates=None, no_show_forced_updates=None, negotiate_only=None, check_returncode=None, **kwargs)ΒΆmethod[source]
Download from repo. Wraps git fetch.
Examples
>>> git = Git(path=example_git_repo.path) >>> git_remote_repo = create_git_remote_repo() >>> git.fetch() '' >>> git = Git(path=example_git_repo.path) >>> git_remote_repo = create_git_remote_repo() >>> git.fetch(reftag=f'file://{git_remote_repo}') '' >>> git.path.exists() True
-
rebase(*, upstream=None, onto=None, branch=None, apply=None, merge=None, quiet=None, verbose=None, stat=None, no_stat=None, verify=None, no_verify=None, fork_point=None, no_fork_point=None, whitespace=None, ignore_whitespace=None, commit_date_is_author_date=None, ignore_date=None, root=None, autostash=None, no_autostash=None, autosquash=None, no_autosquash=None, reschedule_failed_exec=None, no_reschedule_failed_exec=None, context=None, rerere_autoupdate=None, no_rerere_autoupdate=None, keep_empty=None, no_keep_empty=None, reapply_cherry_picks=None, no_reapply_cherry_picks=None, allow_empty_message=None, signoff=None, keep_base=None, strategy=None, strategy_option=None, _exec=None, gpg_sign=None, no_gpg_sign=None, empty=None, rebase_merges=None, interactive=None, edit_todo=None, skip=None, show_current_patch=None, abort=None, _quit=None, check_returncode=None, **kwargs)ΒΆmethod[source]
Reapply commit on top of another tip.
Wraps git rebase.
Examples
>>> git = Git(path=example_git_repo.path) >>> git_remote_repo = create_git_remote_repo() >>> git.rebase() 'Current branch master is up to date.'
Declare upstream:
>>> git = Git(path=example_git_repo.path) >>> git_remote_repo = create_git_remote_repo() >>> git.rebase(upstream='origin') 'Current branch master is up to date.' >>> git.path.exists() True
-
pull(*, reftag=None, repository=None, deepen=None, depth=None, upload_pack=None, shallow_since=None, shallow_exclude=None, negotiation_tip=None, jobs=None, server_option=None, recurse_submodules=None, recurse_submodules_default=None, submodule_prefix=None, cleanup=None, rebase=None, no_rebase=None, strategy=None, strategy_option=None, gpg_sign=None, no_gpg_sign=None, commit=None, no_commit=None, edit=None, no_edit=None, fast_forward_only=None, fast_forward=None, no_fast_forward=None, sign_off=None, no_sign_off=None, stat=None, no_stat=None, squash=None, no_squash=None, verify=None, no_verify=None, verify_signatures=None, no_verify_signatures=None, summary=None, no_summary=None, autostash=None, no_autostash=None, allow_unrelated_histories=None, fetch=None, no_fetch=None, _all=None, force=None, keep=None, multiple=None, dry_run=None, append=None, atomic=None, ipv4=None, ipv6=None, progress=None, quiet=None, verbose=None, unshallow=None, update_shallow=None, negotiate_tip=None, no_write_fetch_head=None, write_fetch_head=None, no_auto_maintenance=None, auto_maintenance=None, no_write_commit_graph=None, write_commit_graph=None, prefetch=None, prune=None, prune_tags=None, no_tags=None, tags=None, no_recurse_submodules=None, set_upstream=None, update_head_ok=None, show_forced_updates=None, no_show_forced_updates=None, negotiate_only=None, log_in_real_time=False, check_returncode=None, **kwargs)ΒΆmethod[source]
Download from repo. Wraps git pull.
Examples
>>> git = Git(path=example_git_repo.path) >>> git_remote_repo = create_git_remote_repo() >>> git.pull() 'Already up to date.'
Fetch via ref:
>>> git = Git(path=tmp_path) >>> git.run(['init']) 'Initialized ...' >>> git_remote_repo = create_git_remote_repo() >>> git.pull(reftag=f'file://{git_remote_repo}') '' >>> git.path.exists() True
Create empty repo. Wraps git init.
- Parameters:
template (str | pathlib.Path, optional) β Directory from which templates will be used. The template directory contains files and directories that will be copied to the $GIT_DIR after it is created. The template directory will be one of the following (in order): - The argument given with the βtemplate option - The contents of the $GIT_TEMPLATE_DIR environment variable - The init.templateDir configuration variable - The default template directory: /usr/share/git-core/templates
separate_git_dir (
libvcs._internal.types.StrOrBytesPath, optional) β Instead of placing the git repository in <directory>/.git/, place it in the specified path. The .git file at <directory>/.git will contain a gitfile that points to the separate git dir. This is useful when you want to store the git directory on a different disk or filesystem.object_format ('sha1' | 'sha256', optional) β Specify the hash algorithm to use. The default is sha1. Note that sha256 is still experimental in git and requires git version >= 2.29.0. Once the repository is created with a specific hash algorithm, it cannot be changed.
branch (str, optional) β Use the specified name for the initial branch. If not specified, fall back to the default name (currently βmasterβ, but may change based on init.defaultBranch configuration).
initial_branch (str, optional) β Alias for branch parameter. Specify the name for the initial branch. This is provided for compatibility with newer git versions.
shared (bool | str, optional) β Specify that the git repository is to be shared amongst several users. Valid values are: - false: Turn off sharing (default) - true: Same as group - umask: Use permissions specified by umask - group: Make the repository group-writable - all, world, everybody: Same as world, make repo readable by all users - An octal number string: Explicit mode specification (e.g., β0660β)
quiet (bool, optional) β Only print error and warning messages; all other output will be suppressed. Useful for scripting.
bare (bool, optional) β Create a bare repository. If GIT_DIR environment is not set, it is set to the current working directory. Bare repositories have no working tree and are typically used as central repositories.
ref_format ('files' | 'reftable', optional) β Specify the reference storage format. Requires git version >= 2.37.0. - files: Classic format with packed-refs and loose refs (default) - reftable: New format that is more efficient for large repositories
check_returncode (bool, optional) β If True, check the return code of the git command and raise a CalledProcessError if it is non-zero.
make_parents (bool, default: True) β If True, create the target directory if it doesnβt exist. If False, raise an error if the directory doesnβt exist.
kwargs (Any)
- Returns:
The output of the git init command.
- Return type:
- Raises:
CalledProcessError β If the git command fails and check_returncode is True.
ValueError β If invalid parameters are provided.
FileNotFoundError β If make_parents is False and the target directory doesnβt exist.
Examples
>>> git = Git(path=tmp_path) >>> git.init() 'Initialized empty Git repository in ...'
Create with a specific initial branch name:
>>> new_repo = tmp_path / 'branch_example' >>> new_repo.mkdir() >>> git = Git(path=new_repo) >>> git.init(branch='main') 'Initialized empty Git repository in ...'
Create a bare repository:
>>> bare_repo = tmp_path / 'bare_example' >>> bare_repo.mkdir() >>> git = Git(path=bare_repo) >>> git.init(bare=True) 'Initialized empty Git repository in ...'
Create with a separate git directory:
>>> repo_path = tmp_path / 'repo' >>> git_dir = tmp_path / 'git_dir' >>> repo_path.mkdir() >>> git_dir.mkdir() >>> git = Git(path=repo_path) >>> git.init(separate_git_dir=str(git_dir.absolute())) 'Initialized empty Git repository in ...'
Create with shared permissions:
>>> shared_repo = tmp_path / 'shared_example' >>> shared_repo.mkdir() >>> git = Git(path=shared_repo) >>> git.init(shared='group') 'Initialized empty shared Git repository in ...'
Create with octal permissions:
>>> shared_repo = tmp_path / 'shared_octal_example' >>> shared_repo.mkdir() >>> git = Git(path=shared_repo) >>> git.init(shared='0660') 'Initialized empty shared Git repository in ...'
Create with a template directory:
>>> template_repo = tmp_path / 'template_example' >>> template_repo.mkdir() >>> git = Git(path=template_repo) >>> git.init(template=str(tmp_path)) 'Initialized empty Git repository in ...'
Create with SHA-256 object format (requires git >= 2.29.0):
>>> sha256_repo = tmp_path / 'sha256_example' >>> sha256_repo.mkdir() >>> git = Git(path=sha256_repo) >>> git.init(object_format='sha256') 'Initialized empty Git repository in ...'
Help info. Wraps git help.
- Parameters:
_all (bool) β Prints everything.
no_external_commands (bool) β For use with
all, excludes external commands.no_aliases (bool) β For use with
all, excludes aliases.verbose (bool) β For us with
all, on by default.config (bool) β List all config vars.
guides (bool) β List concept guides.
info (bool) β Display man page in info format.
man (bool) β Man page.
web (bool) β Man page in HTML.
kwargs (Any)
- Return type:
Examples
>>> git = Git(path=tmp_path)
>>> git.help() "usage: git [...--version] [...--help] [-C <path>]..."
>>> git.help(_all=True) "See 'git help <command>' to read about a specific subcommand..."
>>> git.help(info=True) "usage: git [...--version] [...--help] [-C <path>] [-c <name>=<value>]..."
>>> git.help(man=True) "usage: git [...--version] [...--help] [-C <path>] [-c <name>=<value>]..."
Reset HEAD. Wraps git help.
- Parameters:
quiet (bool)
no_refresh (bool)
refresh (bool)
pathspec_from_file (
libvcs._internal.types.StrOrBytesPath)pathspec_file_nul (bool)
pathspec (
libvcs._internal.types.StrOrBytesPathor list) βlibvcs._internal.types.StrOrBytesPathsoft (bool)
mixed (bool)
hard (bool)
merge (bool)
keep (bool)
commit (str)
kwargs (Any)
- Return type:
Examples
>>> git = Git(path=example_git_repo.path)
>>> git.reset() ''
>>> git.reset(soft=True, commit='HEAD~0') ''
-
checkout(*, quiet=None, progress=None, no_progress=None, pathspec_from_file=None, pathspec=None, force=None, ours=None, theirs=None, no_track=None, guess=None, no_guess=None, _list=None, detach=None, merge=None, ignore_skip_worktree_bits=None, patch=None, orphan=None, conflict=None, overwrite_ignore=None, no_overwrite_ignore=None, recurse_submodules=None, no_recurse_submodules=None, overlay=None, no_overlay=None, commit=None, branch=None, new_branch=None, start_point=None, treeish=None, check_returncode=None, **kwargs)ΒΆmethod[source]
Switch branches or checks out files.
Wraps git checkout (git co).
- Parameters:
quiet (bool)
progress (bool)
no_progress (bool)
pathspec_from_file (
libvcs._internal.types.StrOrBytesPath)pathspec (
libvcs._internal.types.StrOrBytesPathor list) βlibvcs._internal.types.StrOrBytesPathforce (bool)
ours (bool)
theirs (bool)
no_track (bool)
guess (bool)
no_guess (bool)
ignore_skip_worktree_bits (bool)
merge (bool)
_list (bool)
detach (bool)
patch (bool)
orphan (bool)
conflict (str)
overwrite_ignore (bool)
no_overwrite_ignore (bool)
commit (str)
branch (str)
new_branch (str)
start_point (str)
treeish (str)
kwargs (Any)
- Return type:
Examples
>>> git = Git(path=example_git_repo.path)
>>> git.checkout() "Your branch is up to date with 'origin/master'."
>>> git.checkout(branch='origin/master', pathspec='.') ''
-
status(*, verbose=None, long=None, short=None, branch=None, z=None, column=None, no_column=None, ahead_behind=None, no_ahead_behind=None, renames=None, no_renames=None, find_renames=None, porcelain=None, untracked_files=None, ignored=None, ignored_submodules=None, pathspec=None, check_returncode=None, **kwargs)ΒΆmethod[source]
- Parameters:
verbose (bool)
long (bool)
short (bool)
branch (bool)
z (bool)
column (bool)
no_column (bool)
ahead_behind (bool)
no_ahead_behind (bool)
find_renames (bool)
no_find_renames (bool)
untracked_files ('no', 'normal', 'all')
ignored ('traditional', 'no', 'matching')
ignored_submodules ('untracked', 'dirty', 'all')
pathspec (
libvcs._internal.types.StrOrBytesPathor list) βlibvcs._internal.types.StrOrBytesPathkwargs (Any)
- Return type:
Examples
>>> git = Git(path=example_git_repo.path)
>>> git.status() "On branch master..."
>>> pathlib.Path(example_git_repo.path / 'new_file.txt').touch()
>>> git.status(porcelain=True) '?? new_file.txt'
>>> git.status(porcelain='1') '?? new_file.txt'
>>> git.status(porcelain='2') '? new_file.txt'
>>> git.status(C=example_git_repo.path / '.git', porcelain='2') '? new_file.txt'
>>> git.status(porcelain=True, untracked_files="no") ''
-
config(*, replace_all=None, get=None, get_all=None, get_regexp=None, get_urlmatch=None, system=None, local=None, worktree=None, file=None, blob=None, remove_section=None, rename_section=None, unset=None, unset_all=None, _list=None, fixed_value=None, no_type=None, null=None, name_only=None, show_origin=None, show_scope=None, get_color=None, get_colorbool=None, default=None, _type=None, edit=None, no_includes=None, includes=None, add=None, check_returncode=None, **kwargs)ΒΆmethod[source]
Get and set repo configuration.
- Parameters:
file (StrOrBytesPath | None)
_type ('bool', 'int', 'bool-or-int', 'path', 'expiry-date', 'color')
kwargs (Any)
- Return type:
Examples
>>> git = Git(path=example_git_repo.path)
>>> git.config() '...: ...'
>>> git.config(_list=True) '...user.email=...'
>>> git.config(get='color.diff') 'auto'
Version. Wraps git version.
Examples
>>> git = Git(path=example_git_repo.path)
>>> git.version() 'git version ...'
>>> git.version(build_options=True) 'git version ...'
rev-parse. Wraps git rev-parse.
Examples
>>> git = Git(path=example_git_repo.path)
>>> git.rev_parse() ''
>>> git.rev_parse(parseopt=True) 'usage: git rev-parse --parseopt...'
>>> git.rev_parse(verify=True, args='HEAD') '...'
-
rev_list(*, commit, path=None, max_count=None, skip=None, since=None, after=None, until=None, before=None, max_age=None, min_age=None, author=None, committer=None, grep=None, all_match=None, invert_grep=None, regexp_ignore_case=None, basic_regexp=None, extended_regexp=None, fixed_strings=None, perl_regexp=None, remove_empty=None, merges=None, no_merges=None, no_min_parents=None, min_parents=None, no_max_parents=None, max_parents=None, first_parent=None, exclude_first_parent_only=None, _not=None, _all=None, branches=None, tags=None, remotes=None, exclude=None, reflog=None, alternative_refs=None, single_worktree=None, ignore_missing=None, stdin=None, disk_usage=None, cherry_mark=None, cherry_pick=None, left_only=None, right_only=None, cherry=None, walk_reflogs=None, merge=None, boundary=None, use_bitmap_index=None, progress=None, header=None, check_returncode=True, log_in_real_time=False, **kwargs)ΒΆmethod[source]
rev-list. Wraps git rev-list.
Examples
>>> git = Git(path=example_git_repo.path)
>>> git.rev_list(commit="HEAD") '...'
>>> git.run(['commit', '--allow-empty', '--message=Moo']) '[master ...] Moo'
>>> git.rev_list(commit="HEAD", max_count=1) '...'
>>> git.rev_list(commit="HEAD", path=".", max_count=1, header=True) '...'
>>> git.rev_list(commit="origin..HEAD", max_count=1, _all=True, header=True) '...'
>>> git.rev_list(commit="origin..HEAD", max_count=1, header=True) '...'
Return symbolic-ref.
Wraps git symbolic-ref.
Examples
>>> git = Git(path=example_git_repo.path)
>>> git.symbolic_ref(name="test") 'fatal: ref test is not a symbolic ref'
>>> git.symbolic_ref(name="test") 'fatal: ref test is not a symbolic ref'
show-ref. Wraps git show-ref.
Examples
>>> git = Git(path=example_git_repo.path)
>>> git.show_ref() '...'
>>> git.show_ref(pattern='master') '...'
>>> git.show_ref(pattern='master', head=True) '...'
>>> git.show_ref(pattern='HEAD', verify=True) '... HEAD'
>>> git.show_ref(pattern='master', dereference=True) '... refs/heads/master\n... refs/remotes/origin/master'
>>> git.show_ref(pattern='HEAD', tags=True) ''