Module: Git

Extended by:
Configuring, Factories
Defined in:
lib/git.rb,
lib/git.rb,
lib/git/log.rb,
lib/git/url.rb,
lib/git/diff.rb,
lib/git/config.rb,
lib/git/errors.rb,
lib/git/object.rb,
lib/git/version.rb,
lib/git/commands.rb,
lib/git/file_ref.rb,
lib/git/tag_info.rb,
lib/git/diff_info.rb,
lib/git/factories.rb,
lib/git/diff_stats.rb,
lib/git/repository.rb,
lib/git/stash_info.rb,
lib/git/author_info.rb,
lib/git/branch_info.rb,
lib/git/commands/am.rb,
lib/git/commands/gc.rb,
lib/git/commands/mv.rb,
lib/git/commands/rm.rb,
lib/git/configuring.rb,
lib/git/diff_result.rb,
lib/git/fsck_object.rb,
lib/git/fsck_result.rb,
lib/git/parsers/tag.rb,
lib/git/remote_info.rb,
lib/git/status_info.rb,
lib/git/command_line.rb,
lib/git/commands/add.rb,
lib/git/commands/log.rb,
lib/git/commands/tag.rb,
lib/git/dirstat_info.rb,
lib/git/escaped_path.rb,
lib/git/parsers/diff.rb,
lib/git/parsers/fsck.rb,
lib/git/parsers/grep.rb,
lib/git/commands/base.rb,
lib/git/commands/diff.rb,
lib/git/commands/fsck.rb,
lib/git/commands/grep.rb,
lib/git/commands/init.rb,
lib/git/commands/pull.rb,
lib/git/commands/push.rb,
lib/git/commands/show.rb,
lib/git/parsers/stash.rb,
lib/git/path_resolver.rb,
lib/git/worktree_info.rb,
lib/git/commands/apply.rb,
lib/git/commands/clean.rb,
lib/git/commands/clone.rb,
lib/git/commands/fetch.rb,
lib/git/commands/merge.rb,
lib/git/commands/reset.rb,
lib/git/commands/stash.rb,
lib/git/encoding_utils.rb,
lib/git/parsers/branch.rb,
lib/git/parsers/remote.rb,
lib/git/parsers/status.rb,
lib/git/commands/branch.rb,
lib/git/commands/commit.rb,
lib/git/commands/remote.rb,
lib/git/commands/repack.rb,
lib/git/commands/revert.rb,
lib/git/commands/status.rb,
lib/git/parsers/ls_tree.rb,
lib/git/commands/am/quit.rb,
lib/git/commands/am/skip.rb,
lib/git/commands/archive.rb,
lib/git/commands/ls_tree.rb,
lib/git/commands/version.rb,
lib/git/diff_path_status.rb,
lib/git/parsers/cat_file.rb,
lib/git/parsers/worktree.rb,
lib/git/status_file_info.rb,
lib/git/command_line/base.rb,
lib/git/commands/am/abort.rb,
lib/git/commands/am/apply.rb,
lib/git/commands/am/retry.rb,
lib/git/commands/cat_file.rb,
lib/git/commands/checkout.rb,
lib/git/commands/describe.rb,
lib/git/commands/ls_files.rb,
lib/git/commands/name_rev.rb,
lib/git/commands/show_ref.rb,
lib/git/commands/tag/list.rb,
lib/git/commands/worktree.rb,
lib/git/config_entry_info.rb,
lib/git/execution_context.rb,
lib/git/parsers/ls_remote.rb,
lib/git/system_call_guard.rb,
lib/git/tag_delete_result.rb,
lib/git/commands/arguments.rb,
lib/git/commands/ls_remote.rb,
lib/git/commands/read_tree.rb,
lib/git/commands/rev_parse.rb,
lib/git/commands/stash/pop.rb,
lib/git/detached_head_info.rb,
lib/git/diff_file_raw_info.rb,
lib/git/repository/diffing.rb,
lib/git/repository/logging.rb,
lib/git/repository/merging.rb,
lib/git/repository/staging.rb,
lib/git/tag_delete_failure.rb,
lib/git/version_constraint.rb,
lib/git/command_line/result.rb,
lib/git/commands/diff_files.rb,
lib/git/commands/diff_index.rb,
lib/git/commands/merge/quit.rb,
lib/git/commands/merge_base.rb,
lib/git/commands/remote/add.rb,
lib/git/commands/stash/drop.rb,
lib/git/commands/stash/list.rb,
lib/git/commands/stash/push.rb,
lib/git/commands/stash/show.rb,
lib/git/commands/tag/create.rb,
lib/git/commands/tag/delete.rb,
lib/git/commands/tag/verify.rb,
lib/git/commands/update_ref.rb,
lib/git/commands/write_tree.rb,
lib/git/repository/stashing.rb,
lib/git/branch_delete_result.rb,
lib/git/commands/am/continue.rb,
lib/git/commands/branch/copy.rb,
lib/git/commands/branch/list.rb,
lib/git/commands/branch/move.rb,
lib/git/commands/commit_tree.rb,
lib/git/commands/maintenance.rb,
lib/git/commands/merge/abort.rb,
lib/git/commands/merge/start.rb,
lib/git/commands/remote/list.rb,
lib/git/commands/remote/show.rb,
lib/git/commands/revert/quit.rb,
lib/git/commands/revert/skip.rb,
lib/git/commands/stash/apply.rb,
lib/git/commands/stash/clear.rb,
lib/git/commands/stash/store.rb,
lib/git/diff_file_patch_info.rb,
lib/git/parsers/config_entry.rb,
lib/git/repository/branching.rb,
lib/git/branch_delete_failure.rb,
lib/git/commands/cat_file/raw.rb,
lib/git/commands/remote/prune.rb,
lib/git/commands/revert/abort.rb,
lib/git/commands/revert/start.rb,
lib/git/commands/stash/branch.rb,
lib/git/commands/stash/create.rb,
lib/git/commands/symbolic_ref.rb,
lib/git/commands/worktree/add.rb,
lib/git/repository/committing.rb,
lib/git/repository/inspecting.rb,
lib/git/command_line/capturing.rb,
lib/git/command_line/streaming.rb,
lib/git/commands/branch/create.rb,
lib/git/commands/branch/delete.rb,
lib/git/commands/remote/remove.rb,
lib/git/commands/remote/rename.rb,
lib/git/commands/remote/update.rb,
lib/git/commands/show_ref/list.rb,
lib/git/commands/worktree/list.rb,
lib/git/commands/worktree/lock.rb,
lib/git/commands/worktree/move.rb,
lib/git/diff_file_numstat_info.rb,
lib/git/repository/maintenance.rb,
lib/git/commands/cat_file/batch.rb,
lib/git/commands/checkout/files.rb,
lib/git/commands/checkout_index.rb,
lib/git/commands/merge/continue.rb,
lib/git/commands/remote/get_url.rb,
lib/git/commands/remote/set_url.rb,
lib/git/commands/worktree/prune.rb,
lib/git/commands/checkout/branch.rb,
lib/git/commands/maintenance/run.rb,
lib/git/commands/remote/set_head.rb,
lib/git/commands/revert/continue.rb,
lib/git/commands/show_ref/exists.rb,
lib/git/commands/show_ref/verify.rb,
lib/git/commands/worktree/remove.rb,
lib/git/commands/worktree/repair.rb,
lib/git/commands/worktree/unlock.rb,
lib/git/execution_context/global.rb,
lib/git/commands/maintenance/stop.rb,
lib/git/commands/update_ref/batch.rb,
lib/git/repository/shared_private.rb,
lib/git/commands/cat_file/filtered.rb,
lib/git/commands/maintenance/start.rb,
lib/git/commands/symbolic_ref/read.rb,
lib/git/commands/update_ref/delete.rb,
lib/git/commands/update_ref/update.rb,
lib/git/repository/context_helpers.rb,
lib/git/commands/remote/set_url_add.rb,
lib/git/commands/branch/set_upstream.rb,
lib/git/commands/branch/show_current.rb,
lib/git/commands/remote/set_branches.rb,
lib/git/commands/symbolic_ref/delete.rb,
lib/git/commands/symbolic_ref/update.rb,
lib/git/execution_context/repository.rb,
lib/git/repository/object_operations.rb,
lib/git/repository/remote_operations.rb,
lib/git/repository/status_operations.rb,
lib/git/commands/archive/list_formats.rb,
lib/git/commands/config_option_syntax.rb,
lib/git/commands/maintenance/register.rb,
lib/git/commands/am/show_current_patch.rb,
lib/git/commands/branch/unset_upstream.rb,
lib/git/commands/remote/set_url_delete.rb,
lib/git/repository/worktree_operations.rb,
lib/git/commands/maintenance/unregister.rb,
lib/git/commands/config_option_syntax/add.rb,
lib/git/commands/config_option_syntax/get.rb,
lib/git/commands/config_option_syntax/set.rb,
lib/git/commands/worktree/management_base.rb,
lib/git/commands/config_option_syntax/list.rb,
lib/git/commands/show_ref/exclude_existing.rb,
lib/git/commands/config_option_syntax/unset.rb,
lib/git/commands/config_option_syntax/get_all.rb,
lib/git/commands/config_option_syntax/get_color.rb,
lib/git/commands/config_option_syntax/unset_all.rb,
lib/git/commands/config_option_syntax/get_regexp.rb,
lib/git/commands/config_option_syntax/replace_all.rb,
lib/git/commands/config_option_syntax/get_urlmatch.rb,
lib/git/commands/config_option_syntax/get_color_bool.rb,
lib/git/commands/config_option_syntax/remove_section.rb,
lib/git/commands/config_option_syntax/rename_section.rb

