Repository¶
The Repository class provides an interface for analyzing a single Git repository. It can be created from either a local or remote repository.
Overview¶
The Repository class offers methods for:
Commit history analysis with filtering options
File change tracking and blame information
Branch existence checking and repository status
Bus factor calculation and repository metrics
Punchcard statistics generation
Creating a Repository¶
You can create a Repository object in two ways:
Local Repository¶
Create a Repository from a local Git repository:
from gitpandas import Repository
repo = Repository(
working_dir='/path/to/repo/',
verbose=True,
default_branch='main' # Optional, will auto-detect if not specified
)
The directory must contain a .git directory. Subdirectories are not searched.
Remote Repository¶
Create a Repository from a remote Git repository:
from gitpandas import Repository
repo = Repository(
working_dir='git://github.com/user/repo.git',
verbose=True,
default_branch='main' # Optional, will auto-detect if not specified
)
The repository will be cloned locally into a temporary directory. This can be slow for large repositories.
Available Methods¶
Core Analysis¶
# Commit history analysis
repo.commit_history(
branch=None, # Branch to analyze
limit=None, # Maximum number of commits
days=None, # Limit to last N days
ignore_globs=None, # Files to ignore
include_globs=None # Files to include
)
# File change history
repo.file_change_history(
branch=None,
limit=None,
days=None,
ignore_globs=None,
include_globs=None
)
# Blame analysis
repo.blame(
rev="HEAD", # Revision to analyze
committer=True, # Group by committer (False for author)
by="repository", # Group by 'repository' or 'file'
ignore_globs=None,
include_globs=None
)
# Bus factor analysis
repo.bus_factor(
by="repository", # How to group results ('repository' or 'file')
ignore_globs=None,
include_globs=None
)
# Commit pattern analysis
repo.punchcard(
branch=None,
limit=None,
days=None,
by=None, # Additional grouping
normalize=None, # Normalize values
ignore_globs=None,
include_globs=None
)
Repository Information¶
# List files in repository
repo.list_files(rev="HEAD")
# Check branch existence
repo.has_branch(branch)
# Check if repository is bare
repo.is_bare()
# Check for coverage information
repo.has_coverage()
repo.coverage()
# Get specific commit content
repo.get_commit_content(
rev, # Revision to analyze
ignore_globs=None,
include_globs=None
)
Common Parameters¶
Most analysis methods support these filtering parameters:
branch: Branch to analyze (defaults to repository’s default branch)
limit: Maximum number of commits to analyze
days: Limit analysis to last N days
ignore_globs: List of glob patterns for files to ignore
include_globs: List of glob patterns for files to include
by: How to group results (usually ‘repository’ or ‘file’)
API Reference¶
- class gitpandas.repository.Repository(working_dir=None, verbose=False, tmp_dir=None, cache_backend=None, labels_to_add=None, default_branch=None)[source]¶
Bases:
objectA class for analyzing a single git repository.
This class provides functionality to analyze a git repository, whether it is a local repository or a remote repository that needs to be cloned. It offers methods for analyzing commit history, blame information, file changes, and other git metrics.
- Parameters:
working_dir (Optional[str]) – Path to the git repository: - If None: Uses current working directory - If local path: Path must contain a .git directory - If git URL: Repository will be cloned to a temporary directory
verbose (bool, optional) – Whether to print verbose output. Defaults to False.
tmp_dir (Optional[str]) – Directory to clone remote repositories into. Created if not provided.
cache_backend (Optional[object]) – Cache backend instance from gitpandas.cache
labels_to_add (Optional[List[str]]) – Extra labels to add to output DataFrames
default_branch (Optional[str]) – Name of the default branch to use. If None, will try to detect ‘main’ or ‘master’, and if neither exists, will raise ValueError.
- Variables:
verbose (bool) – Whether verbose output is enabled
git_dir (str) – Path to the git repository
repo (git.Repo) – GitPython Repo instance
cache_backend (Optional[object]) – Cache backend being used
_labels_to_add (List[str]) – Labels to add to DataFrames
_git_repo_name (Optional[str]) – Repository name for remote repos
default_branch (str) – Name of the default branch
- Raises:
ValueError – If default_branch is None and neither ‘main’ nor ‘master’ branch exists
Examples
>>> # Create from local repository >>> repo = Repository('/path/to/repo')
>>> # Create from remote repository >>> repo = Repository('git://github.com/user/repo.git')
Note
When using remote repositories, they will be cloned to temporary directories. This can be slow for large repositories.
- __init__(working_dir=None, verbose=False, tmp_dir=None, cache_backend=None, labels_to_add=None, default_branch=None)[source]¶
Initialize a Repository instance.
- Parameters:
working_dir (Optional[str]) – Path to the git repository: - If None: Uses current working directory - If local path: Path must contain a .git directory - If git URL: Repository will be cloned to a temporary directory
verbose (bool, optional) – Whether to print verbose output. Defaults to False.
tmp_dir (Optional[str]) – Directory to clone remote repositories into. Created if not provided.
cache_backend (Optional[object]) – Cache backend instance from gitpandas.cache
labels_to_add (Optional[List[str]]) – Extra labels to add to output DataFrames
default_branch (Optional[str]) – Name of the default branch to use. If None, will try to detect ‘main’ or ‘master’, and if neither exists, will raise ValueError.
- Raises:
ValueError – If default_branch is None and neither ‘main’ nor ‘master’ branch exists
- __del__()[source]¶
Cleanup method called when the object is destroyed.
Cleans up any temporary directories created for cloned repositories.
- is_bare()[source]¶
Checks if this is a bare repository.
A bare repository is one without a working tree, typically used as a central repository.
- Returns:
True if this is a bare repository, False otherwise
- Return type:
- has_coverage()[source]¶
Checks if a parseable .coverage file exists in the repository.
Attempts to find and parse a .coverage file in the repository root directory. The file must be in a valid format that can be parsed as JSON.
- Returns:
True if a valid .coverage file exists, False otherwise
- Return type:
- coverage()[source]¶
Analyzes test coverage information from the repository.
Attempts to read and parse the .coverage file in the repository root using the coverage.py API. Returns coverage statistics for each file.
- Returns:
- A DataFrame with columns:
filename (str): Path to the file
lines_covered (int): Number of lines covered by tests
total_lines (int): Total number of lines
coverage (float): Coverage percentage
repository (str): Repository name
Additional columns for any labels specified in labels_to_add
- Return type:
Note
Returns an empty DataFrame if no coverage data exists or can’t be read.
- Raises:
ImportError – If the optional
coveragepackage is not installed but the repository does have a.coveragefile to parse.
- hours_estimate(branch=None, grouping_window=0.5, single_commit_hours=0.5, limit=None, days=None, committer=True, ignore_globs=None, include_globs=None)[source]¶
inspired by: https://github.com/kimmobrunfeldt/git-hours/blob/8aaeee237cb9d9028e7a2592a25ad8468b1f45e4/index.js#L114-L143
Iterates through the commit history of repo to estimate the time commitement of each author or committer over the course of time indicated by limit/extensions/days/etc.
- Parameters:
branch – (optional, default=None) the branch to return commits for, defaults to default_branch if None
limit – (optional, default=None) a maximum number of commits to return, None for no limit
grouping_window – (optional, default=0.5 hours) the threhold for how close two commits need to be to consider them part of one coding session
single_commit_hours – (optional, default 0.5 hours) the time range to associate with one single commit
days – (optional, default=None) number of days to return, if limit is None
committer – (optional, default=True) whether to use committer vs. author
ignore_globs – (optional, default=None) a list of globs to ignore, default none excludes nothing
include_globs – (optinal, default=None) a list of globs to include, default of None includes everything.
- Returns:
DataFrame
- commit_history(branch=None, limit=None, days=None, ignore_globs=None, include_globs=None)[source]¶
Returns a DataFrame containing the commit history for a branch.
Retrieves the commit history for the specified branch, with options to limit the number of commits or time range, and filter which files to include.
- Parameters:
branch (Optional[str]) – Branch to analyze. Defaults to default_branch if None.
limit (Optional[int]) – Maximum number of commits to return
days (Optional[int]) – If provided, only return commits from the last N days
ignore_globs (Optional[List[str]]) – List of glob patterns for files to ignore
include_globs (Optional[List[str]]) – List of glob patterns for files to include
- Returns:
- A DataFrame with columns:
date (datetime, index): Timestamp of the commit
author (str): Name of the commit author
committer (str): Name of the committer
message (str): Commit message
commit_sha (str): Commit hash
lines (int): Total lines changed
insertions (int): Lines added
deletions (int): Lines removed
net (int): Net lines changed (insertions - deletions)
repository (str): Repository name
- Return type:
DataFrame
Note
If both ignore_globs and include_globs are provided, files must match an include pattern and not match any ignore patterns to be included.
- file_change_history(branch=None, limit=None, days=None, ignore_globs=None, include_globs=None, skip_broken=True)[source]¶
Returns data on commit history of files.
For each file changed in each commit within the given parameters, returns information about insertions, deletions, and commit metadata.
- Parameters:
branch (Optional[str]) – Branch to analyze. Defaults to default_branch if None.
limit (Optional[int]) – Maximum number of commits to return, None for no limit
days (Optional[int]) – Number of days to return if limit is None
ignore_globs (Optional[List[str]]) – List of glob patterns for files to ignore
include_globs (Optional[List[str]]) – List of glob patterns for files to include
skip_broken (bool, optional) – Whether to skip corrupted Git objects. Defaults to True.
- Returns:
- A DataFrame indexed by commit timestamp containing file change data.
Columns include: - filename (str): Path to the file - insertions (int): Number of lines inserted - deletions (int): Number of lines deleted - lines (int): Current line count (insertions - deletions) - message (str): Commit message - committer (str): Name of the committer - author (str): Name of the author - repository (str): Repository name Additional columns for any labels specified in labels_to_add
- Return type:
Note
Files matching both include_globs and ignore_globs patterns will be excluded.
- _process_commit_for_file_history(commit, history, ignore_globs, include_globs, skip_broken)[source]¶
Helper method to process a commit for file change history.
- Parameters:
commit – The commit object to process
history – List to append the file change data to
ignore_globs – List of glob patterns for files to ignore
include_globs – List of glob patterns for files to include
skip_broken – Whether to skip errors for specific files
- file_change_rates(branch=None, limit=None, coverage=False, days=None, ignore_globs=None, include_globs=None, skip_broken=True)[source]¶
Returns a DataFrame with file change rates, calculated as the number of changes between the first commit for that file and the last. If coverage is true, it will also calculate test coverage statistics for python source files.
- Parameters:
branch (Optional[str]) – Which branch to analyze. If None, uses default_branch.
limit (Optional[int]) – How many commits to go back in history. None for all.
coverage (bool) – Whether to calculate test coverage stats. Defaults to False.
days (Optional[int]) – If not None, only consider changes in the last x days.
ignore_globs (Optional[List[str]]) – List of glob patterns for files to ignore
include_globs (Optional[List[str]]) – List of glob patterns for files to include
skip_broken (bool, optional) – Whether to skip corrupted Git objects. Defaults to True.
- Returns:
- A DataFrame with columns:
file (str): Path to the file
unique_committers (int): Number of unique committers
abs_rate_of_change (float): Absolute rate of change
net_rate_of_change (float): Net rate of change
net_change (int): Net lines changed
abs_change (int): Absolute lines changed
edit_rate (float): Edit rate
lines (int): Current line count
repository (str): Repository name
Additional columns for any labels specified in labels_to_add
- Return type:
- blame(rev='HEAD', committer=True, by='repository', ignore_globs=None, include_globs=None)[source]¶
Analyzes blame information for files in the repository.
Retrieves blame information from a specific revision and aggregates it based on the specified grouping. Can group results by committer/author and either repository or file.
- Parameters:
rev (str, optional) – Revision to analyze. Defaults to ‘HEAD’.
committer (bool, optional) – If True, group by committer name. If False, group by author name. Defaults to True.
by (str, optional) – How to group the results. One of: - ‘repository’: Group by repository (default) - ‘file’: Group by individual file
ignore_globs (Optional[List[str]]) – List of glob patterns for files to ignore
include_globs (Optional[List[str]]) – List of glob patterns for files to include
- Returns:
- A DataFrame with columns depending on the ‘by’ parameter:
- If by=’repository’:
committer/author (str): Name of the committer/author
loc (int): Lines of code attributed to that person
- If by=’file’:
committer/author (str): Name of the committer/author
file (str): File path
loc (int): Lines of code attributed to that person in that file
- Return type:
Note
Results are sorted by lines of code in descending order. If both ignore_globs and include_globs are provided, files must match an include pattern and not match any ignore patterns to be included.
- revs(branch=None, limit=None, skip=None, num_datapoints=None, skip_broken=False)[source]¶
Returns a dataframe of all revision tags and their timestamps. It will have the columns:
date
rev
- Parameters:
branch (Optional[str]) – Branch to analyze. Defaults to default_branch if None.
limit (Optional[int]) – Maximum number of revisions to return, None for no limit
skip (Optional[int]) – Number of revisions to skip. Ex: skip=2 returns every other revision, None for no skipping.
num_datapoints (Optional[int]) – If limit and skip are none, and this isn’t, then num_datapoints evenly spaced revs will be used
skip_broken (bool) – Whether to skip corrupted commit objects. Defaults to False.
- Returns:
DataFrame with revision information
- Return type:
DataFrame
- cumulative_blame(branch=None, limit=None, skip=None, num_datapoints=None, committer=True, ignore_globs=None, include_globs=None, skip_broken=True)[source]¶
Returns the blame at every revision of interest. Index is a datetime, column per committer, with number of lines blamed to each committer at each timestamp as data.
- Parameters:
branch (Optional[str]) – Branch to analyze. Defaults to default_branch if None.
limit (Optional[int]) – Maximum number of revisions to return, None for no limit
skip (Optional[int]) – Number of revisions to skip. Ex: skip=2 returns every other revision, None for no skipping.
num_datapoints (Optional[int]) – If limit and skip are none, and this isn’t, then num_datapoints evenly spaced revs will be used
committer (bool, optional) – True if committer should be reported, false if author
ignore_globs (Optional[List[str]]) – List of glob patterns for files to ignore
include_globs (Optional[List[str]]) – List of glob patterns for files to include
skip_broken (bool, optional) – Whether to skip corrupted Git objects. Defaults to True.
- Returns:
- A DataFrame indexed by an ascending (monotonically increasing)
DatetimeIndex named
date, with one integer column per contributor holding the lines blamed to them at that revision. Label columns (repositoryand anylabels_to_addentries) are not included, so the frame is entirely numeric anddf.sum(axis=1)gives total LOC.
- Return type:
DataFrame
Note
If both ignore_globs and include_globs are provided, files must match an include pattern and not match any ignore patterns to be included.
- parallel_cumulative_blame(branch=None, limit=None, skip=None, num_datapoints=None, committer=True, workers=1, ignore_globs=None, include_globs=None, skip_broken=True)[source]¶
Returns the blame at every revision of interest. Index is a datetime, column per committer, with number of lines blamed to each committer at each timestamp as data.
- Parameters:
branch (Optional[str]) – Branch to analyze. Defaults to default_branch if None.
limit (Optional[int]) – Maximum number of revisions to return, None for no limit
skip (Optional[int]) – Number of revisions to skip. Ex: skip=2 returns every other revision, None for no skipping.
num_datapoints (Optional[int]) – If limit and skip are none, and this isn’t, then num_datapoints evenly spaced revs will be used
committer (bool, optional) – True if committer should be reported, false if author
ignore_globs (Optional[List[str]]) – List of glob patterns for files to ignore
include_globs (Optional[List[str]]) – List of glob patterns for files to include
workers (Optional[int]) – Number of workers to use in the threadpool, -1 for one per core.
skip_broken (bool, optional) – Whether to skip corrupted Git objects. Defaults to True.
- Returns:
- A DataFrame indexed by an ascending (monotonically increasing)
DatetimeIndex named
date, with one column per contributor holding the lines blamed to them at that revision. Label columns (repositoryand anylabels_to_addentries) are not included, so the frame is entirely numeric anddf.sum(axis=1)gives total LOC.
- Return type:
DataFrame
- branches()[source]¶
Returns information about all branches in the repository.
Retrieves a list of all branches (both local and remote) from the repository.
- Returns:
- A DataFrame with columns:
repository (str): Repository name
branch (str): Name of the branch
local (bool): Whether the branch is local
Additional columns for any labels specified in labels_to_add
- Return type:
- get_branches_by_commit(commit)[source]¶
Finds all branches containing a specific commit.
- Parameters:
commit (str) – Commit hash to look up
- Returns:
- A DataFrame with columns:
branch (str): Name of each branch containing the commit
commit (str): The commit hash that was looked up
repository (str): Repository name
Additional columns for any labels specified in labels_to_add
- Return type:
- commits_in_tags(start=None, end=None)[source]¶
Analyzes commits associated with each tag.
For each tag, traces backwards through the commit history until hitting another tag, reaching the time limit, or hitting the root commit. This helps understand what changes went into each tagged version.
- Parameters:
start (Union[np.timedelta64, pd.Timestamp], optional) – Start time for analysis. If a timedelta, calculated relative to now. Defaults to 6 months ago.
end (Optional[pd.Timestamp]) – End time for analysis. Defaults to None.
- Returns:
- A DataFrame indexed by (tag_date, commit_date) with columns:
commit_sha (str): SHA of the commit
tag (str): Name of the tag this commit belongs to
repository (str): Repository name
Additional columns for any labels specified in labels_to_add
- Return type:
Note
This is useful for generating changelogs or understanding the scope of changes between tagged releases.
- tags(skip_broken=False)[source]¶
Returns information about all tags in the repository.
Retrieves detailed information about all tags, including both lightweight and annotated tags.
- Parameters:
skip_broken (bool) – Whether to skip corrupted tag objects. Defaults to False.
- Returns:
- A DataFrame indexed by (tag_date, commit_date) with columns:
tag (str): Name of the tag
annotated (bool): Whether it’s an annotated tag
annotation (str): Tag message (empty for lightweight tags)
tag_sha (Optional[str]): SHA of tag object (None for lightweight tags)
commit_sha (str): SHA of the commit being tagged
repository (str): Repository name
Additional columns for any labels specified in labels_to_add
- Return type:
Note
tag_date is the tag creation time for annotated tags, commit time for lightweight
commit_date is always the timestamp of the tagged commit
Both dates are timezone-aware UTC timestamps
- property repo_name¶
- _repo_name()[source]¶
Returns the name of the repository.
For local repositories, uses the name of the directory containing the .git folder. For remote repositories, extracts the name from the URL.
- Returns:
Name of the repository, or ‘unknown_repo’ if name can’t be determined
- Return type:
Note
This is an internal method primarily used to provide consistent repository names in DataFrame outputs.
- _add_labels_to_df(df)[source]¶
Adds configured labels to a DataFrame.
Adds the repository name and any additional configured labels to the DataFrame. This ensures consistent labeling across all DataFrame outputs.
- Parameters:
df (pandas.DataFrame) – DataFrame to add labels to
- Returns:
- The input DataFrame with additional label columns:
repository (str): Repository name
label0..labelN: Values from labels_to_add
- Return type:
Note
This is an internal helper method used by all public methods that return DataFrames.
- _label_columns()[source]¶
Returns the column names that
_add_labels_to_df()attaches.- Returns:
repositoryfollowed by onelabelNper configured label.- Return type:
List[str]
- __str__()[source]¶
Returns a human-readable string representation of the repository.
- Returns:
String in format ‘git repository: {name} at: {path}’
- Return type:
- get_commit_content(rev, ignore_globs=None, include_globs=None)[source]¶
Gets detailed content changes for a specific commit.
For each file changed in the commit, returns the actual content changes including added and removed lines.
- Parameters:
- Returns:
- A DataFrame with columns:
file (str): Path of the changed file
change_type (str): Type of change (A=added, M=modified, D=deleted)
old_line_num (int): Line number in the old version (None for added lines)
new_line_num (int): Line number in the new version (None for deleted lines)
content (str): The actual line content
repository (str): Repository name
Additional columns for any labels specified in labels_to_add
- Return type:
Note
For binary files, only the change_type is recorded, with no line-by-line changes. If both ignore_globs and include_globs are provided, files must match an include pattern and not match any ignore patterns to be included.
- get_file_content(path, rev='HEAD')[source]¶
Gets the content of a file from the repository at a specific revision.
Safely retrieves file content by first verifying the file exists in git’s tree (respecting .gitignore) before attempting to read it.
- Parameters:
- Returns:
- Content of the file if it exists and is tracked by git,
None if file doesn’t exist or isn’t tracked.
- Return type:
Optional[str]
Note
This only works for files that are tracked by git. Untracked files and files matched by .gitignore patterns cannot be read.
- list_files(rev='HEAD')[source]¶
Lists all files in the repository at a specific revision, respecting .gitignore.
Uses git ls-tree to get a list of all tracked files in the repository, which automatically respects .gitignore rules since untracked and ignored files are not in git’s tree.
- Parameters:
rev (str, optional) – Revision to list files from. Defaults to ‘HEAD’.
- Returns:
- A DataFrame with columns:
file (str): Full path to the file relative to repository root
mode (str): File mode (100644 for regular file, 100755 for executable, etc)
type (str): Object type (blob for file, tree for directory)
sha (str): SHA-1 hash of the file content
repository (str): Repository name
Additional columns for any labels specified in labels_to_add
- Return type:
Note
This only includes files that are tracked by git. Untracked files and files matched by .gitignore patterns are not included.
- __repr__()[source]¶
Returns a unique string representation of the repository.
- Returns:
The absolute path to the repository
- Return type:
- bus_factor(by='repository', ignore_globs=None, include_globs=None)[source]¶
Calculates the “bus factor” for the repository.
The bus factor is a measure of risk based on how concentrated the codebase knowledge is among contributors. It is calculated as the minimum number of contributors whose combined contributions account for at least 50% of the codebase’s lines of code.
- Parameters:
by (str, optional) – How to calculate the bus factor. One of: - ‘repository’: Calculate for entire repository (default) - ‘file’: Calculate for each individual file
ignore_globs (Optional[List[str]]) – List of glob patterns for files to ignore
include_globs (Optional[List[str]]) – List of glob patterns for files to include
- Returns:
- A DataFrame with columns depending on the ‘by’ parameter:
- If by=’repository’:
repository (str): Repository name
bus factor (int): Bus factor for the repository
- If by=’file’:
file (str): File path
bus factor (int): Bus factor for that file
repository (str): Repository name
- Return type:
Note
A low bus factor (e.g. 1-2) indicates high risk as knowledge is concentrated among few contributors. A higher bus factor indicates knowledge is better distributed.
- file_owner(rev, filename, committer=True)[source]¶
Determines the primary owner of a file at a specific revision.
The owner is determined by who has contributed the most lines of code to the file according to git blame.
- Parameters:
- Returns:
- Dictionary containing owner information with keys:
name (str): Name of the primary owner
Returns None if file doesn’t exist or can’t be analyzed
- Return type:
Optional[dict]
Note
This is a helper method used by file_detail() to determine file ownership.
- _get_last_edit_date(file_path, rev='HEAD')[source]¶
Get the last edit date for a file at a given revision.
- punchcard(branch=None, limit=None, days=None, by=None, normalize=None, ignore_globs=None, include_globs=None)[source]¶
Returns a pandas DataFrame containing all of the data for a punchcard.
day_of_week
hour_of_day
author / committer
lines
insertions
deletions
net
- Parameters:
branch (Optional[str]) – Branch to analyze. Defaults to default_branch if None.
limit (Optional[int]) – Maximum number of commits to return, None for no limit
days (Optional[int]) – Number of days to return if limit is None
by (Optional[str]) – Agg by options, None for no aggregation (just a high level punchcard), or ‘committer’, ‘author’
normalize (Optional[int]) – If an integer, returns the data normalized to max value of that (for plotting)
ignore_globs (Optional[List[str]]) – List of glob patterns for files to ignore
include_globs (Optional[List[str]]) – List of glob patterns for files to include
- Returns:
DataFrame with punchcard data
- Return type:
DataFrame
- has_branch(branch)[source]¶
Checks if a branch exists in the repository.
- Parameters:
branch (str) – Name of the branch to check
- Returns:
True if the branch exists, False otherwise
- Return type:
Note
This checks both local and remote branches.
- file_detail(include_globs=None, ignore_globs=None, rev='HEAD', committer=True)[source]¶
Provides detailed information about all files in the repository.
Analyzes each file at the specified revision, gathering information about size, ownership, and last modification.
- Parameters:
include_globs (Optional[List[str]]) – List of glob patterns for files to include
ignore_globs (Optional[List[str]]) – List of glob patterns for files to ignore
rev (str, optional) – Revision to analyze. Defaults to ‘HEAD’.
committer (bool, optional) – If True, use committer info. If False, use author. Defaults to True.
- Returns:
- A DataFrame with columns:
file (str): Path to the file
file_owner (str): Name of primary committer/author
last_edit_date (datetime): When file was last modified
loc (int): Lines of code in file
ext (str): File extension
repository (str): Repository name
Additional columns for any labels specified in labels_to_add
- Return type:
Note
The primary file owner is the person responsible for the most lines in the current version of the file.
This method is cached if a cache_backend was provided and rev is not HEAD.
- time_between_revs(rev1, rev2)[source]¶
Calculates the time difference in days between two revisions.
- Parameters:
- Returns:
The absolute time difference in days between the two revisions.
- Return type:
Note
The result is always non-negative (absolute value).
- diff_stats_between_revs(rev1, rev2, ignore_globs=None, include_globs=None)[source]¶
Computes diff statistics between two revisions.
Calculates the total insertions, deletions, net line change, and number of files changed between two arbitrary revisions (commits or tags). Optionally filters files using glob patterns.
- Parameters:
- Returns:
- A dictionary with keys:
’insertions’ (int): Total lines inserted.
’deletions’ (int): Total lines deleted.
’net’ (int): Net lines changed (insertions - deletions).
’files_changed’ (int): Number of files changed.
’files’ (List[str]): List of changed file paths.
- Return type:
Note
Binary files or files that cannot be parsed are skipped. If both ignore_globs and include_globs are provided, files must match an include pattern and not match any ignore patterns to be included.
- committers_between_revs(rev1, rev2, ignore_globs=None, include_globs=None)[source]¶
Finds unique committers and authors between two revisions.
Iterates through all commits between two revisions (exclusive of rev1, inclusive of rev2) and returns the unique committers and authors who contributed, filtered by file globs if provided.
- Parameters:
- Returns:
- A dictionary with keys:
’committers’ (List[str]): Sorted list of unique committer names.
’authors’ (List[str]): Sorted list of unique author names.
- Return type:
Note
Only commits that touch files matching the glob filters are considered. The range is interpreted as Git does: rev1..rev2 means commits reachable from rev2 but not rev1.
- files_changed_between_revs(rev1, rev2, ignore_globs=None, include_globs=None)[source]¶
Lists files changed between two revisions.
Returns a sorted list of all files changed between two arbitrary revisions (commits or tags), optionally filtered by glob patterns.
- Parameters:
- Returns:
Sorted list of file paths changed between the two revisions.
- Return type:
List[str]
Note
If both ignore_globs and include_globs are provided, files must match an include pattern and not match any ignore patterns to be included.
- release_tag_summary(tag_glob=None, ignore_globs=None, include_globs=None)[source]¶
Summarizes repository activity between release tags.
For each tag (filtered by glob), computes the time since the previous tag, diff statistics, committers/authors involved, and files changed between tags. Returns a DataFrame with one row per tag and columns for all computed metrics.
- Parameters:
tag_glob (Optional[Union[str, List[str]]]) – Glob pattern(s) to filter tags (e.g., ‘v*’ or [‘v*’, ‘release-*’]). If None, all tags are included.
ignore_globs (Optional[List[str]]) – List of glob patterns for files to ignore in diff/commit analysis.
include_globs (Optional[List[str]]) – List of glob patterns for files to include in diff/commit analysis.
- Returns:
- DataFrame with columns:
tag (str): Tag name
tag_date (datetime): Tag creation date
commit_sha (str): SHA of the tagged commit
time_since_prev (float): Days since previous tag
insertions (int): Lines inserted since previous tag
deletions (int): Lines deleted since previous tag
net (int): Net lines changed since previous tag
files_changed (int): Number of files changed since previous tag
committers (List[str]): Committers between previous and current tag
authors (List[str]): Authors between previous and current tag
files (List[str]): Files changed between previous and current tag
- Return type:
Note
The first tag in the sorted list will have NaN for time_since_prev and empty diff/commit info. Tag filtering uses fnmatch and supports multiple globs.
- safe_fetch_remote(remote_name='origin', prune=False, dry_run=False)[source]¶
Safely fetch changes from remote repository.
Fetches the latest changes from a remote repository without modifying the working directory. This is a read-only operation that only updates remote-tracking branches.
- Parameters:
- Returns:
- Fetch results with keys:
success (bool): Whether the fetch was successful
message (str): Status message or error description
remote_exists (bool): Whether the specified remote exists
changes_available (bool): Whether new changes were fetched
error (Optional[str]): Error message if fetch failed
- Return type:
Note
This method is safe as it only fetches remote changes and never modifies the working directory or current branch. It will not perform any merges, rebases, or checkouts.
- warm_cache(methods=None, **kwargs)[source]¶
Pre-populate cache with commonly used data.
Executes a set of commonly used repository analysis methods to populate the cache, improving performance for subsequent calls. Only methods that support caching will be executed.
- Parameters:
methods (Optional[List[str]]) – List of method names to pre-warm. If None, uses a default set of commonly used methods. Available methods: - ‘commit_history’: Load commit history - ‘branches’: Load branch information - ‘tags’: Load tag information - ‘blame’: Load blame information - ‘file_detail’: Load file details - ‘list_files’: Load file listing - ‘file_change_rates’: Load file change statistics
**kwargs – Additional keyword arguments to pass to compatible methods unchanged. Common arguments include: - branch: Branch to analyze (default: repository’s default branch) - limit: Limit number of commits to analyze - ignore_globs: List of glob patterns to ignore - include_globs: List of glob patterns to include
- Returns:
- Results of cache warming operations with keys:
success (bool): Whether cache warming was successful
methods_executed (List[str]): List of methods that were executed
methods_failed (List[str]): List of methods that failed
cache_entries_created (int): Number of cache entries created
execution_time (float): Total execution time in seconds
errors (List[str]): List of error messages for failed methods
- Return type:
Note
This method will only execute methods if a cache backend is configured. If no cache backend is available, it will return immediately with a success status but no methods executed.
- invalidate_cache(keys=None, pattern=None)[source]¶
Invalidate specific cache entries or all cache entries for this repository.
- Parameters:
- Returns:
Number of cache entries invalidated
- Return type:
Note
If both keys and pattern are None, all cache entries for this repository are invalidated. Cache keys are automatically prefixed with repository name.
- class gitpandas.repository.GitFlowRepository[source]¶
Bases:
RepositoryA special case where git flow is followed, so we know something about the branching scheme
- __del__()¶
Cleanup method called when the object is destroyed.
Cleans up any temporary directories created for cloned repositories.
- __repr__()¶
Returns a unique string representation of the repository.
- Returns:
The absolute path to the repository
- Return type:
- __str__()¶
Returns a human-readable string representation of the repository.
- Returns:
String in format ‘git repository: {name} at: {path}’
- Return type:
- _add_labels_to_df(df)¶
Adds configured labels to a DataFrame.
Adds the repository name and any additional configured labels to the DataFrame. This ensures consistent labeling across all DataFrame outputs.
- Parameters:
df (pandas.DataFrame) – DataFrame to add labels to
- Returns:
- The input DataFrame with additional label columns:
repository (str): Repository name
label0..labelN: Values from labels_to_add
- Return type:
Note
This is an internal helper method used by all public methods that return DataFrames.
- _get_last_edit_date(file_path, rev='HEAD')¶
Get the last edit date for a file at a given revision.
- _label_columns()¶
Returns the column names that
_add_labels_to_df()attaches.- Returns:
repositoryfollowed by onelabelNper configured label.- Return type:
List[str]
- _process_commit_for_file_history(commit, history, ignore_globs, include_globs, skip_broken)¶
Helper method to process a commit for file change history.
- Parameters:
commit – The commit object to process
history – List to append the file change data to
ignore_globs – List of glob patterns for files to ignore
include_globs – List of glob patterns for files to include
skip_broken – Whether to skip errors for specific files
- _repo_name()¶
Returns the name of the repository.
For local repositories, uses the name of the directory containing the .git folder. For remote repositories, extracts the name from the URL.
- Returns:
Name of the repository, or ‘unknown_repo’ if name can’t be determined
- Return type:
Note
This is an internal method primarily used to provide consistent repository names in DataFrame outputs.
- blame(rev='HEAD', committer=True, by='repository', ignore_globs=None, include_globs=None)¶
Analyzes blame information for files in the repository.
Retrieves blame information from a specific revision and aggregates it based on the specified grouping. Can group results by committer/author and either repository or file.
- Parameters:
rev (str, optional) – Revision to analyze. Defaults to ‘HEAD’.
committer (bool, optional) – If True, group by committer name. If False, group by author name. Defaults to True.
by (str, optional) – How to group the results. One of: - ‘repository’: Group by repository (default) - ‘file’: Group by individual file
ignore_globs (Optional[List[str]]) – List of glob patterns for files to ignore
include_globs (Optional[List[str]]) – List of glob patterns for files to include
- Returns:
- A DataFrame with columns depending on the ‘by’ parameter:
- If by=’repository’:
committer/author (str): Name of the committer/author
loc (int): Lines of code attributed to that person
- If by=’file’:
committer/author (str): Name of the committer/author
file (str): File path
loc (int): Lines of code attributed to that person in that file
- Return type:
Note
Results are sorted by lines of code in descending order. If both ignore_globs and include_globs are provided, files must match an include pattern and not match any ignore patterns to be included.
- branches()¶
Returns information about all branches in the repository.
Retrieves a list of all branches (both local and remote) from the repository.
- Returns:
- A DataFrame with columns:
repository (str): Repository name
branch (str): Name of the branch
local (bool): Whether the branch is local
Additional columns for any labels specified in labels_to_add
- Return type:
- bus_factor(by='repository', ignore_globs=None, include_globs=None)¶
Calculates the “bus factor” for the repository.
The bus factor is a measure of risk based on how concentrated the codebase knowledge is among contributors. It is calculated as the minimum number of contributors whose combined contributions account for at least 50% of the codebase’s lines of code.
- Parameters:
by (str, optional) – How to calculate the bus factor. One of: - ‘repository’: Calculate for entire repository (default) - ‘file’: Calculate for each individual file
ignore_globs (Optional[List[str]]) – List of glob patterns for files to ignore
include_globs (Optional[List[str]]) – List of glob patterns for files to include
- Returns:
- A DataFrame with columns depending on the ‘by’ parameter:
- If by=’repository’:
repository (str): Repository name
bus factor (int): Bus factor for the repository
- If by=’file’:
file (str): File path
bus factor (int): Bus factor for that file
repository (str): Repository name
- Return type:
Note
A low bus factor (e.g. 1-2) indicates high risk as knowledge is concentrated among few contributors. A higher bus factor indicates knowledge is better distributed.
- commit_history(branch=None, limit=None, days=None, ignore_globs=None, include_globs=None)¶
Returns a DataFrame containing the commit history for a branch.
Retrieves the commit history for the specified branch, with options to limit the number of commits or time range, and filter which files to include.
- Parameters:
branch (Optional[str]) – Branch to analyze. Defaults to default_branch if None.
limit (Optional[int]) – Maximum number of commits to return
days (Optional[int]) – If provided, only return commits from the last N days
ignore_globs (Optional[List[str]]) – List of glob patterns for files to ignore
include_globs (Optional[List[str]]) – List of glob patterns for files to include
- Returns:
- A DataFrame with columns:
date (datetime, index): Timestamp of the commit
author (str): Name of the commit author
committer (str): Name of the committer
message (str): Commit message
commit_sha (str): Commit hash
lines (int): Total lines changed
insertions (int): Lines added
deletions (int): Lines removed
net (int): Net lines changed (insertions - deletions)
repository (str): Repository name
- Return type:
DataFrame
Note
If both ignore_globs and include_globs are provided, files must match an include pattern and not match any ignore patterns to be included.
- commits_in_tags(start=None, end=None)¶
Analyzes commits associated with each tag.
For each tag, traces backwards through the commit history until hitting another tag, reaching the time limit, or hitting the root commit. This helps understand what changes went into each tagged version.
- Parameters:
start (Union[np.timedelta64, pd.Timestamp], optional) – Start time for analysis. If a timedelta, calculated relative to now. Defaults to 6 months ago.
end (Optional[pd.Timestamp]) – End time for analysis. Defaults to None.
- Returns:
- A DataFrame indexed by (tag_date, commit_date) with columns:
commit_sha (str): SHA of the commit
tag (str): Name of the tag this commit belongs to
repository (str): Repository name
Additional columns for any labels specified in labels_to_add
- Return type:
Note
This is useful for generating changelogs or understanding the scope of changes between tagged releases.
- committers_between_revs(rev1, rev2, ignore_globs=None, include_globs=None)¶
Finds unique committers and authors between two revisions.
Iterates through all commits between two revisions (exclusive of rev1, inclusive of rev2) and returns the unique committers and authors who contributed, filtered by file globs if provided.
- Parameters:
- Returns:
- A dictionary with keys:
’committers’ (List[str]): Sorted list of unique committer names.
’authors’ (List[str]): Sorted list of unique author names.
- Return type:
Note
Only commits that touch files matching the glob filters are considered. The range is interpreted as Git does: rev1..rev2 means commits reachable from rev2 but not rev1.
- coverage()¶
Analyzes test coverage information from the repository.
Attempts to read and parse the .coverage file in the repository root using the coverage.py API. Returns coverage statistics for each file.
- Returns:
- A DataFrame with columns:
filename (str): Path to the file
lines_covered (int): Number of lines covered by tests
total_lines (int): Total number of lines
coverage (float): Coverage percentage
repository (str): Repository name
Additional columns for any labels specified in labels_to_add
- Return type:
Note
Returns an empty DataFrame if no coverage data exists or can’t be read.
- Raises:
ImportError – If the optional
coveragepackage is not installed but the repository does have a.coveragefile to parse.
- cumulative_blame(branch=None, limit=None, skip=None, num_datapoints=None, committer=True, ignore_globs=None, include_globs=None, skip_broken=True)¶
Returns the blame at every revision of interest. Index is a datetime, column per committer, with number of lines blamed to each committer at each timestamp as data.
- Parameters:
branch (Optional[str]) – Branch to analyze. Defaults to default_branch if None.
limit (Optional[int]) – Maximum number of revisions to return, None for no limit
skip (Optional[int]) – Number of revisions to skip. Ex: skip=2 returns every other revision, None for no skipping.
num_datapoints (Optional[int]) – If limit and skip are none, and this isn’t, then num_datapoints evenly spaced revs will be used
committer (bool, optional) – True if committer should be reported, false if author
ignore_globs (Optional[List[str]]) – List of glob patterns for files to ignore
include_globs (Optional[List[str]]) – List of glob patterns for files to include
skip_broken (bool, optional) – Whether to skip corrupted Git objects. Defaults to True.
- Returns:
- A DataFrame indexed by an ascending (monotonically increasing)
DatetimeIndex named
date, with one integer column per contributor holding the lines blamed to them at that revision. Label columns (repositoryand anylabels_to_addentries) are not included, so the frame is entirely numeric anddf.sum(axis=1)gives total LOC.
- Return type:
DataFrame
Note
If both ignore_globs and include_globs are provided, files must match an include pattern and not match any ignore patterns to be included.
- diff_stats_between_revs(rev1, rev2, ignore_globs=None, include_globs=None)¶
Computes diff statistics between two revisions.
Calculates the total insertions, deletions, net line change, and number of files changed between two arbitrary revisions (commits or tags). Optionally filters files using glob patterns.
- Parameters:
- Returns:
- A dictionary with keys:
’insertions’ (int): Total lines inserted.
’deletions’ (int): Total lines deleted.
’net’ (int): Net lines changed (insertions - deletions).
’files_changed’ (int): Number of files changed.
’files’ (List[str]): List of changed file paths.
- Return type:
Note
Binary files or files that cannot be parsed are skipped. If both ignore_globs and include_globs are provided, files must match an include pattern and not match any ignore patterns to be included.
- file_change_history(branch=None, limit=None, days=None, ignore_globs=None, include_globs=None, skip_broken=True)¶
Returns data on commit history of files.
For each file changed in each commit within the given parameters, returns information about insertions, deletions, and commit metadata.
- Parameters:
branch (Optional[str]) – Branch to analyze. Defaults to default_branch if None.
limit (Optional[int]) – Maximum number of commits to return, None for no limit
days (Optional[int]) – Number of days to return if limit is None
ignore_globs (Optional[List[str]]) – List of glob patterns for files to ignore
include_globs (Optional[List[str]]) – List of glob patterns for files to include
skip_broken (bool, optional) – Whether to skip corrupted Git objects. Defaults to True.
- Returns:
- A DataFrame indexed by commit timestamp containing file change data.
Columns include: - filename (str): Path to the file - insertions (int): Number of lines inserted - deletions (int): Number of lines deleted - lines (int): Current line count (insertions - deletions) - message (str): Commit message - committer (str): Name of the committer - author (str): Name of the author - repository (str): Repository name Additional columns for any labels specified in labels_to_add
- Return type:
Note
Files matching both include_globs and ignore_globs patterns will be excluded.
- file_change_rates(branch=None, limit=None, coverage=False, days=None, ignore_globs=None, include_globs=None, skip_broken=True)¶
Returns a DataFrame with file change rates, calculated as the number of changes between the first commit for that file and the last. If coverage is true, it will also calculate test coverage statistics for python source files.
- Parameters:
branch (Optional[str]) – Which branch to analyze. If None, uses default_branch.
limit (Optional[int]) – How many commits to go back in history. None for all.
coverage (bool) – Whether to calculate test coverage stats. Defaults to False.
days (Optional[int]) – If not None, only consider changes in the last x days.
ignore_globs (Optional[List[str]]) – List of glob patterns for files to ignore
include_globs (Optional[List[str]]) – List of glob patterns for files to include
skip_broken (bool, optional) – Whether to skip corrupted Git objects. Defaults to True.
- Returns:
- A DataFrame with columns:
file (str): Path to the file
unique_committers (int): Number of unique committers
abs_rate_of_change (float): Absolute rate of change
net_rate_of_change (float): Net rate of change
net_change (int): Net lines changed
abs_change (int): Absolute lines changed
edit_rate (float): Edit rate
lines (int): Current line count
repository (str): Repository name
Additional columns for any labels specified in labels_to_add
- Return type:
- file_detail(include_globs=None, ignore_globs=None, rev='HEAD', committer=True)¶
Provides detailed information about all files in the repository.
Analyzes each file at the specified revision, gathering information about size, ownership, and last modification.
- Parameters:
include_globs (Optional[List[str]]) – List of glob patterns for files to include
ignore_globs (Optional[List[str]]) – List of glob patterns for files to ignore
rev (str, optional) – Revision to analyze. Defaults to ‘HEAD’.
committer (bool, optional) – If True, use committer info. If False, use author. Defaults to True.
- Returns:
- A DataFrame with columns:
file (str): Path to the file
file_owner (str): Name of primary committer/author
last_edit_date (datetime): When file was last modified
loc (int): Lines of code in file
ext (str): File extension
repository (str): Repository name
Additional columns for any labels specified in labels_to_add
- Return type:
Note
The primary file owner is the person responsible for the most lines in the current version of the file.
This method is cached if a cache_backend was provided and rev is not HEAD.
- file_owner(rev, filename, committer=True)¶
Determines the primary owner of a file at a specific revision.
The owner is determined by who has contributed the most lines of code to the file according to git blame.
- Parameters:
- Returns:
- Dictionary containing owner information with keys:
name (str): Name of the primary owner
Returns None if file doesn’t exist or can’t be analyzed
- Return type:
Optional[dict]
Note
This is a helper method used by file_detail() to determine file ownership.
- files_changed_between_revs(rev1, rev2, ignore_globs=None, include_globs=None)¶
Lists files changed between two revisions.
Returns a sorted list of all files changed between two arbitrary revisions (commits or tags), optionally filtered by glob patterns.
- Parameters:
- Returns:
Sorted list of file paths changed between the two revisions.
- Return type:
List[str]
Note
If both ignore_globs and include_globs are provided, files must match an include pattern and not match any ignore patterns to be included.
- get_branches_by_commit(commit)¶
Finds all branches containing a specific commit.
- Parameters:
commit (str) – Commit hash to look up
- Returns:
- A DataFrame with columns:
branch (str): Name of each branch containing the commit
commit (str): The commit hash that was looked up
repository (str): Repository name
Additional columns for any labels specified in labels_to_add
- Return type:
- get_cache_stats()¶
Get cache statistics for this repository.
- Returns:
Cache statistics including repository-specific and global cache information
- Return type:
- get_commit_content(rev, ignore_globs=None, include_globs=None)¶
Gets detailed content changes for a specific commit.
For each file changed in the commit, returns the actual content changes including added and removed lines.
- Parameters:
- Returns:
- A DataFrame with columns:
file (str): Path of the changed file
change_type (str): Type of change (A=added, M=modified, D=deleted)
old_line_num (int): Line number in the old version (None for added lines)
new_line_num (int): Line number in the new version (None for deleted lines)
content (str): The actual line content
repository (str): Repository name
Additional columns for any labels specified in labels_to_add
- Return type:
Note
For binary files, only the change_type is recorded, with no line-by-line changes. If both ignore_globs and include_globs are provided, files must match an include pattern and not match any ignore patterns to be included.
- get_file_content(path, rev='HEAD')¶
Gets the content of a file from the repository at a specific revision.
Safely retrieves file content by first verifying the file exists in git’s tree (respecting .gitignore) before attempting to read it.
- Parameters:
- Returns:
- Content of the file if it exists and is tracked by git,
None if file doesn’t exist or isn’t tracked.
- Return type:
Optional[str]
Note
This only works for files that are tracked by git. Untracked files and files matched by .gitignore patterns cannot be read.
- has_branch(branch)¶
Checks if a branch exists in the repository.
- Parameters:
branch (str) – Name of the branch to check
- Returns:
True if the branch exists, False otherwise
- Return type:
Note
This checks both local and remote branches.
- has_coverage()¶
Checks if a parseable .coverage file exists in the repository.
Attempts to find and parse a .coverage file in the repository root directory. The file must be in a valid format that can be parsed as JSON.
- Returns:
True if a valid .coverage file exists, False otherwise
- Return type:
- hours_estimate(branch=None, grouping_window=0.5, single_commit_hours=0.5, limit=None, days=None, committer=True, ignore_globs=None, include_globs=None)¶
inspired by: https://github.com/kimmobrunfeldt/git-hours/blob/8aaeee237cb9d9028e7a2592a25ad8468b1f45e4/index.js#L114-L143
Iterates through the commit history of repo to estimate the time commitement of each author or committer over the course of time indicated by limit/extensions/days/etc.
- Parameters:
branch – (optional, default=None) the branch to return commits for, defaults to default_branch if None
limit – (optional, default=None) a maximum number of commits to return, None for no limit
grouping_window – (optional, default=0.5 hours) the threhold for how close two commits need to be to consider them part of one coding session
single_commit_hours – (optional, default 0.5 hours) the time range to associate with one single commit
days – (optional, default=None) number of days to return, if limit is None
committer – (optional, default=True) whether to use committer vs. author
ignore_globs – (optional, default=None) a list of globs to ignore, default none excludes nothing
include_globs – (optinal, default=None) a list of globs to include, default of None includes everything.
- Returns:
DataFrame
- invalidate_cache(keys=None, pattern=None)¶
Invalidate specific cache entries or all cache entries for this repository.
- Parameters:
- Returns:
Number of cache entries invalidated
- Return type:
Note
If both keys and pattern are None, all cache entries for this repository are invalidated. Cache keys are automatically prefixed with repository name.
- is_bare()¶
Checks if this is a bare repository.
A bare repository is one without a working tree, typically used as a central repository.
- Returns:
True if this is a bare repository, False otherwise
- Return type:
- list_files(rev='HEAD')¶
Lists all files in the repository at a specific revision, respecting .gitignore.
Uses git ls-tree to get a list of all tracked files in the repository, which automatically respects .gitignore rules since untracked and ignored files are not in git’s tree.
- Parameters:
rev (str, optional) – Revision to list files from. Defaults to ‘HEAD’.
- Returns:
- A DataFrame with columns:
file (str): Full path to the file relative to repository root
mode (str): File mode (100644 for regular file, 100755 for executable, etc)
type (str): Object type (blob for file, tree for directory)
sha (str): SHA-1 hash of the file content
repository (str): Repository name
Additional columns for any labels specified in labels_to_add
- Return type:
Note
This only includes files that are tracked by git. Untracked files and files matched by .gitignore patterns are not included.
- parallel_cumulative_blame(branch=None, limit=None, skip=None, num_datapoints=None, committer=True, workers=1, ignore_globs=None, include_globs=None, skip_broken=True)¶
Returns the blame at every revision of interest. Index is a datetime, column per committer, with number of lines blamed to each committer at each timestamp as data.
- Parameters:
branch (Optional[str]) – Branch to analyze. Defaults to default_branch if None.
limit (Optional[int]) – Maximum number of revisions to return, None for no limit
skip (Optional[int]) – Number of revisions to skip. Ex: skip=2 returns every other revision, None for no skipping.
num_datapoints (Optional[int]) – If limit and skip are none, and this isn’t, then num_datapoints evenly spaced revs will be used
committer (bool, optional) – True if committer should be reported, false if author
ignore_globs (Optional[List[str]]) – List of glob patterns for files to ignore
include_globs (Optional[List[str]]) – List of glob patterns for files to include
workers (Optional[int]) – Number of workers to use in the threadpool, -1 for one per core.
skip_broken (bool, optional) – Whether to skip corrupted Git objects. Defaults to True.
- Returns:
- A DataFrame indexed by an ascending (monotonically increasing)
DatetimeIndex named
date, with one column per contributor holding the lines blamed to them at that revision. Label columns (repositoryand anylabels_to_addentries) are not included, so the frame is entirely numeric anddf.sum(axis=1)gives total LOC.
- Return type:
DataFrame
- punchcard(branch=None, limit=None, days=None, by=None, normalize=None, ignore_globs=None, include_globs=None)¶
Returns a pandas DataFrame containing all of the data for a punchcard.
day_of_week
hour_of_day
author / committer
lines
insertions
deletions
net
- Parameters:
branch (Optional[str]) – Branch to analyze. Defaults to default_branch if None.
limit (Optional[int]) – Maximum number of commits to return, None for no limit
days (Optional[int]) – Number of days to return if limit is None
by (Optional[str]) – Agg by options, None for no aggregation (just a high level punchcard), or ‘committer’, ‘author’
normalize (Optional[int]) – If an integer, returns the data normalized to max value of that (for plotting)
ignore_globs (Optional[List[str]]) – List of glob patterns for files to ignore
include_globs (Optional[List[str]]) – List of glob patterns for files to include
- Returns:
DataFrame with punchcard data
- Return type:
DataFrame
- release_tag_summary(tag_glob=None, ignore_globs=None, include_globs=None)¶
Summarizes repository activity between release tags.
For each tag (filtered by glob), computes the time since the previous tag, diff statistics, committers/authors involved, and files changed between tags. Returns a DataFrame with one row per tag and columns for all computed metrics.
- Parameters:
tag_glob (Optional[Union[str, List[str]]]) – Glob pattern(s) to filter tags (e.g., ‘v*’ or [‘v*’, ‘release-*’]). If None, all tags are included.
ignore_globs (Optional[List[str]]) – List of glob patterns for files to ignore in diff/commit analysis.
include_globs (Optional[List[str]]) – List of glob patterns for files to include in diff/commit analysis.
- Returns:
- DataFrame with columns:
tag (str): Tag name
tag_date (datetime): Tag creation date
commit_sha (str): SHA of the tagged commit
time_since_prev (float): Days since previous tag
insertions (int): Lines inserted since previous tag
deletions (int): Lines deleted since previous tag
net (int): Net lines changed since previous tag
files_changed (int): Number of files changed since previous tag
committers (List[str]): Committers between previous and current tag
authors (List[str]): Authors between previous and current tag
files (List[str]): Files changed between previous and current tag
- Return type:
Note
The first tag in the sorted list will have NaN for time_since_prev and empty diff/commit info. Tag filtering uses fnmatch and supports multiple globs.
- property repo_name¶
- revs(branch=None, limit=None, skip=None, num_datapoints=None, skip_broken=False)¶
Returns a dataframe of all revision tags and their timestamps. It will have the columns:
date
rev
- Parameters:
branch (Optional[str]) – Branch to analyze. Defaults to default_branch if None.
limit (Optional[int]) – Maximum number of revisions to return, None for no limit
skip (Optional[int]) – Number of revisions to skip. Ex: skip=2 returns every other revision, None for no skipping.
num_datapoints (Optional[int]) – If limit and skip are none, and this isn’t, then num_datapoints evenly spaced revs will be used
skip_broken (bool) – Whether to skip corrupted commit objects. Defaults to False.
- Returns:
DataFrame with revision information
- Return type:
DataFrame
- safe_fetch_remote(remote_name='origin', prune=False, dry_run=False)¶
Safely fetch changes from remote repository.
Fetches the latest changes from a remote repository without modifying the working directory. This is a read-only operation that only updates remote-tracking branches.
- Parameters:
- Returns:
- Fetch results with keys:
success (bool): Whether the fetch was successful
message (str): Status message or error description
remote_exists (bool): Whether the specified remote exists
changes_available (bool): Whether new changes were fetched
error (Optional[str]): Error message if fetch failed
- Return type:
Note
This method is safe as it only fetches remote changes and never modifies the working directory or current branch. It will not perform any merges, rebases, or checkouts.
- tags(skip_broken=False)¶
Returns information about all tags in the repository.
Retrieves detailed information about all tags, including both lightweight and annotated tags.
- Parameters:
skip_broken (bool) – Whether to skip corrupted tag objects. Defaults to False.
- Returns:
- A DataFrame indexed by (tag_date, commit_date) with columns:
tag (str): Name of the tag
annotated (bool): Whether it’s an annotated tag
annotation (str): Tag message (empty for lightweight tags)
tag_sha (Optional[str]): SHA of tag object (None for lightweight tags)
commit_sha (str): SHA of the commit being tagged
repository (str): Repository name
Additional columns for any labels specified in labels_to_add
- Return type:
Note
tag_date is the tag creation time for annotated tags, commit time for lightweight
commit_date is always the timestamp of the tagged commit
Both dates are timezone-aware UTC timestamps
- time_between_revs(rev1, rev2)¶
Calculates the time difference in days between two revisions.
- Parameters:
- Returns:
The absolute time difference in days between the two revisions.
- Return type:
Note
The result is always non-negative (absolute value).
- warm_cache(methods=None, **kwargs)¶
Pre-populate cache with commonly used data.
Executes a set of commonly used repository analysis methods to populate the cache, improving performance for subsequent calls. Only methods that support caching will be executed.
- Parameters:
methods (Optional[List[str]]) – List of method names to pre-warm. If None, uses a default set of commonly used methods. Available methods: - ‘commit_history’: Load commit history - ‘branches’: Load branch information - ‘tags’: Load tag information - ‘blame’: Load blame information - ‘file_detail’: Load file details - ‘list_files’: Load file listing - ‘file_change_rates’: Load file change statistics
**kwargs – Additional keyword arguments to pass to compatible methods unchanged. Common arguments include: - branch: Branch to analyze (default: repository’s default branch) - limit: Limit number of commits to analyze - ignore_globs: List of glob patterns to ignore - include_globs: List of glob patterns to include
- Returns:
- Results of cache warming operations with keys:
success (bool): Whether cache warming was successful
methods_executed (List[str]): List of methods that were executed
methods_failed (List[str]): List of methods that failed
cache_entries_created (int): Number of cache entries created
execution_time (float): Total execution time in seconds
errors (List[str]): List of error messages for failed methods
- Return type:
Note
This method will only execute methods if a cache backend is configured. If no cache backend is available, it will return immediately with a success status but no methods executed.
- __init__()[source]¶
Initialize a Repository instance.
- Parameters:
working_dir (Optional[str]) – Path to the git repository: - If None: Uses current working directory - If local path: Path must contain a .git directory - If git URL: Repository will be cloned to a temporary directory
verbose (bool, optional) – Whether to print verbose output. Defaults to False.
tmp_dir (Optional[str]) – Directory to clone remote repositories into. Created if not provided.
cache_backend (Optional[object]) – Cache backend instance from gitpandas.cache
labels_to_add (Optional[List[str]]) – Extra labels to add to output DataFrames
default_branch (Optional[str]) – Name of the default branch to use. If None, will try to detect ‘main’ or ‘master’, and if neither exists, will raise ValueError.
- Raises:
ValueError – If default_branch is None and neither ‘main’ nor ‘master’ branch exists