Class: Git::Lib Private

Inherits:
Object
  • Object
show all
Defined in:
lib/git/lib.rb

Overview

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

Internal git operations

Defined Under Namespace

Classes: HeadState

Constant Summary collapse

INIT_OPTION_MAP =

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.

[
  { keys: [:bare], flag: '--bare', type: :boolean },
  { keys: [:initial_branch], flag: '--initial-branch', type: :valued_equals }
].freeze
CLONE_OPTION_MAP =

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.

[
  { keys: [:bare],      flag: '--bare',      type: :boolean },
  { keys: [:recursive], flag: '--recursive', type: :boolean },
  { keys: [:mirror],    flag: '--mirror',    type: :boolean },
  { keys: [:branch],    flag: '--branch',    type: :valued_space },
  { keys: [:filter],    flag: '--filter',    type: :valued_space },
  { keys: %i[remote origin], flag: '--origin', type: :valued_space },
  { keys: [:config], flag: '--config', type: :repeatable_valued_space },
  {
    keys: [:single_branch],
    type: :custom,
    validator: ->(value) { [nil, true, false].include?(value) },
    builder: lambda do |value|
      case value
      when true
        ['--single-branch']
      when false
        ['--no-single-branch']
      else
        []
      end
    end
  },
  {
    keys: [:depth],
    type: :custom,
    builder: ->(value) { ['--depth', value.to_i] if value }
  }
].freeze
DESCRIBE_OPTION_MAP =

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.

The map defining how to translate user options to git command arguments.

[
  { keys: [:all], flag: '--all', type: :boolean },
  { keys: [:tags], flag: '--tags', type: :boolean },
  { keys: [:contains], flag: '--contains', type: :boolean },
  { keys: [:debug], flag: '--debug', type: :boolean },
  { keys: [:long], flag: '--long', type: :boolean },
  { keys: [:always], flag: '--always', type: :boolean },
  { keys: %i[exact_match exact-match], flag: '--exact-match', type: :boolean },
  { keys: [:abbrev], flag: '--abbrev', type: :valued_equals },
  { keys: [:candidates], flag: '--candidates', type: :valued_equals },
  { keys: [:match], flag: '--match', type: :valued_equals },
  {
    keys: [:dirty],
    type: :custom,
    builder: lambda do |value|
      return '--dirty' if value == true

      "--dirty=#{value}" if value.is_a?(String)
    end
  }
].freeze
FULL_LOG_EXTRA_OPTIONS_MAP =

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.

[
  { type: :static, flag: '--pretty=raw' },
  { keys: [:skip], flag: '--skip', type: :valued_equals },
  { keys: [:merges], flag: '--merges', type: :boolean }
].freeze
CAT_FILE_HEADER_LINE =

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.

/\A(?<key>\w+) (?<value>.*)\z/
LS_TREE_OPTION_MAP =

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.

[
  { keys: [:recursive], flag: '-r', type: :boolean }
].freeze
BRANCH_LINE_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.

/
  ^
    # Prefix indicates if this branch is checked out. The prefix is one of:
    (?:
      (?<current>\*[[:blank:]]) |  # Current branch (checked out in the current worktree)
      (?<worktree>\+[[:blank:]]) | # Branch checked out in a different worktree
      [[:blank:]]{2}               # Branch not checked out
    )

    # The branch's full refname
    (?:
      (?<not_a_branch>\(not[[:blank:]]a[[:blank:]]branch\)) |
       (?:\(HEAD[[:blank:]]detached[[:blank:]]at[[:blank:]](?<detached_ref>[^)]+)\)) |
      (?<refname>[^[[:blank:]]]+)
    )

    # Optional symref
    # If this ref is a symbolic reference, this is the ref referenced
    (?:
      [[:blank:]]->[[:blank:]](?<symref>.*)
    )?
  $
/x
GREP_OPTION_MAP =

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.

[
  { keys: [:ignore_case],     flag: '-i', type: :boolean },
  { keys: [:invert_match],    flag: '-v', type: :boolean },
  { keys: [:extended_regexp], flag: '-E', type: :boolean },
  # For validation only, as these are handled manually
  { keys: [:object],       type: :validate_only },
  { keys: [:path_limiter], type: :validate_only }
].freeze
DIFF_FULL_OPTION_MAP =

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.

[
  { type: :static, flag: '-p' },
  { keys: [:path_limiter], type: :validate_only }
].freeze
DIFF_STATS_OPTION_MAP =

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.

[
  { type: :static, flag: '--numstat' },
  { keys: [:path_limiter], type: :validate_only }
].freeze
DIFF_PATH_STATUS_OPTION_MAP =

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.

[
  { type: :static, flag: '--name-status' },
  { keys: [:path_limiter], type: :validate_only },
  { keys: [:path], type: :validate_only }
].freeze
LS_REMOTE_OPTION_MAP =

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.

[
  { keys: [:refs], flag: '--refs', type: :boolean }
].freeze
CONFIG_SET_OPTION_MAP =

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.

WRITE COMMANDS ##

[
  { keys: [:file], flag: '--file', type: :valued_space }
].freeze
ADD_OPTION_MAP =

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.

[
  { keys: [:all], flag: '--all', type: :boolean },
  { keys: [:force], flag: '--force', type: :boolean }
].freeze
RM_OPTION_MAP =

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.

[
  { type: :static, flag: '-f' },
  { keys: [:recursive], flag: '-r',       type: :boolean },
  { keys: [:cached],    flag: '--cached', type: :boolean }
].freeze
COMMIT_OPTION_MAP =

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.

[
  { keys: %i[add_all all], flag: '--all', type: :boolean },
  { keys: [:allow_empty],         flag: '--allow-empty',         type: :boolean },
  { keys: [:no_verify],           flag: '--no-verify',           type: :boolean },
  { keys: [:allow_empty_message], flag: '--allow-empty-message', type: :boolean },
  { keys: [:author],              flag: '--author',              type: :valued_equals },
  { keys: [:message],             flag: '--message',             type: :valued_equals },
  { keys: [:no_gpg_sign],         flag: '--no-gpg-sign',         type: :boolean },
  { keys: [:date], flag: '--date', type: :valued_equals, validator: ->(v) { v.is_a?(String) } },
  { keys: [:amend], type: :custom, builder: ->(value) { ['--amend', '--no-edit'] if value } },
  {
    keys: [:gpg_sign],
    type: :custom,
    builder: lambda { |value|
      if value
        value == true ? '--gpg-sign' : "--gpg-sign=#{value}"
      end
    }
  }
].freeze
RESET_OPTION_MAP =

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.

[
  { keys: [:hard], flag: '--hard', type: :boolean }
].freeze
CLEAN_OPTION_MAP =

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.

[
  { keys: [:force], flag: '--force', type: :boolean },
  { keys: [:ff],    flag: '-ff',     type: :boolean },
  { keys: [:d],     flag: '-d',      type: :boolean },
  { keys: [:x],     flag: '-x',      type: :boolean }
].freeze
REVERT_OPTION_MAP =

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.

[
  { keys: [:no_edit], flag: '--no-edit', type: :boolean }
].freeze
CHECKOUT_OPTION_MAP =

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.

[
  { keys: %i[force f],      flag: '--force', type: :boolean },
  { keys: %i[new_branch b], type: :validate_only },
  { keys: [:start_point], type: :validate_only }
].freeze
MERGE_OPTION_MAP =

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.

[
  { keys: [:no_commit], flag: '--no-commit', type: :boolean },
  { keys: [:no_ff],     flag: '--no-ff',     type: :boolean },
  { keys: [:m],         flag: '-m',          type: :valued_space }
].freeze
MERGE_BASE_OPTION_MAP =

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.