Overview

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.

Defined Under Namespace

Modules: CommandLine, Commands, Configuring, EncodingUtils, Factories, Parsers, PathResolver Classes: AuthorInfo, BranchDeleteFailure, BranchDeleteResult, BranchInfo, CommandLineError, Config, ConfigEntryInfo, DetachedHeadInfo, Diff, DiffFileNumstatInfo, DiffFilePatchInfo, DiffFileRawInfo, DiffInfo, DiffPathStatus, DiffResult, DiffStats, DirstatEntry, DirstatInfo, Error, EscapedPath, ExecutionContext, FailedError, FileDiffInfo, FileRef, FsckObject, FsckResult, GitAltURI, Log, Object, ProcessIOError, RemoteInfo, Repository, SignaledError, StashInfo, StatusFileInfo, StatusInfo, SystemCallGuard, TagDeleteFailure, TagDeleteResult, TagInfo, TimeoutError, URL, UnexpectedResultError, Version, VersionConstraint, VersionError, WorktreeInfo

Constant Summary collapse

Deprecation =

The deprecation instance used to emit deprecation warnings for the Git gem

ActiveSupport defaults the deprecation horizon to a Rails version, and this gem never interpolates it into a warning: every warning is written by hand per ADR-0007. The horizon is informational only, so it carries the ADR's wording instead of a version that would go stale.

