module Git
Define Git::Deprecation before requiring the rest of the library to ensure that any deprecation warnings emitted during the loading of the library are properly configured according to the GIT_DEPRECATION_BEHAVIOR environment variable.
The Git module provides the basic functions to open a git reference to work with. You can open a working directory, open a bare repository, initialize a new repo or clone an existing remote repository.
Constants
- BRANCH_REFNAME_REGEXP
-
Regular expression for parsing branch refnames
Captures:
- remote_name: the remote name (e.g., 'origin') for remote branches, nil for local - branch_name: the branch name without the remote prefix
@example Parse branch refnames
'main' => { remote_name: nil, branch_name: 'main' } 'refs/heads/main' => { remote_name: nil, branch_name: 'main' } 'remotes/origin/main' => { remote_name: 'origin', branch_name: 'main' } 'refs/remotes/origin/main' => { remote_name: 'origin', branch_name: 'main' } 'feature/foo' => { remote_name: nil, branch_name: 'feature/foo' } 'remotes/origin/feature/bar' => { remote_name: 'origin', branch_name: 'feature/bar' }
@note This regex handles both raw full refs (e.g., ‘refs/heads/main`) as stored in
{Git::BranchInfo#refname} and normalized short-form refs (e.g., `main`, `remotes/origin/main`) used elsewhere.@note This regex is a fallback for branch refnames parsed without configured
remote context. Remote names containing '/' can only be resolved reliably when the parser is given the configured remote names. See: https://github.com/ruby-git/ruby-git/issues/919
@api private
- Base
-
Compatibility shim for code that monkeypatches the ‘Git::Base` class from versions prior to 5.0.0.
‘Git::Base` is a module included in {Git::Repository}, so any instance methods added to `Git::Base` are automatically available on {Git::Repository} instances. A deprecation warning is emitted for each method added, encouraging migration to an application-owned extension module.
@example Monkeypatching
Git::Base(deprecated)module Git::Base def my_helper = "hello" end Git.open('.').my_helper # => "hello"
@deprecated Move custom methods to an application-owned extension module and
include or prepend it into {Git::Repository}.@api public
- BranchDeleteFailure
-
Represents a branch that failed to be deleted
This is an immutable data object returned as part of {Git::BranchDeleteResult} when one or more branches could not be deleted.
@example
failure = Git::BranchDeleteFailure.new( name: 'nonexistent', error_message: "branch 'nonexistent' not found." ) failure.name #=> 'nonexistent' failure.error_message #=> "branch 'nonexistent' not found."
@see
Git::Commands::Branch::Delete@api public
@!attribute [r] name
The name of the branch that failed to be deleted @return [String]
@!attribute [r] error_message
The error message from git explaining why the branch could not be deleted @return [String]
- BranchDeleteResult
-
Represents the result of a branch delete operation
This is an immutable data object returned by {Git::Commands::Branch::Delete#call}. It contains information about which branches were successfully deleted and which failed to be deleted, along with the reason for each failure.
Git’s ‘git branch -d` command uses “best effort” semantics - it deletes as many branches as possible and reports errors for those that couldn’t be deleted. This result object reflects that behavior, allowing callers to inspect both successes and failures.
@example Successful deletion of all branches
result = branch_delete.call('feature-1', 'feature-2') result.success? #=> true result.deleted.map(&:name) #=> ['feature-1', 'feature-2'] result.not_deleted #=> []
@example Partial failure (some branches deleted, some not found)
result = branch_delete.call('feature-1', 'nonexistent', 'feature-2') result.success? #=> false result.deleted.map(&:name) #=> ['feature-1', 'feature-2'] result.not_deleted.first.name #=> 'nonexistent' result.not_deleted.first.error_message #=> "branch 'nonexistent' not found."
@see
Git::BranchInfo@see
Git::Commands::Branch::Delete@api public
@!attribute [r] deleted
Branches that were successfully deleted @return [Array<Git::BranchInfo>]
@!attribute [r] not_deleted
Branches that could not be deleted, with the reason for each failure @return [Array<Git::BranchDeleteFailure>]
- BranchInfo
-
Value object representing branch metadata from git branch output
This is a lightweight, immutable data structure returned by branch listing commands. It contains only the data parsed from git output without any repository context or operations.
@example Local branch with upstream tracking
info = Git::BranchInfo.new( refname: 'refs/heads/main', target_oid: 'abc123def456789012345678901234567890abcd', current: true, worktree_path: nil, symref: nil, upstream: 'refs/remotes/origin/main' ) info.current? #=> true info.remote? #=> false info.short_name #=> 'main' info.upstream #=> 'refs/remotes/origin/main'
@example Remote-tracking branch
info = Git::BranchInfo.new( refname: 'refs/remotes/origin/main', target_oid: 'abc123def456789012345678901234567890abcd', current: false, worktree_path: nil, symref: nil, upstream: nil ) info.remote? #=> true info.remote_name #=> 'origin' info.short_name #=> 'main'
@see
Git::Branchfor the full-featured branch object with operations@see
Git::Commands::Branch::Listfor the command that produces these@api public
@!attribute [r] refname
The full reference name of the branch Must be the full refname as returned by git (e.g., 'refs/heads/main', 'refs/remotes/origin/main') because the short name alone is not guaranteed to be unique (e.g., 'main' could exist as both a local and remote branch). @return [String] the branch refname (e.g., 'refs/heads/main', 'refs/remotes/origin/main')
@!attribute [r] remote_name
@return [String, nil] the resolved or fallback-derived remote name, or nil for local branches
@!attribute [r] target_oid
The commit object ID (SHA) that this branch points to (aka HEAD) @return [String, nil] the full 40-character object ID, or nil if branch is unborn (no commits yet)
@!attribute [r] current
Whether this branch is currently checked out in the current worktree @return [Boolean] true if this is the current branch @note A branch can be current ({#current?} true) or in another worktree ({#other_worktree?} true), but never both. A branch not checked out anywhere has both false.@!attribute [r] worktree_path
The absolute path of the *other* linked worktree this branch is checked out in, or nil. This is nil in two distinct cases: - The branch is the current branch in this worktree (use {#current?} to distinguish that case) - The branch is not checked out in any worktree This path is suppressed for the current branch even though git reports it via `%(worktreepath)`, because the current worktree's path is already known from the repository object and storing it here would make {#other_worktree?} incorrect. @return [String, nil] the absolute path of the linked worktree root directory (e.g., `'/home/user/projects/my-repo-hotfix'`), or nil if the branch is not checked out in a different linked worktree@!attribute [r] symref
The target reference if this is a symbolic reference @return [String, nil] the target ref (e.g., 'refs/heads/main'), or nil if not a symref
@!attribute [r] upstream
The configured upstream/tracking branch refname as reported by git @return [String, nil] the raw upstream refname from `%(upstream)` (e.g., `'refs/remotes/origin/main'`), or nil if no upstream is configured @note Remote-tracking branches (e.g., `'refs/remotes/origin/main'`) have upstream: nil @note This is the raw refname snapshot from when the branch list was read. It does not reflect live git state after the snapshot was taken.
- ConfigEntryInfo
-
Represents a single
Gitconfiguration entryReturned by {Git::Configuring} read operations such as {Git::Configuring#config_get}, {Git::Configuring#config_get_all}, {Git::Configuring#config_list}, and their related methods.
@example Create a
ConfigEntryInfoentry = Git::ConfigEntryInfo.new( scope: 'local', origin: 'file:.git/config', key: 'remote.origin.url', value: 'https://github.com/ruby-git/ruby-git' ) entry.section # => "remote" entry.subsection # => "origin" entry.variable # => "url"
@api public
@!attribute [r] scope
The scope of the configuration entry May be one of `"system"`, `"global"`, `"local"`, `"worktree"`, `"command"`, `"file"`, or `"blob"`. The `"command"` scope is used for values supplied via the command line (including default values from `--default`). @return [String] the config scope string (e.g. `"local"`, `"global"`)
@!attribute [r] origin
Where the configuration entry originates The origin is in the format `<origin-type>:<actual-origin>` and is never blank. The origin type prefix is one of `file:`, `blob:`, `command line:`, or `standard input:`. `nil` when the git command used to retrieve this entry does not support `--show-origin` (currently only `--get-urlmatch`). @return [String, nil] the origin path in the format `<type>:<path>`, or `nil`
@!attribute [r] key
The full dotted key name of the configuration entry (e.g., `remote.origin.url`) @return [String] the full dotted key name (e.g. `remote.origin.url`)
@!attribute [r] value
The value of the configuration entry @return [String] the string value of this entry
- Deprecation
-
The deprecation instance used to emit deprecation warnings for the
Gitgem@api public
- DetachedHeadInfo
-
Value object representing a detached HEAD state
When HEAD points directly to a commit rather than a branch reference, the repository is in a “detached HEAD” state. This object captures that state along with the commit SHA that HEAD points to.
This class shares a minimal interface with {Git::BranchInfo} to allow polymorphic usage where appropriate:
-
‘short_name` - returns ’HEAD’
-
‘target_oid` - returns the commit SHA
-
‘to_s` - returns ’HEAD’
-
‘detached?` - returns true
@example Detecting detached HEAD state
head = repo.show_current if head.detached? puts "HEAD detached at #{head.target_oid[0, 7]}" else puts "On branch #{head.short_name}" end
@example Polymorphic usage
head = repo.show_current puts "Checked out: #{head.short_name}" # Works for both types system("git log #{head.short_name}") # Works for both types
@see
Git::BranchInfofor the branch counterpart@see
Git::Commands::Branch::ShowCurrentfor the command that produces this@api private
Work in progress; this class is internal for now and may be made public in a future release.
@!attribute [r] target_oid
The commit object ID (SHA) that HEAD points to @return [String] the full 40-character object ID
-
- DiffFileNumstatInfo
-
Immutable value object representing stats for a single file from git numstat output
@api private
Work in progress; this class is internal for now and may be made public in a future release.
@!attribute [r] path
@return [String] the file path (destination path for renames)
@!attribute [r] src_path
@return [String, nil] the source path for renamed files, nil otherwise
@!attribute [r] insertions
@return [Integer] number of lines inserted
@!attribute [r] deletions
@return [Integer] number of lines deleted
- DiffFilePatchInfo
-
Immutable value object representing a single file’s patch information
DiffFilePatchInfoencapsulates the parsed data from a unified diff for one file, including source and destination file references, the patch text, change type, and line statistics.@example A modified file patch
patch_info = Git::DiffFilePatchInfo.new( src: Git::FileRef.new(mode: '100644', sha: 'abc1234', path: 'lib/foo.rb'), dst: Git::FileRef.new(mode: '100644', sha: 'def5678', path: 'lib/foo.rb'), patch: "diff --git a/lib/foo.rb b/lib/foo.rb\n...", status: :modified, similarity: nil, binary: false, insertions: 10, deletions: 5 )
@example A new file patch (src is nil)
patch_info = Git::DiffFilePatchInfo.new( src: nil, dst: Git::FileRef.new(mode: '100644', sha: 'abc1234', path: 'lib/new.rb'), patch: "diff --git a/lib/new.rb b/lib/new.rb\nnew file mode 100644\n...", status: :added, similarity: nil, binary: false, insertions: 20, deletions: 0 )
@!attribute [r] src
@return [FileRef, nil] the source file reference, or nil for new/added files
@!attribute [r] dst
@return [FileRef, nil] the destination file reference, or nil for deleted files
@!attribute [r] patch
@return [String] the full unified diff patch text for this file
@!attribute [r] status
@return [Symbol] the change status (:added, :modified, :deleted, :renamed, :copied, :type_changed)
@!attribute [r] similarity
@return [Integer, nil] similarity percentage for renames/copies (0-100), nil otherwise
@!attribute [r] binary
@return [Boolean] whether this is a binary file
@!attribute [r] insertions
@return [Integer] number of lines inserted
@!attribute [r] deletions
@return [Integer] number of lines deleted
@api private
Work in progress; this class is internal for now and may be made public in a future release.
- DiffFileRawInfo
-
Immutable value object representing status info for a single file from git raw diff output
Contains the source and destination file references, change status, similarity percentage (for renames/copies), and line change statistics.
@example A modified file
info = Git::DiffFileRawInfo.new( src: Git::FileRef.new(mode: '100644', sha: 'abc1234', path: 'lib/foo.rb'), dst: Git::FileRef.new(mode: '100644', sha: 'def5678', path: 'lib/foo.rb'), status: :modified, similarity: nil, insertions: 5, deletions: 2, binary: false )
@example A new file (src is nil)
info = Git::DiffFileRawInfo.new( src: nil, dst: Git::FileRef.new(mode: '100644', sha: 'abc1234', path: 'lib/new.rb'), status: :added, similarity: nil, insertions: 10, deletions: 0, binary: false )
@example A renamed file
info = Git::DiffFileRawInfo.new( src: Git::FileRef.new(mode: '100644', sha: 'abc1234', path: 'lib/old.rb'), dst: Git::FileRef.new(mode: '100644', sha: 'def5678', path: 'lib/new.rb'), status: :renamed, similarity: 95, insertions: 2, deletions: 1, binary: false )
@!attribute [r] src
@return [FileRef, nil] the source file reference, or nil for new/added files
@!attribute [r] dst
@return [FileRef, nil] the destination file reference, or nil for deleted files
@!attribute [r] status
@return [Symbol] the change status (:added, :modified, :deleted, :renamed, :copied, :type_changed)
@!attribute [r] similarity
@return [Integer, nil] similarity percentage for renames/copies (0-100), nil otherwise
@!attribute [r] insertions
@return [Integer] number of lines inserted
@!attribute [r] deletions
@return [Integer] number of lines deleted
@!attribute [r] binary
@return [Boolean] whether this is a binary file
@api private
Work in progress; this class is internal for now and may be made public in a future release.
- DiffInfo
-
Immutable value object representing diff statistics and optional file patches
DiffInfoencapsulates the parsed output from various git commands that produce diff statistics (like ‘git stash show –stat`). When patches are requested, it also includes the full patch information for each file.The stats hash structure:
-
‘:total` - Hash with `:insertions`, `:deletions`, `:lines`, `:files` keys
-
‘:files` - Hash mapping file paths to `{ insertions:, deletions: }` hashes
@example Create a
DiffInfofrom parsed stats outputinfo = Git::DiffInfo.new( stats: { total: { insertions: 10, deletions: 5, lines: 15, files: 2 }, files: { 'lib/foo.rb' => { insertions: 8, deletions: 3 }, 'lib/bar.rb' => { insertions: 2, deletions: 2 } } }, file_patches: [] )
@example Access statistics
info.insertions # => 10 info.deletions # => 5 info.lines # => 15 info.file_count # => 2
@api private
Work in progress; this class is internal for now and may be made public in a future release.
@!attribute [r] stats
@return [Hash] the statistics hash with :total and :files keys
@!attribute [r] file_patches
@return [Array<FileDiffInfo>] array of file diff info objects (empty if patch not requested)
-
- DiffResult
-
Immutable result object from git diff commands
Contains summary statistics and per-file information from various diff formats. The ‘files` array contains one of:
-
DiffFileNumstatInfo(from –numstat) -
DiffFileRawInfo(from –raw) -
DiffFilePatchInfo(from –patch)
@api private
Work in progress; this class is internal for now and may be made public in a future release.
@!attribute [r] files_changed
@return [Integer] number of files changed (from --shortstat)
@!attribute [r] total_insertions
@return [Integer] total lines inserted across all files (from --shortstat)
@!attribute [r] total_deletions
@return [Integer] total lines deleted across all files (from --shortstat)
@!attribute [r] files
@return [Array<DiffFileNumstatInfo, DiffFileRawInfo, DiffFilePatchInfo>] per-file information
@!attribute [r] dirstat
@return [DirstatInfo, nil] directory statistics if requested, nil otherwise
-
- DirstatEntry
-
Immutable value object representing a single directory’s contribution to a diff
@example Create a
DirstatEntryinfo = Git::DirstatEntry.new(directory: 'lib/commands/', percentage: 45.2) info.directory #=> "lib/commands/" info.percentage #=> 45.2
@api private
Work in progress; this class is internal for now and may be made public in a future release.
@!attribute [r] directory
@return [String] the directory path (always ends with '/')
@!attribute [r] percentage
@return [Float] the percentage of changes in this directory (0.0-100.0)
- DirstatInfo
-
Immutable result object from git –dirstat output
Contains the list of directories and their contribution percentages to the diff.
@example Create a
DirstatInfodirstat = Git::DirstatInfo.new( entries: [ Git::DirstatEntry.new(directory: 'lib/commands/', percentage: 45.2), Git::DirstatEntry.new(directory: 'spec/unit/', percentage: 30.1) ] ) dirstat.entries.first.directory #=> "lib/commands/" dirstat['lib/commands/'] #=> 45.2 dirstat.to_h #=> { "lib/commands/" => 45.2, "spec/unit/" => 30.1 }
@api private
Work in progress; this class is internal for now and may be made public in a future release.
@!attribute [r] entries
@return [Array<DirstatEntry>] directory statistics in order from git output
- FileDiffInfo
-
Immutable value object representing a single file’s diff information
FileDiffInfoencapsulates the parsed data from a unified diff for one file, including the file path, patch text, mode changes, object identifiers, and type.This class is used by
DiffInfofor the legacy diff API.@example Create a
FileDiffInfofrom parsed diff outputdiff_info = Git::FileDiffInfo.new( path: 'lib/example.rb', patch: "diff --git a/lib/example.rb b/lib/example.rb\n...", mode: '100644', src: 'abc1234', dst: 'def5678', type: 'modified', binary: false )
@!attribute [r] path
@return [String] the file path relative to the repository root
@!attribute [r] patch
@return [String] the full unified diff patch text for this file
@!attribute [r] mode
@return [String] the file mode (e.g., '100644' for regular files)
@!attribute [r] src
@return [String] the source blob object identifier
@!attribute [r] dst
@return [String] the destination blob object identifier
@!attribute [r] type
@return [String] the type of change: 'modified', 'new', 'deleted', 'renamed'
@!attribute [r] binary
@return [Boolean] whether this is a binary file
@api private
Work in progress; this class is internal for now and may be made public in a future release.
- FileRef
-
Immutable value object representing a reference to a file at a specific point in time
FileRefencapsulates the mode, SHA, and path of a file as it exists on one side of a diff. This is used to represent either the source (before) or destination (after) state of a file in a diff operation.When a file doesn’t exist on a side of the diff (e.g., src for new files, dst for deleted files), the entire
FileRefshould be nil rather than having aFileRefwith nil attributes.@example A modified file’s source reference
src = Git::FileRef.new(mode: '100644', sha: 'abc1234', path: 'lib/foo.rb')
@example A new file (src would be nil, not a
FileRef)# src = nil dst = Git::FileRef.new(mode: '100644', sha: 'def5678', path: 'lib/new_file.rb')
@api private
Work in progress; this class is internal for now and may be made public in a future release.
@!attribute [r] mode
@return [String] the file mode (e.g., '100644' for regular file, '100755' for executable, '120000' for symlink)
@!attribute [r] sha
@return [String] the blob SHA (object identifier)
@!attribute [r] path
@return [String] the file path relative to repository root
- GitExecuteError
-
An alias for
Git::ErrorGit::GitExecuteErrorerror class is an alias forGit::Errorfor backwards compatibility. It is recommended to useGit::Errordirectly.@deprecated Use
Git::Errorinstead - LS_REMOTE_ALLOWED_OPTS
-
Option keys accepted by {.ls_remote}
Parser-incompatible options such as ‘:get_url` and `:symref` are intentionally excluded because {Git::Parsers::LsRemote.parse_output} cannot handle the non-standard output formats those flags produce.
@return [Array<Symbol>]
@api private
- MINIMUM_GIT_VERSION
-
Minimum git version required by this gem
Commandsand features may require newer versions, but this is the absolute minimum supported version for the gem as a whole.@return [Git::Version]
@api public
- REMOTE_NAME_NOT_GIVEN
-
Sentinel for distinguishing omitted
BranchInforemote_name from explicit nil - REPOSITORY_SPECIFIC_SCOPES
-
Scopes that require an active repository and cannot be used at the
Gitmodule level@api private
- RemoteInfo
-
Value object representing a configured git remote
Each instance holds the parsed configuration for a single remote as read from the repository’s git config. Multi-value fields (‘:url`, `:push_url`, `:fetch`, `:push`) are always `Array<String>` (never `nil`; may be empty). All other fields are nilable except `:name`.
@example Minimal remote (fetch-only, one
URL)info = Git::RemoteInfo.new( name: 'origin', url: ['https://github.com/ruby-git/ruby-git.git'], push_url: [], fetch: ['+refs/heads/*:refs/remotes/origin/*'], push: [] ) info.name # => "origin" info.url # => ["https://github.com/ruby-git/ruby-git.git"] info.prune # => nil
@api public
@!attribute [r] name
@return [String] the name of the remote (e.g. `'origin'`)
@!attribute [r] url
@return [Array<String>] the fetch URL(s) for this remote (`remote.<name>.url`)
@!attribute [r] push_url
@return [Array<String>] the push URL(s) for this remote (`remote.<name>.pushurl`)
@!attribute [r] fetch
@return [Array<String>] the fetch refspec(s) for this remote (`remote.<name>.fetch`)
@!attribute [r] push
@return [Array<String>] the push refspec(s) for this remote (`remote.<name>.push`)
@!attribute [r] mirror
@return [Boolean, nil] `true`/`false` per `remote.<name>.mirror`, or `nil` when not set
@!attribute [r] skip_default_update
@return [Boolean, nil] `true`/`false` per `remote.<name>.skipDefaultUpdate`, or `nil` when not set
@!attribute [r] tag_opt
@return [String, nil] the tag-fetching option (`remote.<name>.tagOpt`), or `nil` when not set
@!attribute [r] prune
@return [Boolean, nil] `true`/`false` per `remote.<name>.prune`; `nil` inherits `fetch.prune`
@!attribute [r] prune_tags
@return [Boolean, nil] `true`/`false` per `remote.<name>.pruneTags`; `nil` inherits `fetch.pruneTags`
@!attribute [r] receivepack
@return [String, nil] the `git-receive-pack` path on the remote (`remote.<name>.receivepack`)
@!attribute [r] uploadpack
@return [String, nil] the `git-upload-pack` path on the remote (`remote.<name>.uploadpack`)
@!attribute [r] promisor
@return [Boolean, nil] `true`/`false` per `remote.<name>.promisor`, or `nil` when not set
@!attribute [r] partial_clone_filter
@return [String, nil] the partial-clone object filter (`remote.<name>.partialclonefilter`)
@!attribute [r] vcs
@return [String, nil] the VCS type for git-remote helpers (`remote.<name>.vcs`)
- StashInfo
-
Immutable value object representing stash entry information
StashInfoencapsulates the parsed data from ‘git stash list` output. Each entry contains comprehensive information about the stash including its index, reference name, commit SHA, branch, message, author/committer details, and timestamps.@example Create a
StashInfofrom parsed stash list outputinfo = Git::StashInfo.new( index: 0, name: 'stash@{0}', oid: 'abc123def456789...', short_oid: 'abc123d', branch: 'main', message: 'WIP on main: abc123 Initial commit', author_name: 'Jane Doe', author_email: 'jane@example.com', author_date: '2026-01-24T10:30:00-08:00', committer_name: 'Jane Doe', committer_email: 'jane@example.com', committer_date: '2026-01-24T10:30:00-08:00' ) info.index # => 0 info.name # => 'stash@{0}' info.oid # => 'abc123def456789...' info.short_oid # => 'abc123d' info.branch # => 'main' info.message # => 'WIP on main: abc123 Initial commit' info.author_name # => 'Jane Doe' info.author_email # => 'jane@example.com' info.author_date # => '2026-01-24T10:30:00-08:00' info.committer_name # => 'Jane Doe' info.committer_email # => 'jane@example.com' info.committer_date # => '2026-01-24T10:30:00-08:00'
@api public
@!attribute [r] index
@return [Integer] the stash index (0, 1, 2, ...)
@!attribute [r] name
@return [String] the stash reference name (e.g., 'stash@\\{0\\}')@!attribute [r] oid
@return [String] the full 40-character object identifier of the stash
@!attribute [r] short_oid
@return [String] the abbreviated object identifier (typically 7 characters)
@!attribute [r] branch
@return [String, nil] the branch name where the stash was created, or nil for custom stash messages
@!attribute [r] message
@return [String] the stash message (e.g., 'WIP on main: abc123 commit msg')
@!attribute [r] author_name
@return [String] the name of the stash author
@!attribute [r] author_email
@return [String] the email of the stash author
@!attribute [r] author_date
@return [String] the author date in ISO 8601 format
@!attribute [r] committer_name
@return [String] the name of the stash committer
@!attribute [r] committer_email
@return [String] the email of the stash committer
@!attribute [r] committer_date
@return [String] the committer date in ISO 8601 format
- TagDeleteFailure
-
Represents a tag that failed to be deleted
This is an immutable data object returned as part of {Git::TagDeleteResult} when one or more tags could not be deleted.
@example
failure = Git::TagDeleteFailure.new( name: 'nonexistent', error_message: "tag 'nonexistent' not found." ) failure.name #=> 'nonexistent' failure.error_message #=> "tag 'nonexistent' not found."
@see
Git::TagDeleteResult@see
Git::Commands::Tag::Delete@api public
@!attribute [r] name
The name of the tag that failed to be deleted @return [String]
@!attribute [r] error_message
The error message from git explaining why the tag could not be deleted @return [String]
- TagDeleteResult
-
Represents the result of a tag delete operation
This is an immutable data object returned by {Git::Commands::Tag::Delete#call}. It contains information about which tags were successfully deleted and which failed to be deleted, along with the reason for each failure.
Git’s ‘git tag -d` command uses “best effort” semantics - it deletes as many tags as possible and reports errors for those that couldn’t be deleted. This result object reflects that behavior, allowing callers to inspect both successes and failures.
@example Successful deletion of all tags
result = tag_delete.call('v1.0.0', 'v2.0.0') result.success? #=> true result.deleted.map(&:name) #=> ['v1.0.0', 'v2.0.0'] result.not_deleted #=> []
@example Partial failure (some tags deleted, some not found)
result = tag_delete.call('v1.0.0', 'nonexistent', 'v2.0.0') result.success? #=> false result.deleted.map(&:name) #=> ['v1.0.0', 'v2.0.0'] result.not_deleted.first.name #=> 'nonexistent' result.not_deleted.first.error_message #=> "tag 'nonexistent' not found."
@see
Git::TagInfo@see
Git::Commands::Tag::Delete@api public
@!attribute [r] deleted
Tags that were successfully deleted @return [Array<Git::TagInfo>]
@!attribute [r] not_deleted
Tags that could not be deleted, with the reason for each failure @return [Array<Git::TagDeleteFailure>]
- TagInfo
-
Value object representing tag metadata from git tag output
This is a lightweight, immutable data structure returned by tag listing commands. It contains only the data parsed from git output without any repository context or operations.
@example Annotated tag
info = Git::TagInfo.new( name: 'v1.0.0', oid: 'abc123def456', # tag object's ID target_oid: 'def456abc789', # commit it points to objecttype: 'tag', tagger_name: 'John Doe', tagger_email: '<john@example.com>', tagger_date: '2024-01-15T10:30:00-08:00', message: 'Release version 1.0.0' ) info.annotated? #=> true info.tagger.name #=> 'John Doe'
@example Lightweight tag
info = Git::TagInfo.new( name: 'v1.0.0', oid: nil, # no tag object exists target_oid: 'def456abc789', # commit ID objecttype: 'commit', tagger_name: nil, tagger_email: nil, tagger_date: nil, message: nil ) info.lightweight? #=> true info.tagger #=> nil
@see Git::Tag for the full-featured tag object with operations
@see
Git::Commands::Tag::Listfor the command that produces these@api public
@!attribute [r] name
@return [String] the tag name (e.g., 'v1.0.0')
@!attribute [r] oid
The object ID of the tag object itself. For annotated tags, this is the tag object's ID. For lightweight tags, this is nil because lightweight tags are not objects in the git database. @return [String, nil] the tag object's ID, or nil for lightweight tags
@!attribute [r] target_oid
The object ID of the commit this tag ultimately points to. For both annotated and lightweight tags, this is the commit ID that the tag resolves to (i.e., the dereferenced target). @return [String] the commit ID this tag points to
@!attribute [r] objecttype
@return [String] 'tag' for annotated tags, 'commit' for lightweight tags
@!attribute [r] tagger_name
@return [String, nil] the tagger's name, or nil for lightweight tags
@!attribute [r] tagger_email
@return [String, nil] the tagger's email, or nil for lightweight tags
@!attribute [r] tagger_date
@return [String, nil] the tag date in ISO 8601 format, or nil for lightweight tags
@!attribute [r] message
@return [String, nil] the tag message, or nil for lightweight tags
- VERSION
-
The current gem version
@return [String] the current gem version
- Version
-
Represents a git version with major, minor, and patch components
Gitversions follow a strict major.minor.patch format. This class provides parsing from git command output (which may include platform suffixes) and comparison operations for version gating.@!attribute [r] major
The major version number @return [Integer]
@!attribute [r] minor
The minor version number @return [Integer]
@!attribute [r] patch
The patch version number @return [Integer]
@example Creating a version directly
version = Git::Version.new(2, 42, 1) version.to_s #=> "2.42.1"
@example Parsing from git version output
Git::Version.parse('git version 2.42.1') #=> Git::Version.new(2, 42, 1) Git::Version.parse('2.39.2 (Apple Git-143)') #=> Git::Version.new(2, 39, 2)
@example Parsing versions with platform suffixes
Git::Version.parse('2.42.0.windows.1') #=> Git::Version.new(2, 42, 0)
@example Comparing versions
Git::Version.new(2, 42, 1) > Git::Version.new(2, 28, 0) #=> true
@api public
- VersionConstraint
-
Represents a git version constraint with minimum and upper bound versions
Used by {Git::Commands::Base.requires_git_version} to declare version requirements and by {Git::VersionError} to report constraint violations.
@example Minimum version only
constraint = Git::VersionConstraint.new(min: Git::Version.parse('2.30.0')) constraint.too_old?(Git::Version.parse('2.28.0')) #=> true constraint.too_new?(Git::Version.parse('2.28.0')) #=> false
@example Upper bound only
constraint = Git::VersionConstraint.new(before: Git::Version.parse('2.50.0')) constraint.too_old?(Git::Version.parse('2.51.0')) #=> false constraint.too_new?(Git::Version.parse('2.51.0')) #=> true
@example Both bounds
constraint = Git::VersionConstraint.new( min: Git::Version.parse('2.30.0'), before: Git::Version.parse('2.50.0') ) constraint.satisfied_by?(Git::Version.parse('2.40.0')) #=> true
@api public
Public Class Methods
Source
# File lib/git.rb, line 754 def self.binary_version(binary_path = nil) binary_path ||= Git::Config.instance.binary_path Git::Deprecation.warn( 'Git.binary_version is deprecated and will be removed in v6.0.0. ' \ 'Use Git.git_version instead, which returns a Git::Version ' \ '(not an Array). For the legacy array shape, call: Git.git_version.to_a. ' \ 'The optional binary_path argument is preserved: Git.git_version(binary_path).' ) git_version(binary_path).to_a end
Return the version of the git binary
@example Basic usage
Git.binary_version # => [2, 46, 0]
@param binary_path [String, nil] path to the git binary; defaults to
`Git::Config.instance.binary_path`
@return [Array<Integer>] the version of the git binary
@deprecated Use {Git.git_version} instead, which returns a
{Git::Version} (not an Array)
For the legacy array shape, call: `Git.git_version.to_a`.
The optional binary_path argument is preserved:
`Git.git_version(binary_path)`.
Source
# File lib/git.rb, line 518 def self.cached_git_version(binary_path, &block) @git_version_cache_mutex.synchronize do @git_version_cache[binary_path] ||= block.call end end
Return the cached git version for the given binary path
If it isn’t already known, compute it using the given block.
@param binary_path [String] the path to the git binary
@return [Git::Version] the git version
@yield [] compute the git version if it is not cached
@yieldreturn [Git::Version] the computed git version
@api private
Source
# File lib/git.rb, line 529 def self.clear_git_version_cache @git_version_cache_mutex.synchronize do @git_version_cache.clear end end
Clear the cached git version for all binary paths
@return [void]
@api private
Source
# File lib/git.rb, line 236 def self.config Git::Config.instance end
Returns the process-wide {Git::Config} singleton
@example Read the configured binary path
Git.config.binary_path #=> "git"
@return [Git::Config] the singleton config object
Source
# File lib/git.rb, line 224 def self.configure yield Git::Config.instance nil end
Configures the gem by yielding {Git::Config.instance} to the block
@example Set the global git binary path
Git.configure { |c| c.binary_path = '/usr/local/bin/git' }
@return [void]
@yield [config] yields the singleton config object
@yieldparam config [Git::Config] the singleton config object
@yieldreturn [void]
Source
# File lib/git.rb, line 164 def self.const_missing(name) return super unless name == :CommandLineResult # Cache the constant first so subsequent accesses are zero-cost even if # the deprecation behavior raises (e.g. in the test suite). const_set(:CommandLineResult, Git::CommandLine::Result) Git::Deprecation.warn( 'Git::CommandLineResult is deprecated and will be removed in v6.0.0. ' \ 'Use Git::CommandLine::Result instead.' ) Git::CommandLine::Result end
Intercept the first lookup of the deprecated ‘Git::CommandLineResult` constant
When ‘name` is `:CommandLineResult`, caches and returns {Git::CommandLine::Result} after emitting a deprecation warning. Calls `super` for any other unknown constant, preserving normal Ruby `NameError` behavior.
@param name [Symbol] the name of the missing constant
@return [Class] the resolved constant value
@api private
Source
# File lib/git.rb, line 313 def self.default_branch(repository, options = {}) context = Git::ExecutionContext::Global.new(logger: options[:log]) output = Git::Commands::LsRemote.new(context).call(repository, 'HEAD', symref: true).stdout Git::Parsers::LsRemote.parse_default_branch(output) end
Returns the name of the default branch of the given repository
@example with a URI string
Git.default_branch('https://github.com/ruby-git/ruby-git') # => 'master' Git.default_branch('https://github.com/rspec/rspec-core') # => 'main'
@example with a URI object
repository_uri = URI('https://github.com/ruby-git/ruby-git') Git.default_branch(repository_uri) # => 'master'
@example with a local repository
Git.default_branch('.') # => 'master'
@example with a local repository Pathname
repository_path = Pathname('.') Git.default_branch(repository_path) # => 'master'
@example with the logging option
logger = Logger.new(STDOUT, level: Logger::INFO) Git.default_branch('.', log: logger) # => 'master' # Logs the executed git command to STDOUT, for example: # I, [2022-04-13T16:01:33.221596 #18415] INFO -- : git '-c' 'core.quotePath=true' # '-c' 'color.ui=false' ls-remote '--symref' '--' '.' 'HEAD' 2>&1
@param repository [URI, Pathname, String] The (possibly remote) repository to get the default branch name for
See [GIT URLS](https://git-scm.com/docs/git-clone#_git_urls_a_id_urls_a) for more information.
@param options [Hash] The options for this command (see list of valid
options below)
@option options [Logger] :log A logger to use for Git operations. Git
commands are logged at the `:info` level. Additional logging is done at the `:debug` level.
@return [String] the name of the default branch
Source
# File lib/git.rb, line 339 def self.export(repository_url, directory = nil, options = {}) options.delete(:remote) repo = clone(repository_url, directory, { depth: 1 }.merge(options)) repo.checkout("origin/#{options[:branch]}") if options[:branch] FileUtils.rm_r File.join(repo.dir.to_s, '.git') end
Clone a repository into ‘directory` then remove its `.git` directory
Exports the current HEAD (or the specific branch given in options[:branch]) into the given ‘directory`. It then removes all traces of git from the directory.
Takes the same options as {Git.clone} except that ‘:remote` is silently ignored and `:depth` defaults to 1.
@param repository_url [String, URI, Pathname] the repository to export from
@param directory [String, Pathname, nil] the directory to export into; defaults to the
repository basename
@param options [Hash] options forwarded to {Git.clone} (‘:remote` is ignored;
`:depth` defaults to 1)
@option options [String] :branch the branch or tag to export instead of HEAD
@return [void]
Source
# File lib/git.rb, line 554 def self.git_version(binary_path = nil) path = binary_path || Git::Config.instance.binary_path cached_git_version(path) { run_git_version(path) } end
Return the version of a git binary as a {Git::Version}
@example Default binary
Git.git_version #=> #<Git::Version 2.42.0>
@example Explicit binary path
Git.git_version('/opt/homebrew/bin/git') #=> #<Git::Version 2.42.0>
@param binary_path [String, nil] path to the git binary; defaults to
`Git::Config.instance.binary_path`
@return [Git::Version] the parsed git version
@raise [Git::UnexpectedResultError] if the version output cannot be parsed
@raise [Git::FailedError] if the git binary exits with a non-zero status
@raise [Git::Error] if the binary is not found or fails to launch
Source
# File lib/git.rb, line 370 def self.global_config(name = nil, value = nil) Git::Deprecation.warn( 'Git.global_config is deprecated and will be removed in v6.0.0. ' \ 'Use Git.config_get(name, global: true), Git.config_set(name, value, global: true), ' \ 'or Git.config_list(global: true) instead.' ) legacy_config_set_get_list(name, value, global: true) end
Get or set a git global configuration value
@example Set a value
Git.global_config('user.name', 'Scott Chacon')
@example Get a value
Git.global_config('user.name') # => 'Scott Chacon'
@example List all global config entries
Git.global_config # => { 'user.name' => 'Scott Chacon', ... }
@param name [String, nil] the config key to get or set; omit to list all
@param value [Object, nil] the value to set; omit to get or list
@return [String, Hash, Git::CommandLine::Result] the config value, all entries,
or the result of the set command
@deprecated Use {Git.config_get}, {Git.config_set}, or {Git.config_list} instead.
- `Git.global_config('user.name')` → `Git.config_get('user.name', global: true)`
- `Git.global_config('user.name', 'Bob')` → `Git.config_set('user.name', 'Bob', global: true)`
- `Git.global_config` → `Git.config_list(global: true)`
Source
# File lib/git.rb, line 466 def self.ls_remote(repository = '.', options = {}) repository = normalize_ls_remote_repository(repository) options = options.dup log = options.delete(:log) unknown = options.keys - LS_REMOTE_ALLOWED_OPTS raise ArgumentError, "Unknown options: #{unknown.join(', ')}" unless unknown.empty? context = Git::ExecutionContext::Global.new(logger: log) output_lines = Git::Commands::LsRemote.new(context).call(repository, **options).stdout.split("\n") Git::Parsers::LsRemote.parse_output(output_lines) end
Displays references available in a remote repository along with the associated commit IDs
@example From a remote repository given its URL
references = Git.ls_remote('https://github.com/user/repo.git')
@example From the default remote of the current repository
references = Git.ls_remote
@example From a specific remote of the current repository
references = Git.ls_remote('origin')
@param repository [String, nil] the target repository location or the name of a remote
Defaults to `'.'` (the current directory). Passing `nil` explicitly is deprecated and will be removed in v6.0.0; pass `'.'` or omit the argument.
@param options [Hash] the options to pass to the git command
@option options [Boolean, nil] :branches (nil) limit output to refs under ‘refs/heads/`
Alias: `:b`
@option options [Boolean, nil] :heads (nil) limit output to refs under ‘refs/heads/`
Deprecated: use `:branches` instead. Kept for backward compatibility with older git versions where `--heads` is the only supported flag. Alias: `:h`
@option options [Boolean, nil] :tags (nil) limit output to refs under ‘refs/tags/`
Alias: `:t`
@option options [Boolean, nil] :refs (nil) exclude peeled tags and pseudorefs
like `HEAD` from the output
@option options [String] :upload_pack (nil) full path to ‘git-upload-pack` on the
remote host Useful when accessing repositories via SSH where the daemon does not use the PATH configured by the user.
@option options [Boolean, nil] :quiet (nil) do not print the remote URL to stderr
Alias: `:q`
@option options [Boolean, nil] :exit_code (nil) exit with status ‘2` when no
matching refs are found in the remote repository Without this option, the command exits `0` whenever it successfully communicates with the remote, even if no refs match.
@option options [String] :sort (nil) sort output by the given key
Prefix `-` for descending order. Supports `"version:refname"` or `"v:refname"`. See `git for-each-ref` for sort key documentation.
@option options [String, Array<String>] :server_option (nil) transmit a string to
the server when communicating using protocol version 2 The string must not contain NUL or LF characters. Repeatable by passing an Array. Alias: `:o`
@option options [Numeric] :timeout (nil) execution timeout in seconds
@option options [Logger] :log (nil) a logger to use for Git operations
Git commands are logged at the `:info` level. Additional logging is done at the `:debug` level.
@return [Hash{String => Hash}] the available references of the target repo
Private Class Methods
Source
# File lib/git.rb, line 729 def self.assert_valid_scope!(**options_to_check) invalid = REPOSITORY_SPECIFIC_SCOPES.select { |s| options_to_check[s] } return if invalid.empty? raise ArgumentError, "#{invalid.join(', ')} scope requires a repository" end
Raises ArgumentError when a repository-specific scope is requested.
The :local, :worktree, and :blob scopes require an active git repository and are therefore not valid at the Git module level.
@param options_to_check [Hash{Symbol => Object}] the scope options to check
If any of the options listed in +REPOSITORY_SPECIFIC_SCOPES+ are present and truthy, an +ArgumentError+ will be raised.
@option options_to_check [Object] :local truthy value requests local scope
@option options_to_check [Object] :worktree truthy value requests worktree scope
@option options_to_check [Object] :blob truthy value requests blob scope
@raise [ArgumentError] if a repository-specific scope is requested
@api private
Source
# File lib/git.rb, line 29 def self.configure_deprecation_behavior(deprecation, behavior) return if behavior.nil? behavior = behavior.strip allowed_behaviors = ActiveSupport::Deprecation::DEFAULT_BEHAVIORS.keys.map(&:to_s) unless allowed_behaviors.include?(behavior) raise ArgumentError, "Invalid GIT_DEPRECATION_BEHAVIOR=#{behavior.inspect}; " \ "expected one of: #{allowed_behaviors.join(', ')}" end deprecation.behavior = behavior.to_sym end
Configure a deprecation instance from a GIT_DEPRECATION_BEHAVIOR value
@param deprecation [ActiveSupport::Deprecation] the deprecation instance to configure
@param behavior [String, nil] the desired behavior name (e.g. ‘’silence’‘); when
`nil` the deprecation instance is left unchanged
@return [void]
@raise [ArgumentError] if ‘behavior` is not one of the keys of
`ActiveSupport::Deprecation::DEFAULT_BEHAVIORS`
@api private
Source
# File lib/git.rb, line 697 def self.execution_context Git::ExecutionContext::Global.new end
@api private
Source
# File lib/git.rb, line 655 def self.legacy_config_get(name, global:) options = global ? { global: true } : {} result = Git::Commands::ConfigOptionSyntax::Get.new(execution_context).call(name, **options) raise Git::FailedError, result if result.status.exitstatus != 0 result.stdout end
Get the value of a git configuration option
@param name [String] the name of the git configuration option
@param global [Boolean] whether to use the global git configuration
@return [String] the value of the git configuration option
@api private
Source
# File lib/git.rb, line 673 def self.legacy_config_list(global:) options = global ? { global: true } : {} output = Git::Commands::ConfigOptionSyntax::List.new(execution_context).call(**options).stdout parse_config_list(output.split("\n")) end
Get a list of all git configuration options
@param global [Boolean] true to use the global git configuration, false for the
local repo config
@return [Hash{String => String}] all git configuration options
@api private
Source
# File lib/git.rb, line 639 def self.legacy_config_set(name, value, global:) options = global ? { global: true } : {} Git::Commands::ConfigOptionSyntax::Set.new(execution_context).call(name, value, **options) end
Set the value of a git configuration option
@param name [String] the name of the git configuration value to set
@param value [String, Boolean] the value to set
@param global [Boolean] whether to use the global git configuration
@api private
Source
# File lib/git.rb, line 618 def self.legacy_config_set_get_list(name, value, global:) if !name.nil? && !value.nil? legacy_config_set(name, value, global:) elsif !name.nil? legacy_config_get(name, global:) else legacy_config_list(global:) end end
Get or set a git config value
@overload legacy_config_set_get_list(name, value, global:)
Set the value of a git configuration option @param name [String] the name of the git configuration value to set @param value [String, Boolean] the value to set @param global [Boolean] true to use the global git configuration, false for the local repo config @return [Git::CommandLine::Result] the result of the git config command
@overload legacy_config_set_get_list(name, global:)
Get the value of a git configuration option @param name [String] the name of the git configuration value to get @param global [Boolean] true to use the global git configuration, false for the local repo config @return [String] the value of the git configuration option
@overload legacy_config_set_get_list(global:)
Get all git configuration options
@param global [Boolean] true to use the global git configuration, false for the
local repo config
@return [Hash{String => String}] all git configuration options
@raise [Git::FailedError] if the git config command fails
@api private
Source
# File lib/git.rb, line 489 def self.normalize_ls_remote_repository(repository) return repository unless repository.nil? Git::Deprecation.warn( 'Passing nil as the repository to Git.ls_remote is deprecated and will ' \ "be removed in v6.0.0. Pass '.' explicitly or omit the argument instead." ) '.' end
Normalize the repository argument for {.ls_remote}
Returns the repository unchanged unless it is nil, in which case a deprecation warning is emitted and ‘’.‘` is returned.
@param repository [String, nil] the repository argument passed by the caller
@return [String] the normalized repository value (‘’.‘` when nil was given)
@api private
Source
# File lib/git.rb, line 688 def self.parse_config_list(lines) lines.each_with_object({}) do |line, hsh| key, value = line.split('=', 2) hsh[key] = value || '' end end
Parse the output of ‘git config –list` into a hash
@param lines [Array<String>] the lines of output from ‘git config –list`
@return [Hash{String => String}] the parsed git configuration options
@api private
Source
# File lib/git.rb, line 573 def self.run_git_version(path) output = Git::Commands::Version.new(Git::ExecutionContext::Global.new(binary_path: path)).call.stdout Git::Version.parse(output) end
Return the version of the git binary
@param path [String] the path to the git binary
@return [Git::Version] the parsed git version
@raise [Git::UnexpectedResultError] if the version output cannot be parsed
@raise [Git::FailedError] if the git binary exits with a non-zero status
@raise [Git::Error] if the binary is not found or fails to launch
@api private
Public Instance Methods
Source
# File lib/git.rb, line 203 def config(name = nil, value = nil) Git::Deprecation.warn( 'Git#config is deprecated and will be removed in v6.0.0. ' \ 'Use Git.config_get(name), Git.config_set(name, value), or Git.config_list instead.' ) Git.__send__(:legacy_config_set_get_list, name, value, global: false) end
Gets or sets local git configuration options
@overload config(name, value)
Set the value for the git named configuration option @param name [String] the name of the git configuration option @param value [String, Boolean] the value to set for the git configuration option @return [Git::CommandLine::Result] the result of the git configuration command
@overload config(name)
Get the value for the git named configuration option @param name [String] the name of the git configuration option @return [String] the value of the git configuration option
@overload config()
List all git configuration options
@return [Hash{String => String}] a hash of all git configuration options
@deprecated Mixing in the ‘Git` module is deprecated and will be removed in v6.0.0.
Use `Git.config_get(name)`, `Git.config_set(name, value)`, or `Git.config_list` instead.
Source
# File lib/git.rb, line 266 def global_config(name = nil, value = nil) Git::Deprecation.warn( 'Git#global_config is deprecated and will be removed in v6.0.0. ' \ 'Use Git.config_get(name, global: true), Git.config_set(name, value, global: true), ' \ 'or Git.config_list(global: true) instead.' ) Git.__send__(:legacy_config_set_get_list, name, value, global: true) end
Gets or sets global git configuration options
@overload global_config(name, value)
Set the value for the git named configuration option @param name [String] the name of the git configuration option @param value [String, Boolean] the value to set for the git configuration option @return [Git::CommandLine::Result] the result of the git configuration command
@overload global_config(name)
Get the value for the git named configuration option @param name [String] the name of the git configuration option @return [String] the value of the git configuration option
@overload global_config()
List all git configuration options
@return [Hash{String => String}] a hash of all git configuration options
@deprecated Mixing in the ‘Git` module is deprecated and will be removed in v6.0.0.
Use `Git.config_get(name, global: true)`, `Git.config_set(name, value, global: true)`, or `Git.config_list(global: true)` instead.