[
  { keys: [:octopus],     flag: '--octopus',     type: :boolean },
  { keys: [:independent], flag: '--independent', type: :boolean },
  { keys: [:fork_point],  flag: '--fork-point',  type: :boolean },
  { keys: [:all],         flag: '--all',         type: :boolean }
].freeze
REMOTE_ADD_OPTION_MAP =

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.

[
  { keys: %i[with_fetch fetch], flag: '-f', type: :boolean },
  { keys: [:track], flag: '-t', type: :valued_space }
].freeze
REMOTE_SET_BRANCHES_OPTION_MAP =

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.

[
  { keys: [:add], flag: '--add', type: :boolean }
].freeze
TAG_OPTION_MAP =

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.

[
  { keys: %i[force f],       flag: '-f', type: :boolean },
  { keys: %i[annotate a],    flag: '-a', type: :boolean },
  { keys: %i[sign s],        flag: '-s', type: :boolean },
  { keys: %i[delete d],      flag: '-d', type: :boolean },
  { keys: %i[message m],     flag: '-m', type: :valued_space }
].freeze
FETCH_OPTION_MAP =

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.

[
  { keys: [:all], flag: '--all', type: :boolean },
  { keys: %i[tags t],            flag: '--tags',           type: :boolean },
  { keys: %i[prune p],           flag: '--prune',          type: :boolean },
  { keys: %i[prune-tags P], flag: '--prune-tags', type: :boolean },
  { keys: %i[force f], flag: '--force', type: :boolean },
  { keys: %i[update-head-ok u], flag: '--update-head-ok', type: :boolean },
  { keys: [:unshallow],           flag: '--unshallow',      type: :boolean },
  { keys: [:depth],               flag: '--depth',          type: :valued_space },
  { keys: [:ref],                 type: :validate_only }
].freeze
PUSH_OPTION_MAP =

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.

[
  { keys: [:mirror],      flag: '--mirror',      type: :boolean },
  { keys: [:delete],      flag: '--delete',      type: :boolean },
  { keys: %i[force f], flag: '--force', type: :boolean },
  { keys: [:push_option], flag: '--push-option', type: :repeatable_valued_space },
  { keys: [:all],         type: :validate_only }, # For validation purposes
  { keys: [:tags],        type: :validate_only }  # From the `push` method's logic
].freeze
PULL_OPTION_MAP =

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.

[
  { keys: [:allow_unrelated_histories], flag: '--allow-unrelated-histories', type: :boolean }
].freeze
READ_TREE_OPTION_MAP =

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.

[
  { keys: [:prefix], flag: '--prefix', type: :valued_equals }
].freeze
COMMIT_TREE_OPTION_MAP =

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.

[
  { keys: %i[parent parents], flag: '-p', type: :repeatable_valued_space },
  { keys: [:message], flag: '-m', type: :valued_space }
].freeze
CHECKOUT_INDEX_OPTION_MAP =

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.

[
  { keys: [:prefix], flag: '--prefix', type: :valued_equals },
  { keys: [:force],  flag: '--force',  type: :boolean },
  { keys: [:all],    flag: '--all',    type: :boolean },
  { keys: [:path_limiter], type: :validate_only }
].freeze
ARCHIVE_OPTION_MAP =

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.

[
  { keys: [:prefix],     flag: '--prefix', type: :valued_equals },
  { keys: [:remote],     flag: '--remote', type: :valued_equals },
  # These options are used by helpers or handled manually
  { keys: [:path],       type: :validate_only },
  { keys: [:format],     type: :validate_only },
  { keys: [:add_gzip],   type: :validate_only }
].freeze
COMMAND_ARG_DEFAULTS =

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.

{
  out: nil,
  err: nil,
  normalize: true,
  chomp: true,
  merge: false,
  chdir: nil,
  timeout: nil # Don't set to Git.config.timeout here since it is mutable
}.freeze
STATIC_GLOBAL_OPTS =

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.

%w[
  -c core.quotePath=true
  -c color.ui=false
  -c color.advice=false
  -c color.diff=false
  -c color.grep=false
  -c color.push=false
  -c color.remote=false
  -c color.showBranch=false
  -c color.status=false
  -c color.transport=false
].freeze
LOG_OPTION_MAP =

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.

[
  { type: :static, flag: '--no-color' },
  { keys: [:all],    flag: '--all',    type: :boolean },
  { keys: [:cherry], flag: '--cherry', type: :boolean },
  { keys: [:since],  flag: '--since',     type: :valued_equals },
  { keys: [:until],  flag: '--until',     type: :valued_equals },
  { keys: [:grep],   flag: '--grep',      type: :valued_equals },
  { keys: [:author], flag: '--author',    type: :valued_equals },
  { keys: [:count],  flag: '--max-count', type: :valued_equals },
  { keys: [:between], type: :custom, builder: ->(value) { "#{value[0]}..#{value[1]}" if value } }
].freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(base, logger) ⇒ Lib #initialize(base, logger) ⇒ Lib

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.

Create a new Git::Lib object