ActiveSupport::Deprecation.new('in a future major release', DeprecationGemName.new('Git'))
MINIMUM_GIT_VERSION =

Minimum git version required by this gem

Commands and features may require newer versions, but this is the absolute minimum supported version for the gem as a whole.

Returns:

Version.parse('2.43.0')
GitExecuteError =
Deprecated.

Use Git::Error instead. Will be removed in a future major release.

An alias for Git::Error

Git::GitExecuteError is an alias for Git::Error kept for backwards compatibility. It is an ActiveSupport::Deprecation::DeprecatedConstantProxy, so any use of it, including instantiating it and matching it in a rescue clause, emits a deprecation warning through Git::Deprecation. The reflective methods that debuggers and IRB call, such as inspect and name, do not warn. It will be removed in a future major release.

ActiveSupport::Deprecation::DeprecatedConstantProxy.new(
  'Git::GitExecuteError', 'Git::Error', Git::Deprecation,
  message: 'Git::GitExecuteError is deprecated and will be removed in a future major release. ' \
           'Use Git::Error instead.'
)
VERSION =

The current gem version

Returns:

  • (String) —

    the current gem version

'6.0.0'
BRANCH_REFNAME_REGEXP =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

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

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

Examples:

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' }
%r{
  \A                                            # start of string
  (?:refs/heads/)?                              # optional refs/heads/ prefix (stripped)
  (?:(?:refs/)?remotes/(?<remote_name>[^/]+)/)? # optional refs?/remotes/<remote_name>/
  (?<branch_name>.+)                            # branch name (everything else)
  \z                                            # end of string
}x

