nicetoolbox.utils.git_utils.CustomRepo¶
- class nicetoolbox.utils.git_utils.CustomRepo(repo_path)[source]¶
Bases:
RepoCustomize the Repo class from gitpython for easier access/use.
This class extends the base class Repo from gitpython and provides additional methods for easier access and use of a git repository.
- Parameters:
repo_path (str) – The path to the git repository.
- Raises:
RuntimeError – If the repo_path is not a valid directory or a git repository.
- None¶
See also
Documentation of the base class Repo: https://gitpython.readthedocs.io/en/stable/index.html
Create a new Repo instance
- Parameters:
path –
the path to either the root git directory or the bare git repo:
repo = Repo("/Users/mtrier/Development/git-python") repo = Repo("/Users/mtrier/Development/git-python.git") repo = Repo("~/Development/git-python.git") repo = Repo("$REPOSITORIES/Development/git-python.git") repo = Repo("C:\Users\mtrier\Development\git-python\.git")
In Cygwin, path may be a ‘cygdrive/…’ prefixed path.
If it evaluates to false,
GIT_DIRis used, and if this also evals to false, the current-directory is used.
odbt – Object DataBase type - a type which is constructed by providing the directory containing the database objects, i.e. .git/objects. It will be used to access all object data
search_parent_directories –
if True, all parent directories will be searched for a valid repo as well.
Please note that this was the default behaviour in older versions of GitPython, which is considered a bug though.
- Raises:
InvalidGitRepositoryError –
NoSuchPathError –
- Returns:
git.Repo
Methods
Archive the tree at the given revision.
The blame information for the given file at the given revision.
Iterator for blame information for the given file at the given revision.
Create a clone from this repository.
Create a clone from the given URL
closeThe Commit object for the specified revision
- return:
- return:
Create a new head within the repository.
Create a new remote.
Create a new submodule
Create a new tag reference.
- return:
The commit which is currently being replayed while rebasing.
Delete the given heads
Delete the given remote.
Delete the given tag references
Get the latest commit hash and message of the git repository.
- return:
True if our git_dir is not at the root of our working_tree_dir, but a .git file with a
Checks if paths are ignored via .gitignore Doing so using the "git check-ignore" method.
Initialize a git repository at the given path if specified
Check if a commit is an ancestor of another
- return:
is_valid_objectA list of Commit objects representing the history of a given ref/commit
An iterator yielding Submodule instances, see Traversable interface for a description of args and kwargs
- return:
Iterator yielding Tree objects
Find the closest common ancestor for the given revision (e.g.
- return:
Remote with the specified name
- return:
Object at the given revision, either Commit, Tag, Tree or Blob
- return:
Submodule with the given name
Update the submodules, keeping the repository consistent as it will take the previous state into consideration.
- return:
TagReference Object, reference pointing to a Commit or Tag
The Tree object for the given treeish revision Examples.
Attributes
DAEMON_EXPORT_FILEThe name of the currently active branch.
Retrieve a list of alternates paths or set a list paths to be used as alternates
True if the repository is bare
A list of
Headobjects representing the branch heads in this repoThe git dir that holds everything except possibly HEAD, FETCH_HEAD, ORIG_HEAD, COMMIT_EDITMSG, index, and logs/.
config_levelIf True, git-daemon may export this repository
the project's description
gitHEAD Object pointing to the current head reference
A list of
Headobjects representing the branch heads in this repoIndexFile representing this repository's index. :note: This property can be expensive, as the returned
IndexFilewill be reinitialized. It's recommended to re-use the object.re_author_committer_startre_envvarsre_hexsha_onlyre_hexsha_shortenedre_tab_full_linere_whitespaceA list of Reference objects representing tags, heads and remote references.
A list of Reference objects representing tags, heads and remote references.
A list of Remote objects allowing to access and manipulate remotes
git.IterableList(Submodule, ...) of direct submodules available from the current head
A list of
Tagobjects that are available in this repounsafe_git_clone_options- returns:
list(str,...)
The working tree directory of our git repository.
working_dirgit_dir- GitCommandWrapperType¶
alias of
Git
- property active_branch: Head¶
The name of the currently active branch.
- Raises:
TypeError – If HEAD is detached
- Returns:
Head to the active branch
- property alternates: List[str]¶
Retrieve a list of alternates paths or set a list paths to be used as alternates
- archive(ostream: TextIO | BinaryIO, treeish: str | None = None, prefix: str | None = None, **kwargs: Any) Repo¶
Archive the tree at the given revision.
- Parameters:
ostream – file compatible stream object to which the archive will be written as bytes
treeish – is the treeish name/id, defaults to active branch
prefix – is the optional prefix to prepend to each filename in the archive
kwargs –
Additional arguments passed to git-archive
Use the ‘format’ argument to define the kind of format. Use specialized ostreams to write any format supported by python.
You may specify the special path keyword, which may either be a repository-relative path to a directory or file to place into the archive, or a list or tuple of multiple paths.
- Raises:
GitCommandError – in case something went wrong
- Returns:
self
- property bare: bool¶
True if the repository is bare
- Type:
return
- blame(rev: str | HEAD, file: str, incremental: bool = False, rev_opts: List[str] | None = None, **kwargs: Any) List[List[Commit | List[str | bytes] | None]] | Iterator[BlameEntry] | None¶
The blame information for the given file at the given revision.
- Parameters:
rev – revision specifier, see git-rev-parse for viable options.
- Returns:
list: [git.Commit, list: [<line>]] A list of lists associating a Commit object with a list of lines that changed within the given commit. The Commit objects will be given in order of appearance.
- blame_incremental(rev: str | HEAD, file: str, **kwargs: Any) Iterator[BlameEntry]¶
Iterator for blame information for the given file at the given revision.
Unlike .blame(), this does not return the actual file’s contents, only a stream of BlameEntry tuples.
- Parameters:
rev – revision specifier, see git-rev-parse for viable options.
- Returns:
lazy iterator of BlameEntry tuples, where the commit indicates the commit to blame for the line, and range indicates a span of line numbers in the resulting file.
If you combine all line number ranges outputted by this command, you should get a continuous range spanning all line numbers in the file.
- property branches: IterableList[Head]¶
A list of
Headobjects representing the branch heads in this repo- Returns:
git.IterableList(Head, ...)
- clone(path: str | PathLike[str], progress: Callable[[int, str | float, str | float | None, str], None] | None = None, multi_options: List[str] | None = None, allow_unsafe_protocols: bool = False, allow_unsafe_options: bool = False, **kwargs: Any) Repo¶
Create a clone from this repository.
- Parameters:
path – is the full path of the new repo (traditionally ends with ./<name>.git).
progress – See ‘git.remote.Remote.push’.
multi_options – A list of Clone options that can be provided multiple times. One option per list item which is passed exactly as specified to clone. For example [’–config core.filemode=false’, ‘–config core.ignorecase’, ‘–recurse-submodule=repo1_path’, ‘–recurse-submodule=repo2_path’]
allow_unsafe_protocols – Allow unsafe protocols to be used, like ext
allow_unsafe_options – Allow unsafe options to be used, like –upload-pack
kwargs –
odbt = ObjectDatabase Type, allowing to determine the object database implementation used by the returned Repo instance
All remaining keyword arguments are given to the git-clone command
- Returns:
git.Repo(the newly cloned repo)
- classmethod clone_from(url: str | PathLike[str], to_path: str | PathLike[str], progress: Callable[[int, str | float, str | float | None, str], None] | None = None, env: Mapping[str, str] | None = None, multi_options: List[str] | None = None, allow_unsafe_protocols: bool = False, allow_unsafe_options: bool = False, **kwargs: Any) Repo¶
Create a clone from the given URL
- Parameters:
url – valid git url, see http://www.kernel.org/pub/software/scm/git/docs/git-clone.html#URLS
to_path – Path to which the repository should be cloned to
progress – See ‘git.remote.Remote.push’.
env – Optional dictionary containing the desired environment variables. Note: Provided variables will be used to update the execution environment for git. If some variable is not specified in env and is defined in os.environ, value from os.environ will be used. If you want to unset some variable, consider providing empty string as its value.
multi_options – See
clonemethodallow_unsafe_protocols – Allow unsafe protocols to be used, like ext
allow_unsafe_options – Allow unsafe options to be used, like –upload-pack
kwargs – see the
clonemethod
- Returns:
Repo instance pointing to the cloned directory
- commit(rev: str | Commit_ish | None = None) Commit¶
The Commit object for the specified revision
- Parameters:
rev – revision specifier, see git-rev-parse for viable options.
- Returns:
git.Commit
- property common_dir: str | PathLike[str]¶
The git dir that holds everything except possibly HEAD, FETCH_HEAD, ORIG_HEAD, COMMIT_EDITMSG, index, and logs/.
- Type:
return
- config_reader(config_level: Literal['system', 'global', 'user', 'repository'] | None = None) GitConfigParser¶
- Returns:
GitConfigParser allowing to read the full git configuration, but not to write it
The configuration will include values from the system, user and repository configuration files.
- Parameters:
config_level – For possible values, see config_writer method If None, all applicable levels will be used. Specify a level in case you know which file you wish to read to prevent reading multiple files.
- Note:
On windows, system configuration cannot currently be read as the path is unknown, instead the global path will be used.
- config_writer(config_level: Literal['system', 'global', 'user', 'repository'] = 'repository') GitConfigParser¶
- Returns:
GitConfigParser allowing to write values of the specified configuration file level. Config writers should be retrieved, used to change the configuration, and written right away as they will lock the configuration file in question and prevent other’s to write it.
- Parameters:
config_level – One of the following values system = system wide configuration file global = user level configuration file repository = configuration file for this repository only
- create_head(path: PathLike, commit: 'SymbolicReference' | 'str' = 'HEAD', force: bool = False, logmsg: str | None = None) Head¶
Create a new head within the repository. For more documentation, please see the Head.create method.
- Returns:
newly created Head Reference
- create_remote(name: str, url: str, **kwargs: Any) Remote¶
Create a new remote.
For more information, please see the documentation of the Remote.create methods
- Returns:
Remote reference
- create_submodule(*args: Any, **kwargs: Any) Submodule¶
Create a new submodule
- Note:
See the documentation of Submodule.add for a description of the applicable parameters
- Returns:
created submodules
- create_tag(path: PathLike, ref: str | 'SymbolicReference' = 'HEAD', message: str | None = None, force: bool = False, **kwargs: Any) TagReference¶
Create a new tag reference. For more documentation, please see the TagReference.create method.
- Returns:
TagReference object
- currently_rebasing_on() Commit | None¶
- Returns:
The commit which is currently being replayed while rebasing.
None if we are not currently rebasing.
- property daemon_export: bool¶
If True, git-daemon may export this repository
- delete_head(*heads: str | Head, **kwargs: Any) None¶
Delete the given heads
- Parameters:
kwargs – Additional keyword arguments to be passed to git-branch
- delete_remote(remote: Remote) str¶
Delete the given remote.
- property description: str¶
the project’s description
- get_git_hash()[source]¶
Get the latest commit hash and message of the git repository.
- Returns:
- A tuple containing the latest commit hash (string) and the
commit message (string).
- Return type:
tuple
- Raises:
RuntimeError – If the repository is not a valid git repository.
- has_separate_working_tree() bool¶
- Returns:
True if our git_dir is not at the root of our working_tree_dir, but a .git file with a platform agnositic symbolic link. Our git_dir will be wherever the .git file points to
- Note:
bare repositories will always return False here
- property head: HEAD¶
HEAD Object pointing to the current head reference
- Type:
return
- property heads: IterableList[Head]¶
A list of
Headobjects representing the branch heads in this repo- Returns:
git.IterableList(Head, ...)
- ignored(*paths: str | PathLike[str]) List[str]¶
Checks if paths are ignored via .gitignore Doing so using the “git check-ignore” method.
- Parameters:
paths – List of paths to check whether they are ignored or not
- Returns:
subset of those paths which are ignored
- property index: IndexFile¶
IndexFile representing this repository’s index. :note: This property can be expensive, as the returned
IndexFilewill bereinitialized. It’s recommended to re-use the object.
- Type:
return
- classmethod init(path: str | ~os.PathLike[str] | None = None, mkdir: bool = True, odbt: ~typing.Type[~git.db.GitCmdObjectDB] = <class 'git.db.GitCmdObjectDB'>, expand_vars: bool = True, **kwargs: ~typing.Any) Repo¶
Initialize a git repository at the given path if specified
- Parameters:
path – is the full path to the repo (traditionally ends with /<name>.git) or None in which case the repository will be created in the current working directory
mkdir – if specified will create the repository directory if it doesn’t already exists. Creates the directory with a mode=0755. Only effective if a path is explicitly given
odbt – Object DataBase type - a type which is constructed by providing the directory containing the database objects, i.e. .git/objects. It will be used to access all object data
expand_vars – if specified, environment variables will not be escaped. This can lead to information disclosure, allowing attackers to access the contents of environment variables
kwargs – keyword arguments serving as additional options to the git-init command
- Returns:
git.Repo(the newly created repo)
- is_ancestor(ancestor_rev: Commit, rev: Commit) bool¶
Check if a commit is an ancestor of another
- Parameters:
ancestor_rev – Rev which should be an ancestor
rev – Rev to test against ancestor_rev
- Returns:
True, ancestor_rev is an ancestor to rev.
- is_dirty(index: bool = True, working_tree: bool = True, untracked_files: bool = False, submodules: bool = True, path: str | PathLike[str] | None = None) bool¶
- Returns:
True, the repository is considered dirty. By default it will react like a git-status without untracked files, hence it is dirty if the index or the working copy have changes.
- iter_commits(rev: str | Commit | 'SymbolicReference' | None = None, paths: PathLike | Sequence[PathLike] = '', **kwargs: Any) Iterator[Commit]¶
A list of Commit objects representing the history of a given ref/commit
- Parameters:
rev – revision specifier, see git-rev-parse for viable options. If None, the active branch will be used.
paths – is an optional path or a list of paths; if set only commits that include the path or paths will be returned
kwargs – Arguments to be passed to git-rev-list - common ones are max_count and skip
- Note:
to receive only commits between two named revisions, use the “revA…revB” revision specifier
- Returns:
git.Commit[]
- iter_submodules(*args: Any, **kwargs: Any) Iterator[Submodule]¶
An iterator yielding Submodule instances, see Traversable interface for a description of args and kwargs
- Returns:
Iterator
- iter_trees(*args: Any, **kwargs: Any) Iterator['Tree']¶
- Returns:
Iterator yielding Tree objects
- Note:
Takes all arguments known to iter_commits method
- merge_base(*rev: TBD, **kwargs: Any) List[Commit_ish | None]¶
Find the closest common ancestor for the given revision (e.g. Commits, Tags, References, etc)
- Parameters:
rev – At least two revs to find the common ancestor for.
kwargs – Additional arguments to be passed to the repo.git.merge_base() command which does all the work.
- Returns:
A list of Commit objects. If –all was not specified as kwarg, the list will have at max one Commit, or is empty if no common merge base exists.
- Raises:
ValueError – If not at least two revs are provided
- property references: IterableList[Reference]¶
A list of Reference objects representing tags, heads and remote references.
- Returns:
IterableList(Reference, …)
- property refs: IterableList[Reference]¶
A list of Reference objects representing tags, heads and remote references.
- Returns:
IterableList(Reference, …)
- remote(name: str = 'origin') Remote¶
- Returns:
Remote with the specified name
- Raises:
ValueError – if no remote with such a name exists
- property remotes: IterableList[Remote]¶
A list of Remote objects allowing to access and manipulate remotes
- Returns:
git.IterableList(Remote, ...)
- rev_parse(rev: str) 'Commit' | 'Tag' | 'Tree' | 'Blob'¶
- Returns:
Object at the given revision, either Commit, Tag, Tree or Blob
- Parameters:
rev – git-rev-parse compatible revision specification as string, please see http://www.kernel.org/pub/software/scm/git/docs/git-rev-parse.html for details
- Raises:
BadObject – if the given revision could not be found
ValueError – If rev couldn’t be parsed
IndexError – If invalid reflog index is specified
- submodule(name: str) Submodule¶
- Returns:
Submodule with the given name
- Raises:
ValueError – If no such submodule exists
- submodule_update(*args: Any, **kwargs: Any) Iterator[Submodule]¶
Update the submodules, keeping the repository consistent as it will take the previous state into consideration. For more information, please see the documentation of RootModule.update
- property submodules: IterableList[Submodule]¶
git.IterableList(Submodule, …) of direct submodules available from the current head
- Type:
return
- tag(path: str | PathLike[str]) TagReference¶
- Returns:
TagReference Object, reference pointing to a Commit or Tag
- Parameters:
path – path to the tag reference, i.e. 0.1.5 or tags/0.1.5
- property tags: IterableList[TagReference]¶
A list of
Tagobjects that are available in this repo- Returns:
git.IterableList(TagReference, ...)
- tree(rev: Tree_ish | str | None = None) Tree¶
The Tree object for the given treeish revision Examples:
repo.tree(repo.heads[0])
- Parameters:
rev – is a revision pointing to a Treeish ( being a commit or tree )
- Returns:
git.Tree- Note:
If you need a non-root level tree, find it by iterating the root tree. Otherwise it cannot know about its path relative to the repository root and subsequent operations might have unexpected results.
- property untracked_files: List[str]¶
- Returns:
list(str,…)
Files currently untracked as they have not been staged yet. Paths are relative to the current working directory of the git command.
- Note:
ignored files will not appear here, i.e. files mentioned in .gitignore
- Note:
This property is expensive, as no cache is involved. To process the result, please consider caching it yourself.