Overloads:

  • #initialize(base, logger) ⇒ Lib

    Parameters:

    • base (Hash)

      the hash containing paths to the Git working copy, the Git repository directory, and the Git index file.

    • logger (Logger)

    Options Hash (base):

    • :working_directory (Pathname)
    • :repository (Pathname)
    • :index (Pathname)
  • #initialize(base, logger) ⇒ Lib

    Parameters:

    • base (#dir, #repo, #index)

      an object with methods to get the Git worktree (#dir), the Git repository directory (#repo), and the Git index file (#index).

    • logger (Logger)


66
67
68
69
70
71
72
73
74
75
76
# File 'lib/git/lib.rb', line 66

def initialize(base = nil, logger = nil)
  @logger = logger || Logger.new(nil)
  @git_ssh = :use_global_config

  case base
  when Git::Base
    initialize_from_base(base)
  when Hash
    initialize_from_hash(base)
  end
end

Instance Attribute Details

#git_dirPathname (readonly)

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.

The path to the Git repository directory. The default is "#{git_work_dir}/.git".

Returns:

  • (Pathname)

    the Git repository directory.

See Also:

  • repository](https://git-scm.com/docs/gitglossary#Documentation/gitglossary.txt-aiddefrepositoryarepository)


35
36
37
# File 'lib/git/lib.rb', line 35

def git_dir
  @git_dir
end

#git_index_filePathname (readonly)

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.

The Git index file used to stage changes (using git add) before they are committed.

Returns:

  • (Pathname)

    the Git index file

See Also:

  • index file](https://git-scm.com/docs/gitglossary#Documentation/gitglossary.txt-aiddefindexaindex)


44
45
46
# File 'lib/git/lib.rb', line 44

def git_index_file
  @git_index_file
end

#git_work_dirPathname (readonly)

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.

The path to the Git working copy. The default is '"./.git"'.

Returns:

  • (Pathname)

    the path to the Git working copy.

See Also:

  • working tree](https://git-scm.com/docs/gitglossary#Documentation/gitglossary.txt-aiddefworkingtreeaworkingtree)


26
27
28
# File 'lib/git/lib.rb', line 26

def git_work_dir
  @git_work_dir
end

Class Method Details

.warn_if_old_command(lib)

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.

rubocop:disable Naming/PredicateMethod



1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
# File 'lib/git/lib.rb', line 1639

def self.warn_if_old_command(lib) # rubocop:disable Naming/PredicateMethod
  Git::Deprecation.warn('Git::Lib#warn_if_old_command is deprecated. Use meets_required_version?.')

  return true if @version_checked

  @version_checked = true
  unless lib.meets_required_version?
    warn "[WARNING] The git gem requires git #{lib.required_command_version.join('.')} or later, " \
         "but only found #{lib.current_command_version.join('.')}. You should probably upgrade."
  end
  true
end

Instance Method Details

#add(paths = '.', options = {})

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.

Update the index from the current worktree to prepare the for the next commit

Examples:

lib.add('path/to/file')
lib.add(['path/to/file1','path/to/file2'])
lib.add(:all => true)

Parameters:

  • paths (String, Array<String>) (defaults to: '.')

    files to be added to the repository (relative to the worktree root)

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

Options Hash (options):

  • :all (Boolean)

    Add, modify, and remove index entries to match the worktree

  • :force (Boolean)

    Allow adding otherwise ignored files



1118
1119
1120
1121
1122
1123
1124
1125
# File 'lib/git/lib.rb', line 1118

def add(paths = '.', options = {})
  args = build_args(options, ADD_OPTION_MAP)

  args << '--'
  args.concat(Array(paths))

  command('add', *args)
end

#apply(patch_file)

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.



1240
1241
1242
1243
1244
# File 'lib/git/lib.rb', line 1240

def apply(patch_file)
  arr_opts = []
  arr_opts << '--' << patch_file if patch_file
  command('apply', *arr_opts)
end

#apply_mail(patch_file)

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.



1246
1247
1248
1249
1250
# File 'lib/git/lib.rb', line 1246

def apply_mail(patch_file)
  arr_opts = []
  arr_opts << '--' << patch_file if patch_file
  command('am', *arr_opts)
end

#archive(sha, file = nil, opts = {})

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.



1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
# File 'lib/git/lib.rb', line 1591

def archive(sha, file = nil, opts = {})
  ArgsBuilder.validate!(opts, ARCHIVE_OPTION_MAP)
  file ||= temp_file_name
  format, gzip = parse_archive_format_options(opts)

  args = build_args(opts, ARCHIVE_OPTION_MAP)
  args.unshift("--format=#{format}")
  args << sha
  args.push('--', opts[:path]) if opts[:path]

  File.open(file, 'wb') { |f| command('archive', *args, out: f) }
  apply_gzip(file) if gzip

  file
end

#assert_args_are_not_options(arg_name, *args)

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.

Validate that the given arguments cannot be mistaken for a command-line option

Parameters:

  • arg_name (String)

    the name of the arguments to mention in the error message

  • args (Array<String, nil>)

    the arguments to validate

Raises:

  • (ArgumentError)

    if any of the parameters are a string starting with a hyphen



838
839
840
841
842
843
# File 'lib/git/lib.rb', line 838

def assert_args_are_not_options(arg_name, *args)
  invalid_args = args.select { |arg| arg&.start_with?('-') }
  return unless invalid_args.any?

  raise ArgumentError, "Invalid #{arg_name}: '#{invalid_args.join("', '")}'"
end

#branch_contains(commit, branch_name = '')

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.



799
800
801
# File 'lib/git/lib.rb', line 799

def branch_contains(commit, branch_name = '')
  command('branch',  branch_name, '--contains', commit)
end

#branch_current

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.



794
795
796
797
# File 'lib/git/lib.rb', line 794

def branch_current
  branch_name = command('branch', '--show-current')
  branch_name.empty? ? 'HEAD' : branch_name
end

#branch_delete(branch)

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.



1283
1284
1285
# File 'lib/git/lib.rb', line 1283

def branch_delete(branch)
  command('branch', '-D', branch)
end

#branch_new(branch)

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.



1279
1280
1281
# File 'lib/git/lib.rb', line 1279

def branch_new(branch)
  command('branch', branch)
end

#branches_all

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.



712
713
714
715
716
717
# File 'lib/git/lib.rb', line 712

def branches_all
  lines = command_lines('branch', '-a')
  lines.each_with_index.filter_map do |line, index|
    parse_branch_line(line, index, lines)
  end
end

#cat_file_commit(object) ⇒ Hash Also known as: commit_data

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 a hash of commit data

The returned commit data has the following keys:

  • tree [String]
  • parent [Array]
  • author [String] the author name, email, and commit timestamp
  • committer [String] the committer name, email, and merge timestamp
  • message [String] the commit message
  • gpgsig [String] the public signing key of the commit (if signed)

Parameters:

  • object (String)

    the object to get the type

Returns:

  • (Hash)

    commit data

Raises:

  • (ArgumentError)

    if object is a string starting with a hyphen

See Also:



500
501
502
503
504
505
# File 'lib/git/lib.rb', line 500

def cat_file_commit(object)
  assert_args_are_not_options('object', object)

  cdata = command_lines('cat-file', 'commit', object)
  process_commit_data(cdata, object)
end

#cat_file_contents(object) ⇒ String Also known as: object_contents

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.

Output the contents or other properties of one or more objects.

Examples:

Get the contents of a file without a block

lib.cat_file_contents('README.md') # => "This is a README file\n"

Get the contents of a file with a block

lib.cat_file_contents('README.md') { |f| f.read } # => "This is a README file\n"

Parameters:

  • object (String)

    the object whose contents to return

Returns:

  • (String)

    the object contents

Raises:

  • (ArgumentError)

    if object is a string starting with a hyphen

See Also:



426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
# File 'lib/git/lib.rb', line 426

def cat_file_contents(object)
  assert_args_are_not_options('object', object)

  if block_given?
    Tempfile.create do |file|
      # If a block is given, write the output from the process to a temporary
      # file and then yield the file to the block
      #
      command('cat-file', '-p', object, out: file, err: file)
      file.rewind
      yield file
    end
  else
    # If a block is not given, return the file contents as a string
    command('cat-file', '-p', object)
  end
end

#cat_file_size(object) ⇒ String Also known as: object_size

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.

Get the size for the given object

Parameters:

  • object (String)

    the object to get the type

Returns:

  • (String)

    the object type

Raises:

  • (ArgumentError)

    if object is a string starting with a hyphen

See Also:



474
475
476
477
478
# File 'lib/git/lib.rb', line 474

def cat_file_size(object)
  assert_args_are_not_options('object', object)

  command('cat-file', '-s', object).to_i
end

#cat_file_tag(object) ⇒ Hash Also known as: tag_data

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 a hash of annotated tag data

Does not work with lightweight tags. List all annotated tags in your repository with the following command:

git for-each-ref --format='%(refname:strip=2)' refs/tags | \
  while read tag; do git cat-file tag $tag >/dev/null 2>&1 && echo $tag; done

The returned commit data has the following keys:

  • object [String] the sha of the tag object
  • type [String]
  • tag [String] tag name
  • tagger [String] the name and email of the user who created the tag and the timestamp of when the tag was created
  • message [String] the tag message

Parameters:

  • object (String)

    the tag to retrieve

Returns:

  • (Hash)

    tag data

    Example tag data returned:

    {
      "name" => "annotated_tag",
      "object" => "46abbf07e3c564c723c7c039a43ab3a39e5d02dd",
      "type" => "commit",
      "tag" => "annotated_tag",
      "tagger" => "Scott Chacon <[email protected]> 1724799270 -0700",
      "message" => "Creating an annotated tag\n"
    }
    

Raises:

  • (ArgumentError)

    if object is a string starting with a hyphen

See Also:



569
570
571
572
573
574
# File 'lib/git/lib.rb', line 569

def cat_file_tag(object)
  assert_args_are_not_options('object', object)

  tdata = command_lines('cat-file', 'tag', object)
  process_tag_data(tdata, object)
end

#cat_file_type(object) ⇒ String Also known as: object_type

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.

Get the type for the given object

Parameters:

  • object (String)

    the object to get the type

Returns:

  • (String)

    the object type

Raises:

  • (ArgumentError)

    if object is a string starting with a hyphen

See Also:



456
457
458
459
460
# File 'lib/git/lib.rb', line 456

def cat_file_type(object)
  assert_args_are_not_options('object', object)

  command('cat-file', '-t', object)
end

#change_head_branch(branch_name)

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.



684
685
686
# File 'lib/git/lib.rb', line 684

def change_head_branch(branch_name)
  command('symbolic-ref', 'HEAD', "refs/heads/#{branch_name}")
end

#checkout(branch = nil, opts = {})

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.

Runs checkout command to checkout or create branch

accepts options: :new_branch :force :start_point

Parameters:

  • branch (String) (defaults to: nil)
  • opts (Hash) (defaults to: {})


1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
# File 'lib/git/lib.rb', line 1302

def checkout(branch = nil, opts = {})
  if branch.is_a?(Hash) && opts.empty?
    opts = branch
    branch = nil
  end
  ArgsBuilder.validate!(opts, CHECKOUT_OPTION_MAP)

  flags = build_args(opts, CHECKOUT_OPTION_MAP)
  positional_args = build_checkout_positional_args(branch, opts)

  command('checkout', *flags, *positional_args)
end

#checkout_file(version, file)

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.



1315
1316
1317
1318
1319
1320
# File 'lib/git/lib.rb', line 1315

def checkout_file(version, file)
  arr_opts = []
  arr_opts << version
  arr_opts << file
  command('checkout', *arr_opts)
end

#checkout_index(opts = {})

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.



1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
# File 'lib/git/lib.rb', line 1571

def checkout_index(opts = {})
  ArgsBuilder.validate!(opts, CHECKOUT_INDEX_OPTION_MAP)
  args = build_args(opts, CHECKOUT_INDEX_OPTION_MAP)

  if (path = opts[:path_limiter]) && path.is_a?(String)
    args.push('--', path)
  end

  command('checkout-index', *args)
end

#clean(opts = {})

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.



1221
1222
1223
1224
# File 'lib/git/lib.rb', line 1221

def clean(opts = {})
  args = build_args(opts, CLEAN_OPTION_MAP)
  command('clean', *args)
end

#clone(repository_url, directory, opts = {}) ⇒ Hash

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.

TODO:

make this work with SSH password or auth_key

Clones a repository into a newly created directory

Parameters:

  • repository_url (String)

    the URL of the repository to clone

  • directory (String, nil)

    the directory to clone into

    If nil, the repository is cloned into a directory with the same name as the repository.

  • opts (Hash) (defaults to: {})

    the options for this command

Options Hash (opts):

  • :bare (Boolean) — default: false

    if true, clone as a bare repository

  • :branch (String)

    the branch to checkout

  • :config (String, Array)

    one or more configuration options to set

  • :depth (Integer)

    the number of commits back to pull

  • :filter (String)

    specify partial clone

  • :mirror (String)

    set up a mirror of the source repository

  • :origin (String)

    the name of the remote

  • :path (String)

    an optional prefix for the directory parameter

  • :remote (String)

    the name of the remote

  • :recursive (Boolean)

    after the clone is created, initialize all within, using their default settings

  • :timeout (Numeric, nil)

    the number of seconds to wait for the command to complete

    See #command for more information about :timeout

Returns:

  • (Hash)

    the options to pass to Base.new



166
167
168
169
170
171
172
173
174
175
176
# File 'lib/git/lib.rb', line 166

def clone(repository_url, directory, opts = {})
  @path = opts[:path] || '.'
  clone_dir = opts[:path] ? File.join(@path, directory) : directory

  args = build_args(opts, CLONE_OPTION_MAP)
  args.push('--', repository_url, clone_dir)

  command('clone', *args, timeout: opts[:timeout])

  return_base_opts_from_clone(clone_dir, opts)
end

#commit(message, opts = {})

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.

Takes the commit message with the options and executes the commit command

accepts options: :amend :all :allow_empty :author :date :no_verify :allow_empty_message :gpg_sign (accepts true or a gpg key ID as a String) :no_gpg_sign (conflicts with :gpg_sign)

Parameters:

  • message (String)

    the commit message to be used

  • opts (Hash) (defaults to: {})

    the commit options to be used

Raises:

  • (ArgumentError)


1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
# File 'lib/git/lib.rb', line 1193

def commit(message, opts = {})
  opts[:message] = message if message # Handle message arg for backward compatibility

  # Perform cross-option validation before building args
  raise ArgumentError, 'cannot specify :gpg_sign and :no_gpg_sign' if opts[:gpg_sign] && opts[:no_gpg_sign]

  ArgsBuilder.validate!(opts, COMMIT_OPTION_MAP)

  args = build_args(opts, COMMIT_OPTION_MAP)
  command('commit', *args)
end

#commit_tree(tree, opts = {})

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.



1552
1553
1554
1555
1556
1557
1558
# File 'lib/git/lib.rb', line 1552

def commit_tree(tree, opts = {})
  opts[:message] ||= "commit tree #{tree}"
  ArgsBuilder.validate!(opts, COMMIT_TREE_OPTION_MAP)

  flags = build_args(opts, COMMIT_TREE_OPTION_MAP)
  command('commit-tree', tree, *flags)
end

#compare_version_to(*other_version) ⇒ Integer

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.

Returns current_command_version <=> other_version

Examples:

lib.current_command_version #=> [2, 42, 0]

lib.compare_version_to(2, 41, 0) #=> 1
lib.compare_version_to(2, 42, 0) #=> 0
lib.compare_version_to(2, 43, 0) #=> -1

Parameters:

  • other_version (Array<Object>)

    the other version to compare to

Returns:

  • (Integer)

    -1 if this version is less than other_version, 0 if equal, or 1 if greater than



1627
1628
1629
# File 'lib/git/lib.rb', line 1627

def compare_version_to(*other_version)
  current_command_version <=> other_version
end

#config_get(name)

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.



1042
1043
1044
# File 'lib/git/lib.rb', line 1042

def config_get(name)
  command('config', '--get', name, chdir: @git_dir)
end

#config_list

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.



1050
1051
1052
# File 'lib/git/lib.rb', line 1050

def config_list
  parse_config_list command_lines('config', '--list', chdir: @git_dir)
end

#config_remote(name)

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.



1034
1035
1036
1037
1038
1039
1040
# File 'lib/git/lib.rb', line 1034

def config_remote(name)
  hsh = {}
  config_list.each do |key, value|
    hsh[key.gsub("remote.#{name}.", '')] = value if /remote.#{name}/.match(key)
  end
  hsh
end

#config_set(name, value, options = {})

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.



1090
1091
1092
1093
1094
# File 'lib/git/lib.rb', line 1090

def config_set(name, value, options = {})
  ArgsBuilder.validate!(options, CONFIG_SET_OPTION_MAP)
  flags = build_args(options, CONFIG_SET_OPTION_MAP)
  command('config', *flags, name, value)
end

#conflicts

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.

:yields: file, your, their



1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
# File 'lib/git/lib.rb', line 1364

def conflicts # :yields: file, your, their
  unmerged.each do |file_path|
    Tempfile.create(['YOUR-', File.basename(file_path)]) do |your_file|
      write_staged_content(file_path, 2, your_file).flush

      Tempfile.create(['THEIR-', File.basename(file_path)]) do |their_file|
        write_staged_content(file_path, 3, their_file).flush
        yield(file_path, your_file.path, their_file.path)
      end
    end
  end
end

#current_branch_stateHeadState

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.

The current branch state which is the state of HEAD

Returns:

  • (HeadState)

    the state and name of the current branch



786
787
788
789
790
791
792
# File 'lib/git/lib.rb', line 786

def current_branch_state
  branch_name = command('branch', '--show-current')
  return HeadState.new(:detached, 'HEAD') if branch_name.empty?

  state = get_branch_state(branch_name)
  HeadState.new(state, branch_name)
end

#current_command_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.

returns the current version of git, as an Array of Fixnums.



1608
1609
1610
1611
1612
1613
# File 'lib/git/lib.rb', line 1608

def current_command_version
  output = command('version')
  version = output[/\d+(\.\d+)+/]
  version_parts = version.split('.').collect(&:to_i)
  version_parts.fill(0, version_parts.length...3)
end

#describe(commit_ish = nil, opts = {}) ⇒ String

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.

Finds most recent tag that is reachable from a commit

Parameters:

  • commit_ish (String, nil) (defaults to: nil)

    target commit sha or object name

  • opts (Hash) (defaults to: {})

    the given options

Options Hash (opts):

  • :all (Boolean)
  • :tags (Boolean)
  • :contains (Boolean)
  • :debug (Boolean)
  • :long (Boolean)
  • :always (Boolean)
  • :exact_match (Boolean)
  • :dirty (true, String)
  • :abbrev (String)
  • :candidates (String)
  • :match (String)

Returns:

  • (String)

    the tag name

Raises:

  • (ArgumentError)

    if the commit_ish is a string starting with a hyphen

See Also:



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

def describe(commit_ish = nil, opts = {})
  assert_args_are_not_options('commit-ish object', commit_ish)

  args = build_args(opts, DESCRIBE_OPTION_MAP)
  args << commit_ish if commit_ish

  command('describe', *args)
end

#diff_files

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.

compares the index and the working directory



953
954
955
# File 'lib/git/lib.rb', line 953

def diff_files
  diff_as_hash('diff-files')
end

#diff_full(obj1 = 'HEAD', obj2 = nil, opts = {})

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.



897
898
899
900
901
902
903
904
905
906
907
908
909
# File 'lib/git/lib.rb', line 897

def diff_full(obj1 = 'HEAD', obj2 = nil, opts = {})
  assert_args_are_not_options('commit or commit range', obj1, obj2)
  ArgsBuilder.validate!(opts, DIFF_FULL_OPTION_MAP)

  args = build_args(opts, DIFF_FULL_OPTION_MAP)
  args.push(obj1, obj2).compact!

  if (pathspecs = normalize_pathspecs(opts[:path_limiter], 'path limiter'))
    args.push('--', *pathspecs)
  end

  command('diff', *args)
end

#diff_index(treeish)

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.

compares the index and the repository



958
959
960
# File 'lib/git/lib.rb', line 958

def diff_index(treeish)
  diff_as_hash('diff-index', treeish)
end

#diff_path_status(reference1 = nil, reference2 = nil, opts = {})

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.



937
938
939
940
941
942
943
944
945
946
947
948
949
950
# File 'lib/git/lib.rb', line 937

def diff_path_status(reference1 = nil, reference2 = nil, opts = {})
  assert_args_are_not_options('commit or commit range', reference1, reference2)
  ArgsBuilder.validate!(opts, DIFF_PATH_STATUS_OPTION_MAP)

  args = build_args(opts, DIFF_PATH_STATUS_OPTION_MAP)
  args.push(reference1, reference2).compact!

  path_limiter = handle_deprecated_path_option(opts)
  if (pathspecs = normalize_pathspecs(path_limiter, 'path limiter'))
    args.push('--', *pathspecs)
  end

  parse_diff_path_status(args)
end

#diff_stats(obj1 = 'HEAD', obj2 = nil, opts = {})

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.



916
917
918
919
920
921
922
923
924
925
926
927
928
929
# File 'lib/git/lib.rb', line 916

def diff_stats(obj1 = 'HEAD', obj2 = nil, opts = {})
  assert_args_are_not_options('commit or commit range', obj1, obj2)
  ArgsBuilder.validate!(opts, DIFF_STATS_OPTION_MAP)

  args = build_args(opts, DIFF_STATS_OPTION_MAP)
  args.push(obj1, obj2).compact!

  if (pathspecs = normalize_pathspecs(opts[:path_limiter], 'path limiter'))
    args.push('--', *pathspecs)
  end

  output_lines = command_lines('diff', *args)
  parse_diff_stats_output(output_lines)
end

#each_cat_file_header(data)

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.



520
521
522
523
524
525
526
527
528
529
# File 'lib/git/lib.rb', line 520

def each_cat_file_header(data)
  while (match = CAT_FILE_HEADER_LINE.match(data.shift))
    key = match[:key]
    value_lines = [match[:value]]

    value_lines << data.shift.lstrip while data.first.start_with?(' ')

    yield key, value_lines.join("\n")
  end
end

#empty?Boolean

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.

Returns true if the repository is empty (meaning it has no commits)

Returns:

  • (Boolean)


1146
1147
1148
1149
1150
1151
1152
1153
1154
# File 'lib/git/lib.rb', line 1146

def empty?
  command('rev-parse', '--verify', 'HEAD')
  false
rescue Git::FailedError => e
  raise unless e.result.status.exitstatus == 128 &&
               e.result.stderr == 'fatal: Needed a single revision'

  true
end

#fetch(remote, opts)

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.



1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
# File 'lib/git/lib.rb', line 1459

def fetch(remote, opts)
  ArgsBuilder.validate!(opts, FETCH_OPTION_MAP)
  args = build_args(opts, FETCH_OPTION_MAP)

  if remote || opts[:ref]
    args << '--'
    args << remote if remote
    args << opts[:ref] if opts[:ref]
  end

  command('fetch', *args, merge: true)
end

#full_log_commits(opts = {}) ⇒ Array<Hash>

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 commits that are within the given revision range

Parameters:

  • opts (Hash) (defaults to: {})

    the given options

Options Hash (opts):

  • :count (Integer)

    the maximum number of commits to return (maps to max-count)

  • :all (Boolean)
  • :cherry (Boolean)
  • :since (String)
  • :until (String)
  • :grep (String)
  • :author (String)
  • :between (Array<String>)

    an array of two commit-ish strings to specify a revision range

    Only :between or :object options can be used, not both.

  • :object (String)

    the revision range for the git log command

    Only :between or :object options can be used, not both.

  • :path_limiter (String, Pathname, Array<String, Pathname>)

    only include commits that impact files from the specified paths

  • :skip (Integer)

Returns:

  • (Array<Hash>)

    the log output parsed into an array of hashs for each commit

    Each hash contains the following keys:

    • 'sha' [String] the commit sha
    • 'author' [String] the author of the commit
    • 'message' [String] the commit message
    • 'parent' [Array] the commit shas of the parent commits
    • 'tree' [String] the tree sha
    • 'author' [String] the author of the commit and timestamp of when the changes were created
    • 'committer' [String] the committer of the commit and timestamp of when the commit was applied
    • 'merges' [Boolean] if truthy, only include merge commits (aka commits with 2 or more parents)

Raises:

  • (ArgumentError)

    if the revision range (specified with :between or :object) is a string starting with a hyphen

See Also:



355
356
357
358
359
360
361
362
363
364
365
# File 'lib/git/lib.rb', line 355

def full_log_commits(opts = {})
  assert_args_are_not_options('between', opts[:between]&.first)
  assert_args_are_not_options('object', opts[:object])

  args = log_common_options(opts)
  args += build_args(opts, FULL_LOG_EXTRA_OPTIONS_MAP)
  args += log_path_options(opts)

  full_log = command_lines('log', *args)
  process_commit_log_data(full_log)
end

#full_tree(sha)

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.



676
677
678
# File 'lib/git/lib.rb', line 676

def full_tree(sha)
  command_lines('ls-tree', '-r', sha)
end

#gc

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.



1529
1530
1531
# File 'lib/git/lib.rb', line 1529

def gc
  command('gc', '--prune', '--aggressive', '--auto')
end

#global_config_get(name)

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.



1046
1047
1048
# File 'lib/git/lib.rb', line 1046

def global_config_get(name)
  command('config', '--global', '--get', name)
end

#global_config_list

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.



1054
1055
1056
# File 'lib/git/lib.rb', line 1054

def global_config_list
  parse_config_list command_lines('config', '--global', '--list')
end

#global_config_set(name, value)

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.



1096
1097
1098
# File 'lib/git/lib.rb', line 1096

def global_config_set(name, value)
  command('config', '--global', name, value)
end

#grep(string, opts = {})

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.

returns hash [tree-ish] = [[line_no, match], [line_no, match2]] [tree-ish] = [[line_no, match], [line_no, match2]]



815
816
817
818
819
820
821
822
823
824
825
826
827
828
# File 'lib/git/lib.rb', line 815

def grep(string, opts = {})
  opts[:object] ||= 'HEAD'
  ArgsBuilder.validate!(opts, GREP_OPTION_MAP)

  boolean_flags = build_args(opts, GREP_OPTION_MAP)
  args = ['-n', *boolean_flags, '-e', string, opts[:object]]

  if (limiter = opts[:path_limiter])
    args.push('--', *Array(limiter))
  end

  lines = execute_grep_command(args)
  parse_grep_output(lines)
end

#handle_deprecated_path_option(opts)

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.

Handle deprecated :path option in favor of :path_limiter



881
882
883
884
885
886
887
888
889
890
# File 'lib/git/lib.rb', line 881

def handle_deprecated_path_option(opts)
  if opts.key?(:path_limiter)
    opts[:path_limiter]
  elsif opts.key?(:path)
    Git::Deprecation.warn(
      'Git::Lib#diff_path_status :path option is deprecated. Use :path_limiter instead.'
    )
    opts[:path]
  end
end

#ignored_files

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.



1024
1025
1026
# File 'lib/git/lib.rb', line 1024

def ignored_files
  command_lines('ls-files', '--others', '-i', '--exclude-standard').map { |f| unescape_quoted_path(f) }
end

#init(opts = {})

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.

creates or reinitializes the repository

options: :bare :working_directory :initial_branch



90
91
92
93
# File 'lib/git/lib.rb', line 90

def init(opts = {})
  args = build_args(opts, INIT_OPTION_MAP)
  command('init', *args)
end

#list_files(ref_dir)

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.



753
754
755
756
# File 'lib/git/lib.rb', line 753

def list_files(ref_dir)
  dir = File.join(@git_dir, 'refs', ref_dir)
  Dir.glob('**/*', base: dir).select { |f| File.file?(File.join(dir, f)) }
end

#log_commits(opts = {}) ⇒ Array<String>

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 commits that are within the given revision range

Parameters:

  • opts (Hash) (defaults to: {})

    the given options

Options Hash (opts):

  • :count (Integer)

    the maximum number of commits to return (maps to max-count)

  • :all (Boolean)
  • :cherry (Boolean)
  • :since (String)
  • :until (String)
  • :grep (String)
  • :author (String)
  • :between (Array<String>)

    an array of two commit-ish strings to specify a revision range

    Only :between or :object options can be used, not both.

  • :object (String)

    the revision range for the git log command

    Only :between or :object options can be used, not both.

  • :path_limiter (String, Pathname, Array<String, Pathname>)

    only include commits that impact files from the specified paths

Returns:

  • (Array<String>)

    the log output

Raises:

  • (ArgumentError)

    if the resulting revision range is a string starting with a hyphen

See Also:



282
283
284
285
286
287
288
289
290
291
292
293
# File 'lib/git/lib.rb', line 282

def log_commits(opts = {})
  assert_args_are_not_options('between', opts[:between]&.first)
  assert_args_are_not_options('object', opts[:object])

  arr_opts = log_common_options(opts)

  arr_opts << '--pretty=oneline'

  arr_opts += log_path_options(opts)

  command_lines('log', *arr_opts).map { |l| l.split.first }
end

#ls_files(location = nil) ⇒ Hash<String, Hash>

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.

List all files that are in the index

Parameters:

  • location (String) (defaults to: nil)

    the location to list the files from

Returns:

  • (Hash<String, Hash>)

    a hash of files in the index

    • key: file [String] the file path
    • value: file_info [Hash] the file information containing the following keys:
      • :path [String] the file path
      • :mode_index [String] the file mode
      • :sha_index [String] the file sha
      • :stage [String] the file stage


974
975
976
977
978
979
980
981
982
983
984
985
# File 'lib/git/lib.rb', line 974

def ls_files(location = nil)
  location ||= '.'
  {}.tap do |files|
    command_lines('ls-files', '--stage', location).each do |line|
      (info, file) = split_status_line(line)
      (mode, sha, stage) = info.split
      files[file] = {
        path: file, mode_index: mode, sha_index: sha, stage: stage
      }
    end
  end
end

#ls_remote(location = nil, opts = {})

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.



1014
1015
1016
1017
1018
1019
1020
1021
1022
# File 'lib/git/lib.rb', line 1014

def ls_remote(location = nil, opts = {})
  ArgsBuilder.validate!(opts, LS_REMOTE_OPTION_MAP)

  flags = build_args(opts, LS_REMOTE_OPTION_MAP)
  positional_arg = location || '.'

  output_lines = command_lines('ls-remote', *flags, positional_arg)
  parse_ls_remote_output(output_lines)
end

#ls_tree(sha, opts = {})

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.



656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
# File 'lib/git/lib.rb', line 656

def ls_tree(sha, opts = {})
  data = { 'blob' => {}, 'tree' => {}, 'commit' => {} }
  args = build_args(opts, LS_TREE_OPTION_MAP)

  args.unshift(sha)
  args << opts[:path] if opts[:path]

  command_lines('ls-tree', *args).each do |line|
    (info, filenm) = split_status_line(line)
    (mode, type, sha) = info.split
    data[type][filenm] = { mode: mode, sha: sha }
  end

  data
end

#meets_required_version?Boolean

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.

Returns:

  • (Boolean)


1635
1636
1637
# File 'lib/git/lib.rb', line 1635

def meets_required_version?
  (current_command_version <=> required_command_version) >= 0
end

#merge(branch, message = nil, opts = {})

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.



1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
# File 'lib/git/lib.rb', line 1328

def merge(branch, message = nil, opts = {})
  # For backward compatibility, treat the message arg as the :m option.
  opts[:m] = message if message
  ArgsBuilder.validate!(opts, MERGE_OPTION_MAP)

  args = build_args(opts, MERGE_OPTION_MAP)
  args.concat(Array(branch))

  command('merge', *args)
end

#merge_base(*args)

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.



1346
1347
1348
1349
1350
1351
1352
1353
1354
# File 'lib/git/lib.rb', line 1346

def merge_base(*args)
  opts = args.last.is_a?(Hash) ? args.pop : {}
  ArgsBuilder.validate!(opts, MERGE_BASE_OPTION_MAP)

  flags = build_args(opts, MERGE_BASE_OPTION_MAP)
  command_args = flags + args

  command('merge-base', *command_args).lines.map(&:strip)
end

#mv(file1, file2)

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.



672
673
674
# File 'lib/git/lib.rb', line 672

def mv(file1, file2)
  command_lines('mv', '--', file1, file2)
end

#name_rev(commit_ish) ⇒ String? Also known as: namerev

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.

Find the first symbolic name for given commit_ish

Parameters:

  • commit_ish (String)

    the commit_ish to find the symbolic name of

Returns:

  • (String, nil)

    the first symbolic name or nil if the commit_ish isn't found

Raises:

  • (ArgumentError)

    if the commit_ish is a string starting with a hyphen



402
403
404
405
406
# File 'lib/git/lib.rb', line 402

def name_rev(commit_ish)
  assert_args_are_not_options('commit_ish', commit_ish)

  command('name-rev', commit_ish).split[1]
end

#normalize_pathspecs(pathspecs, arg_name) ⇒ Array<String>?

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.

Normalizes path specifications for Git commands

Converts a single path or array of paths into a consistent array format suitable for appending to Git command arguments after '--'. Empty strings are filtered out after conversion.

Parameters:

  • pathspecs (String, Pathname, Array<String, Pathname>, nil)

    path(s) to normalize

  • arg_name (String)

    name of the argument for error messages

Returns:

  • (Array<String>, nil)

    normalized array of path strings, or nil if empty/nil input

Raises:

  • (ArgumentError)

    if any path is not a String or Pathname



856
857
858
859
860
861
862
863
864
865
866
# File 'lib/git/lib.rb', line 856

def normalize_pathspecs(pathspecs, arg_name)
  return nil unless pathspecs

  normalized = Array(pathspecs)
  validate_pathspec_types(normalized, arg_name)

  normalized = normalized.map(&:to_s).reject(&:empty?)
  return nil if normalized.empty?

  normalized
end

#parse_config(file)

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.



1067
1068
1069
# File 'lib/git/lib.rb', line 1067

def parse_config(file)
  parse_config_list command_lines('config', '--list', '--file', file)
end

#parse_config_list(lines)

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.



1058
1059
1060
1061
1062
1063
1064
1065
# File 'lib/git/lib.rb', line 1058

def parse_config_list(lines)
  hsh = {}
  lines.each do |line|
    (key, *values) = line.split('=')
    hsh[key] = values.join('=')
  end
  hsh
end

#process_commit_data(data, sha)

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.



509
510
511
512
513
514
515
516
# File 'lib/git/lib.rb', line 509

def process_commit_data(data, sha)
  # process_commit_headers consumes the header lines from the `data` array,
  # leaving only the message lines behind.
  headers = process_commit_headers(data)
  message = "#{data.join("\n")}\n"

  { 'sha' => sha, 'message' => message }.merge(headers)
end

#process_commit_log_data(data)

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.



590
591
592
# File 'lib/git/lib.rb', line 590

def process_commit_log_data(data)
  RawLogParser.new(data).parse
end

#process_tag_data(data, name)

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.



578
579
580
581
582
583
584
585
586
587
588
# File 'lib/git/lib.rb', line 578

def process_tag_data(data, name)
  hsh = { 'name' => name }

  each_cat_file_header(data) do |key, value|
    hsh[key] = value
  end

  hsh['message'] = "#{data.join("\n")}\n"

  hsh
end

#pull(remote = nil, branch = nil, opts = {})

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.

Raises:

  • (ArgumentError)


1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
# File 'lib/git/lib.rb', line 1501

def pull(remote = nil, branch = nil, opts = {})
  raise ArgumentError, 'You must specify a remote if a branch is specified' if remote.nil? && !branch.nil?

  ArgsBuilder.validate!(opts, PULL_OPTION_MAP)

  flags = build_args(opts, PULL_OPTION_MAP)
  positional_args = [remote, branch].compact

  command('pull', *flags, *positional_args)
end

#push(remote = nil, branch = nil, opts = nil)

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.

Raises:

  • (ArgumentError)


1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
# File 'lib/git/lib.rb', line 1481

def push(remote = nil, branch = nil, opts = nil)
  remote, branch, opts = normalize_push_args(remote, branch, opts)
  ArgsBuilder.validate!(opts, PUSH_OPTION_MAP)

  raise ArgumentError, 'remote is required if branch is specified' if !remote && branch

  args = build_push_args(remote, branch, opts)

  if opts[:mirror]
    command('push', *args)
  else
    command('push', *args)
    command('push', '--tags', *(args - [branch].compact)) if opts[:tags]
  end
end

#read_tree(treeish, opts = {})

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.



1537
1538
1539
1540
1541
# File 'lib/git/lib.rb', line 1537

def read_tree(treeish, opts = {})
  ArgsBuilder.validate!(opts, READ_TREE_OPTION_MAP)
  flags = build_args(opts, READ_TREE_OPTION_MAP)
  command('read-tree', *flags, treeish)
end

#remote_add(name, url, opts = {})

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.



1382
1383
1384
1385
1386
1387
1388
1389
1390
# File 'lib/git/lib.rb', line 1382

def remote_add(name, url, opts = {})
  ArgsBuilder.validate!(opts, REMOTE_ADD_OPTION_MAP)

  flags = build_args(opts, REMOTE_ADD_OPTION_MAP)
  positional_args = ['--', name, url]
  command_args = ['add'] + flags + positional_args

  command('remote', *command_args)
end

#remote_remove(name)

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.



1414
1415
1416
# File 'lib/git/lib.rb', line 1414

def remote_remove(name)
  command('remote', 'rm', name)
end

#remote_set_branches(name, branches, opts = {})

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.



1396
1397
1398
1399
1400
1401
1402
1403
1404
# File 'lib/git/lib.rb', line 1396

def remote_set_branches(name, branches, opts = {})
  ArgsBuilder.validate!(opts, REMOTE_SET_BRANCHES_OPTION_MAP)

  flags = build_args(opts, REMOTE_SET_BRANCHES_OPTION_MAP)
  branch_args = Array(branches).flatten
  command_args = ['set-branches'] + flags + [name] + branch_args

  command('remote', *command_args)
end

#remote_set_url(name, url)

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.



1406
1407
1408
1409
1410
1411
1412
# File 'lib/git/lib.rb', line 1406

def remote_set_url(name, url)
  arr_opts = ['set-url']
  arr_opts << name
  arr_opts << url

  command('remote', *arr_opts)
end

#remotes

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.



1418
1419
1420
# File 'lib/git/lib.rb', line 1418

def remotes
  command_lines('remote')
end

#repack

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.



1525
1526
1527
# File 'lib/git/lib.rb', line 1525

def repack
  command('repack', '-a', '-d')
end

#repository_default_branch(repository) ⇒ String

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.

Returns the name of the default branch of the given repository

Parameters:

  • repository (URI, Pathname, String)

    The (possibly remote) repository to clone from

Returns:

  • (String)

    the name of the default branch

Raises:



184
185
186
187
188
189
190
191
192
193
194
# File 'lib/git/lib.rb', line 184

def repository_default_branch(repository)
  output = command('ls-remote', '--symref', '--', repository, 'HEAD')

  match_data = output.match(%r{^ref: refs/remotes/origin/(?<default_branch>[^\t]+)\trefs/remotes/origin/HEAD$})
  return match_data[:default_branch] if match_data

  match_data = output.match(%r{^ref: refs/heads/(?<default_branch>[^\t]+)\tHEAD$})
  return match_data[:default_branch] if match_data

  raise Git::UnexpectedResultError, 'Unable to determine the default branch'
end

#required_command_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.



1631
1632
1633
# File 'lib/git/lib.rb', line 1631

def required_command_version
  [2, 28]
end

#reset(commit, opts = {})

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.



1208
1209
1210
1211
1212
# File 'lib/git/lib.rb', line 1208

def reset(commit, opts = {})
  args = build_args(opts, RESET_OPTION_MAP)
  args << commit if commit
  command('reset', *args)
end

#rev_parse(revision) ⇒ String Also known as: revparse

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.

Verify and resolve a Git revision to its full SHA

Examples:

lib.rev_parse('HEAD') # => '9b9b31e704c0b85ffdd8d2af2ded85170a5af87d'
lib.rev_parse('9b9b31e') # => '9b9b31e704c0b85ffdd8d2af2ded85170a5af87d'

Parameters:

  • revision (String)

    the revision to resolve

Returns:

  • (String)

    the full commit hash

Raises:

  • (Git::FailedError)

    if the revision cannot be resolved

  • (ArgumentError)

    if the revision is a string starting with a hyphen

See Also:



385
386
387
388
389
# File 'lib/git/lib.rb', line 385

def rev_parse(revision)
  assert_args_are_not_options('rev', revision)

  command('rev-parse', '--revs-only', '--end-of-options', revision, '--')
end

#revert(commitish, opts = {})

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.



1230
1231
1232
1233
1234
1235
1236
1237
1238
# File 'lib/git/lib.rb', line 1230

def revert(commitish, opts = {})
  # Forcing --no-edit as default since it's not an interactive session.
  opts = { no_edit: true }.merge(opts)

  args = build_args(opts, REVERT_OPTION_MAP)
  args << commitish

  command('revert', *args)
end

#rm(path = '.', opts = {})

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.



1133
1134
1135
1136
1137
1138
1139
1140
# File 'lib/git/lib.rb', line 1133

def rm(path = '.', opts = {})
  args = build_args(opts, RM_OPTION_MAP)

  args << '--'
  args.concat(Array(path))

  command('rm', *args)
end

#show(objectish = nil, path = nil) ⇒ String

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.

Shows objects

Parameters:

  • objectish (String|NilClass) (defaults to: nil)

    the target object reference (nil == HEAD)

  • path (String|NilClass) (defaults to: nil)

    the path of the file to be shown

Returns:

  • (String)

    the object information



1076
1077
1078
1079
1080
1081
1082
# File 'lib/git/lib.rb', line 1076

def show(objectish = nil, path = nil)
  arr_opts = []

  arr_opts << (path ? "#{objectish}:#{path}" : objectish)

  command('show', *arr_opts.compact, chomp: false)
end

#stash_apply(id = nil)

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.



1263
1264
1265
1266
1267
1268
1269
# File 'lib/git/lib.rb', line 1263

def stash_apply(id = nil)
  if id
    command('stash', 'apply', id)
  else
    command('stash', 'apply')
  end
end

#stash_clear

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.



1271
1272
1273
# File 'lib/git/lib.rb', line 1271

def stash_clear
  command('stash', 'clear')
end

#stash_list

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.



1275
1276
1277
# File 'lib/git/lib.rb', line 1275

def stash_list
  command('stash', 'list')
end

#stash_save(message)

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.



1258
1259
1260
1261
# File 'lib/git/lib.rb', line 1258

def stash_save(message)
  output = command('stash', 'save', message)
  output =~ /HEAD is now at/
end

#stashes_all

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.



1252
1253
1254
1255
1256
# File 'lib/git/lib.rb', line 1252

def stashes_all
  stash_log_lines.each_with_index.map do |line, index|
    parse_stash_log_line(line, index)
  end
end

#tag(name, *args)

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.



1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
# File 'lib/git/lib.rb', line 1434

def tag(name, *args)
  opts = args.last.is_a?(Hash) ? args.pop : {}
  target = args.first

  validate_tag_options!(opts)
  ArgsBuilder.validate!(opts, TAG_OPTION_MAP)

  flags = build_args(opts, TAG_OPTION_MAP)
  positional_args = [name, target].compact

  command('tag', *flags, *positional_args)
end

#tag_sha(tag_name)

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.



1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
# File 'lib/git/lib.rb', line 1512

def tag_sha(tag_name)
  head = File.join(@git_dir, 'refs', 'tags', tag_name)
  return File.read(head).chomp if File.exist?(head)

  begin
    command('show-ref', '--tags', '-s', tag_name)
  rescue Git::FailedError => e
    raise unless e.result.status.exitstatus == 1 && e.result.stderr == ''

    ''
  end
end

#tags

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.



1422
1423
1424
# File 'lib/git/lib.rb', line 1422

def tags
  command_lines('tag')
end

#tree_depth(sha)

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.



680
681
682
# File 'lib/git/lib.rb', line 680

def tree_depth(sha)
  full_tree(sha).size
end

#unescape_quoted_path(path) ⇒ String

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.

Unescape a path if it is quoted

Git commands that output paths (e.g. ls-files, diff), will escape unusual characters.

Examples:

lib.unescape_if_quoted('"quoted_file_\\342\\230\\240"') # => 'quoted_file_☠'
lib.unescape_if_quoted('unquoted_file')   # => 'unquoted_file'

Parameters:

  • path (String)

    the path to unescape if quoted

Returns:

  • (String)

    the unescaped path if quoted otherwise the original path



1002
1003
1004
1005
1006
1007
1008
# File 'lib/git/lib.rb', line 1002

def unescape_quoted_path(path)
  if path.start_with?('"') && path.end_with?('"')
    Git::EscapedPath.new(path[1..-2]).unescape
  else
    path
  end
end

#unmerged

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.



1356
1357
1358
1359
1360
1361
1362
# File 'lib/git/lib.rb', line 1356

def unmerged
  unmerged = []
  command_lines('diff', '--cached').each do |line|
    unmerged << ::Regexp.last_match(1) if line =~ /^\* Unmerged path (.*)/
  end
  unmerged
end

#untracked_files

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.



1028
1029
1030
1031
1032
# File 'lib/git/lib.rb', line 1028

def untracked_files
  command_lines('ls-files', '--others', '--exclude-standard', chdir: @git_work_dir).map do |f|
    unescape_quoted_path(f)
  end
end

#update_ref(ref, commit)

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.



1560
1561
1562
# File 'lib/git/lib.rb', line 1560

def update_ref(ref, commit)
  command('update-ref', ref, commit)
end

#validate_pathspec_types(pathspecs, arg_name)

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.

Validates that all pathspecs are String or Pathname objects

Parameters:

  • pathspecs (Array)

    the pathspecs to validate

  • arg_name (String)

    name of the argument for error messages

Raises:

  • (ArgumentError)

    if any path is not a String or Pathname



874
875
876
877
878
# File 'lib/git/lib.rb', line 874

def validate_pathspec_types(pathspecs, arg_name)
  return if pathspecs.all? { |path| path.is_a?(String) || path.is_a?(Pathname) }

  raise ArgumentError, "Invalid #{arg_name}: must be a String, Pathname, or Array of Strings/Pathnames"
end

#worktree_add(dir, commitish = nil)

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.



739
740
741
742
743
# File 'lib/git/lib.rb', line 739

def worktree_add(dir, commitish = nil)
  return worktree_command('worktree', 'add', dir, commitish) unless commitish.nil?

  worktree_command('worktree', 'add', dir)
end

#worktree_prune

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.



749
750
751
# File 'lib/git/lib.rb', line 749

def worktree_prune
  worktree_command('worktree', 'prune')
end

#worktree_remove(dir)

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.



745
746
747
# File 'lib/git/lib.rb', line 745

def worktree_remove(dir)
  worktree_command('worktree', 'remove', dir)
end

#worktrees_all

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.



719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
# File 'lib/git/lib.rb', line 719

def worktrees_all
  arr = []
  directory = ''
  # Output example for `worktree list --porcelain`:
  # worktree /code/public/ruby-git
  # HEAD 4bef5abbba073c77b4d0ccc1ffcd0ed7d48be5d4
  # branch refs/heads/master
  #
  # worktree /tmp/worktree-1
  # HEAD b8c63206f8d10f57892060375a86ae911fad356e
  # detached
  #
  command_lines('worktree', 'list', '--porcelain').each do |w|
    s = w.split
    directory = s[1] if s[0] == 'worktree'
    arr << [directory, s[1]] if s[0] == 'HEAD'
  end
  arr
end

#write_tree

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.



1543
1544
1545
# File 'lib/git/lib.rb', line 1543

def write_tree
  command('write-tree')
end