Class Method Summary collapse

Class Method Details

.cached_git_version(binary_path) { ... } ⇒ Git::Version

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Return the cached git version for the given binary path

If it isn't already known, compute it using the given block.

Parameters:

  • binary_path (String) —

    the path to the git binary

Yields:

  • [] compute the git version if it is not cached

Yield Returns:

Returns:



372
373
374
375
376
# File 'lib/git.rb', line 372

def self.cached_git_version(binary_path, &block)
  @git_version_cache_mutex.synchronize do
    @git_version_cache[binary_path] ||= block.call
  end
end

.clear_git_version_cache

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Clear the cached git version for all binary paths



383
384
385
386
387
# File 'lib/git.rb', line 383

def self.clear_git_version_cache
  @git_version_cache_mutex.synchronize do
    @git_version_cache.clear
  end
end

.config ⇒ Git::Config

Returns the process-wide Config singleton

Examples:

Read the configured binary path

Git.config.binary_path  #=> "git"

Returns:



166
167
168
# File 'lib/git.rb', line 166

def self.config
  Git::Config.instance
end

.configure {|config| ... }

This method returns an undefined value.

Configures the gem by yielding Git::Config.instance to the block

Examples:

Set the global git binary path

Git.configure { |c| c.binary_path = '/usr/local/bin/git' }

Yields:

  • (config) —

    yields the singleton config object

Yield Parameters:

Yield Returns:

  • (void)


154
155
156
157
# File 'lib/git.rb', line 154

def self.configure
  yield Git::Config.instance
  nil
end

.default_branch(repository, options = {}) ⇒ String

Returns the name of the default branch of the given repository

Examples:

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'

with a URI object

repository_uri = URI('https://github.com/ruby-git/ruby-git')
Git.default_branch(repository_uri) # => 'master'

with a local repository

Git.default_branch('.') # => 'master'

with a local repository Pathname

repository_path = Pathname('.')
Git.default_branch(repository_path) # => 'master'

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

Parameters:

  • repository (URI, Pathname, String) —

    The (possibly remote) repository to get the default branch name for

    See GIT URLS for more information.

  • options (Hash) (defaults to: {}) —

    The options for this command (see list of valid options below)

Options Hash (options):

  • :log (Logger) —

    A logger to use for Git operations. Git commands are logged at the :info level. Additional logging is done at the :debug level.

Returns:

  • (String) —

    the name of the default branch



208
209
210
211
212
# File 'lib/git.rb', line 208

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

.export(repository_url, directory = nil, options = {})

This method returns an undefined value.

Clone a repository into directory then remove its .git directory

Exports the current HEAD (or the specific branch given in options) into the given directory. It then removes all traces of git from the directory.

Removing .git is not atomic. If it fails, the exported files are complete and usable, but the directory keeps whatever part of .git could not be deleted. Nothing is cleaned up, because the exported files are the deliverable and the leftover has to be removed by hand once the cause of the failure is fixed.

Takes the same options as clone except that :depth defaults to 1.

Parameters:

  • repository_url (String, URI, Pathname) —

    the repository to export from

  • directory (String, Pathname, nil) (defaults to: nil) —

    the directory to export into; defaults to the repository basename

  • options (Hash) (defaults to: {}) —

    options forwarded to clone (:depth defaults to 1)

Options Hash (options):

  • :branch (String) —

    the branch or tag to export instead of HEAD. Give the short name (main, v1.0.0); a full ref path such as refs/tags/v1.0.0 or a commit SHA is not accepted. Use :revision to export a SHA.

Raises:

  • (Git::Error) —

    if the .git directory cannot be removed. The exported files are left in place, and the directory keeps whatever part of .git could not be deleted.



244
245
246
247
248
249
250
251
# File 'lib/git.rb', line 244

def self.export(repository_url, directory = nil, options = {})
  repo = clone(repository_url, directory, { depth: 1 }.merge(options))
  git_dir = File.join(repo.dir.to_s, '.git')
  Git::SystemCallGuard.call(
    "Failed to remove '#{git_dir}'; the exported files are in place, but part of the " \
    'repository remains and has to be removed by hand'
  ) { FileUtils.rm_r(git_dir) }
end

.git_version(binary_path = nil) ⇒ Git::Version

Return the version of a git binary as a Version

Examples:

Default binary

Git.git_version #=> #<Git::Version 2.42.0>

Explicit binary path

Git.git_version('/opt/homebrew/bin/git') #=> #<Git::Version 2.42.0>

Parameters:

  • binary_path (String, nil) (defaults to: nil) —

    path to the git binary; defaults to Git::Config.instance.binary_path

Returns:

Raises:



408
409
410
411
# File 'lib/git.rb', line 408

def self.git_version(binary_path = nil)
  path = binary_path || Git::Config.instance.binary_path
  cached_git_version(path) { run_git_version(path) }
end

.ls_remote(repository = '.', options = {}) ⇒ Hash{String => Hash}

Displays references available in a remote repository along with the associated commit IDs

Examples:

From a remote repository given its URL

references = Git.ls_remote('https://github.com/user/repo.git')

From the default remote of the current repository

references = Git.ls_remote

From a specific remote of the current repository

references = Git.ls_remote('origin')

Parameters:

  • repository (String) (defaults to: '.') —

    the target repository location or the name of a remote

    Defaults to '.' (the current directory). Passing nil raises ArgumentError; pass '.' or omit the argument.

  • options (Hash) (defaults to: {}) —

    the options to pass to the git command

Options Hash (options):

  • :branches (Boolean, nil) — default: nil —

    limit output to refs under refs/heads/

    Alias: :b

  • :heads (Boolean, nil) — default: 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

  • :tags (Boolean, nil) — default: nil —

    limit output to refs under refs/tags/

    Alias: :t

  • :refs (Boolean, nil) — default: nil —

    exclude peeled tags and pseudorefs like HEAD from the output

  • :upload_pack (String) — default: 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.

  • :quiet (Boolean, nil) — default: nil —

    do not print the remote URL to stderr

    Alias: :q

  • :exit_code (Boolean, nil) — default: 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.

  • :sort (String) — default: 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.

  • :server_option (String, Array<String>) — default: 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

  • :timeout (Numeric) — default: nil —

    execution timeout in seconds

  • :log (Logger) — default: nil —

    a logger to use for Git operations

    Git commands are logged at the :info level. Additional logging is done at the :debug level.

Returns:

  • (Hash{String => Hash}) —

    the available references of the target repo

Raises:

  • (ArgumentError) —

    if repository is nil or options contains an unknown key



342
343
344
345
346
347
348
349
350
351
352
353
# File 'lib/git.rb', line 342

def self.ls_remote(repository = '.', options = {})
  raise ArgumentError, 'repository must not be nil' if repository.nil?

  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