Module: Git

Defined in:
lib/git.rb,
lib/git.rb,
lib/git/lib.rb,
lib/git/log.rb,
lib/git/url.rb,
lib/git/base.rb,
lib/git/diff.rb,
lib/git/path.rb,
lib/git/index.rb,
lib/git/stash.rb,
lib/git/author.rb,
lib/git/branch.rb,
lib/git/config.rb,
lib/git/errors.rb,
lib/git/object.rb,
lib/git/remote.rb,
lib/git/status.rb,
lib/git/stashes.rb,
lib/git/version.rb,
lib/git/branches.rb,
lib/git/worktree.rb,
lib/git/worktrees.rb,
lib/git/diff_stats.rb,
lib/git/repository.rb,
lib/git/fsck_object.rb,
lib/git/fsck_result.rb,
lib/git/args_builder.rb,
lib/git/command_line.rb,
lib/git/escaped_path.rb,
lib/git/encoding_utils.rb,
lib/git/diff_path_status.rb,
lib/git/working_directory.rb,
lib/git/command_line_result.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.

Author:

Defined Under Namespace

Modules: EncodingUtils Classes: ArgsBuilder, Author, Base, Branch, Branches, CommandLine, CommandLineError, CommandLineResult, Config, Diff, DiffPathStatus, DiffStats, Error, EscapedPath, FailedError, FsckObject, FsckResult, GitAltURI, Index, Lib, Log, Object, Path, ProcessIOError, Remote, Repository, SignaledError, Stash, Stashes, Status, TimeoutError, URL, UnexpectedResultError, WorkingDirectory, Worktree, Worktrees

Constant Summary collapse

Deprecation =

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

ActiveSupport::Deprecation.new('5.0.0', 'Git')
LibImpl =

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.

Internal alias for Git::Lib, used by the gem itself after the public constant is deprecated. Code outside the gem should not reference this constant.

remove_const(:Lib)
GitExecuteError =
Deprecated.

Use Git::Error instead

An alias for Git::Error

Git::GitExecuteError error class is an alias for Git::Error for backwards compatibility. It is recommended to use Git::Error directly.

ActiveSupport::Deprecation::DeprecatedConstantProxy.new('Git::GitExecuteError', 'Git::Error', Git::Deprecation)
VERSION =

The current gem version

Returns:

  • (String)

    the current gem version.

'4.4.5'

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.bare(git_dir, options = {}) ⇒ Git::Base

Open a bare repository

Opens a bare repository located in the git_dir directory. Since there is no working copy, you can not checkout or commit but you can do most read operations.

Examples:

Open a bare repository and retrieve the first commit SHA

repository = Git.bare('ruby-git.git')
puts repository.log[0].sha #=> "64c6fa011d3287bab9158049c85f3e85718854a0"

Parameters:

  • git_dir (Pathname)

    The path to the bare repository directory containing an initialized Git repository. If a relative path is given, it is converted to an absolute path using File.expand_path.

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

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

Options Hash (options):

  • :git_ssh (String, nil)

    An optional custom SSH command

    • If not specified, uses the global config (Git.configure { |c| c.git_ssh = ... }).
    • If nil, disables SSH for this instance.
    • If a non-empty string, uses that value for this instance.
  • :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:

  • (Git::Base)

    an object that can execute git commands in the context of the bare repository.

See Also:



146
147
148
# File 'lib/git.rb', line 146

def self.bare(git_dir, options = {})
  Base.bare(git_dir, options)
end

.binary_version(binary_path = Git::Base.config.binary_path) ⇒ Array<Integer>

Return the version of the git binary

Examples:

Git.binary_version # => [2, 46, 0]

Returns:

  • (Array<Integer>)

    the version of the git binary



483
484
485
# File 'lib/git.rb', line 483

def self.binary_version(binary_path = Git::Base.config.binary_path)
  Base.binary_version(binary_path)
end

.clone(repository_url, directory = nil, options = {}) ⇒ Git::Base

Clone a repository into an empty or newly created directory

Examples:

Clone into the default directory ruby-git

git = Git.clone('https://github.com/ruby-git/ruby-git.git')

Clone and then checkout the development branch

git = Git.clone('https://github.com/ruby-git/ruby-git.git', branch: 'development')

Clone into a different directory my-ruby-git

git = Git.clone('https://github.com/ruby-git/ruby-git.git', 'my-ruby-git')
# or:
git = Git.clone('https://github.com/ruby-git/ruby-git.git', path: 'my-ruby-git')

Create a bare repository in the directory ruby-git.git

git = Git.clone('https://github.com/ruby-git/ruby-git.git', bare: true)

Clone a repository and set a single config option

git = Git.clone(
  'https://github.com/ruby-git/ruby-git.git',
  config: 'submodule.recurse=true'
)

Clone a repository and set multiple config options

git = Git.clone(
  'https://github.com/ruby-git/ruby-git.git',
  config: ['user.name=John Doe', '[email protected]']
)

Clone using a specific SSH key

git = Git.clone(
  '[email protected]:ruby-git/ruby-git.git',
  'local-dir',
  git_ssh: 'ssh -i /path/to/private_key'
)

Parameters:

  • repository_url (URI, Pathname)

    The (possibly remote) repository url to clone from. See GIT URLS for more information.

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

    The directory to clone into

    If directory is a relative directory it is relative to the path option if given. If path is not given, directory is relative to the current working directory.

    If nil, directory will be set to the basename of the last component of the path from the repository_url. For example, for the URL: https://github.com/org/repo.git, directory will be set to repo.

    If the last component of the path is .git, the next-to-last component of the path is used. For example, for the URL /Users/me/foo/.git, directory will be set to foo.

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

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

Options Hash (options):

  • :bare (Boolean)

    Make a bare Git repository. See what is a bare repository?.

  • :branch (String)

    The name of a branch or tag to checkout instead of the default branch.

  • :config (Array, String)

    A list of configuration options to set on the newly created repository.

  • :depth (Integer)

    Create a shallow clone with a history truncated to the specified number of commits.

  • :filter (String)

    Request that the server send a partial clone according to the given filter

  • :single_branch (Boolean, nil)

    Control whether the clone limits fetch refspecs to a single branch.

    • If nil (default), no flag is passed and the Git default is used.
    • If true, --single-branch is passed to limit the refspec to the checkout branch.
    • If false, --no-single-branch is passed to broaden the refspec (useful for shallow clones that should include all branches).
  • :git_ssh (String, nil)

    An optional custom SSH command

    • If not specified, uses the global config (Git.configure { |c| c.git_ssh = ... }).
    • If nil, disables SSH for this instance.
    • If a non-empty string, uses that value for this instance.
  • :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.

  • :mirror (Boolean)

    Set up a mirror of the source repository.

  • :origin (String)

    Use the value instead origin to track the upstream repository.

  • :path (Pathname)

    The directory to clone into. May be used as an alternative to the directory parameter. If specified, the path option is used instead of the directory parameter.

  • :recursive (Boolean)

    After the clone is created, initialize all submodules within, using their default settings.

Returns:

  • (Git::Base)

    an object that can execute git commands in the context of the cloned local working copy or cloned repository.

See Also:



257
258
259
260
261
# File 'lib/git.rb', line 257

def self.clone(repository_url, directory = nil, options = {})
  clone_to_options = options.slice(:bare, :mirror)
  directory ||= Git::URL.clone_to(repository_url, **clone_to_options)
  Base.clone(repository_url, directory, options)
end

.config



104
105
106
# File 'lib/git.rb', line 104

def self.config
  Base.config
end

.configure {|Base.config| ... }

Yields:



100
101
102
# File 'lib/git.rb', line 100

def self.configure
  yield Base.config
end

.const_missing(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.



72
73
74
75
76
77
78
79
80
# File 'lib/git.rb', line 72

def self.const_missing(name)
  return super unless name == :Lib

  Git::Deprecation.warn(
    'Git::Lib is deprecated and will be removed in version 5.x. ' \
    'Use the #lib accessor on the object returned by Git.init, Git.open, or Git.clone instead.'
  )
  const_set(:Lib, LibImpl)
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'
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



300
301
302
# File 'lib/git.rb', line 300

def self.default_branch(repository, options = {})
  Base.repository_default_branch(repository, options)
end

.export(repository, name, options = {})

Export the current HEAD (or a branch, if options is specified) into the name directory, then remove all traces of git from the directory.

See clone for options. Does not obey the :remote option, since the .git info will be deleted anyway; always uses the default remote, 'origin.'

options is the short name of the ref: a branch name such as 'main' or a tag name such as 'v1.0.0'. A full ref path such as 'refs/tags/v1.0.0' or a commit SHA is not accepted.

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.

Raises:

  • (SystemCallError)

    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.



324
325
326
327
328
# File 'lib/git.rb', line 324

def self.export(repository, name, options = {})
  options.delete(:remote)
  repo = clone(repository, name, { depth: 1 }.merge(options))
  FileUtils.rm_r File.join(repo.dir.to_s, '.git')
end

.global_config(name = nil, value = nil)

Same as g.config, but forces it to be at the global level

g.config('user.name', 'Scott Chacon') # sets value g.config('user.email', '[email protected]') # sets value g.config('user.name') # returns 'Scott Chacon' g.config # returns whole config hash



336
337
338
339
340
341
342
343
344
345
346
347
348
# File 'lib/git.rb', line 336

def self.global_config(name = nil, value = nil)
  lib = LibImpl.new(nil, nil)
  if name && value
    # set value
    lib.global_config_set(name, value)
  elsif name
    # return value
    lib.global_config_get(name)
  else
    # return hash
    lib.global_config_list
  end
end

.init(directory = '.', options = {}) ⇒ Git::Base

Create an empty Git repository or reinitialize an existing Git repository

Examples:

Initialize a repository in the current directory

git = Git.init

Initialize a repository in some other directory

git = Git.init '~/code/ruby-git'

Initialize a bare repository

git = Git.init '~/code/ruby-git.git', bare: true

Initialize a repository in a non-default location (outside of the working copy)

git = Git.init '~/code/ruby-git', repository: '~/code/ruby-git.git'

Parameters:

  • directory (Pathname) (defaults to: '.')

    If the :bare option is NOT given or is not true, the repository will be created in "#{directory}/.git". Otherwise, the repository is created in "#{directory}".

    All directories along the path to directory are created if they do not exist.

    A relative path is referenced from the current working directory of the process and converted to an absolute path using File.expand_path.

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

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

Options Hash (options):

  • :bare (Boolean)

    Instead of creating a repository at "#{directory}/.git", create a bare repository at "#{directory}". See what is a bare repository?.

  • :initial_branch (String)

    Use the specified name for the initial branch in the newly created repository.

  • :repository (Pathname)

    the path to put the newly initialized Git repository. The default for non-bare repository is "#{directory}/.git".

    A relative path is referenced from the current working directory of the process and converted to an absolute path using File.expand_path.

  • :git_ssh (String, nil)

    An optional custom SSH command

    • If not specified, uses the global config (Git.configure { |c| c.git_ssh = ... }).
    • If nil, disables SSH for this instance.
    • If a non-empty string, uses that value for this instance.
  • :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:

  • (Git::Base)

    an object that can execute git commands in the context of the newly initialized repository

See Also:



406
407
408
# File 'lib/git.rb', line 406

def self.init(directory = '.', options = {})
  Base.init(directory, options)
end

.ls_remote(location = nil, options = {}) ⇒ {String=>Hash}

returns a Hash containing information about the references of the target repository

options :refs

Parameters:

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

    the target repository location or nil for '.'

Returns:

  • ({String=>Hash})

    the available references of the target repo.



418
419
420
# File 'lib/git.rb', line 418

def self.ls_remote(location = nil, options = {})
  LibImpl.new.ls_remote(location, options)
end

.open(working_dir, options = {}) ⇒ Git::Base

Open a an existing Git working directory

Git.open will most likely be the most common way to create a git reference, referring to an existing working directory.

If not provided in the options, the library will assume the repository and index are in the default places (.git/, .git/index).

Examples:

Open the Git working directory in the current directory

git = Git.open

Open a Git working directory in some other directory

git = Git.open('~/Projects/ruby-git')

Use a logger to see what is going on

logger = Logger.new(STDOUT)
git = Git.open('~/Projects/ruby-git', log: logger)

Open a working copy whose repository is in a non-standard directory

git = Git.open('~/Projects/ruby-git', repository: '~/Project/ruby-git.git')

Parameters:

  • working_dir (Pathname)

    the path to the working directory to use for git commands.

    A relative path is referenced from the current working directory of the process and converted to an absolute path using File.expand_path.

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

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

Options Hash (options):

  • :repository (Pathname)

    used to specify a non-standard path to the repository directory. The default is "#{working_dir}/.git".

  • :index (Pathname)

    used to specify a non-standard path to an index file. The default is "#{working_dir}/.git/index"

  • :git_ssh (String, nil)

    An optional custom SSH command

    • If not specified, uses the global config (Git.configure { |c| c.git_ssh = ... }).
    • If nil, disables SSH for this instance.
    • If a non-empty string, uses that value for this instance.
  • :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:

  • (Git::Base)

    an object that can execute git commands in the context of the opened working copy



472
473
474
# File 'lib/git.rb', line 472

def self.open(working_dir, options = {})
  Base.open(working_dir, options)
end

Instance Method Details

#config(name = nil, value = nil)

g.config('user.name', 'Scott Chacon') # sets value g.config('user.email', '[email protected]') # sets value g.config('user.name') # returns 'Scott Chacon' g.config # returns whole config hash



86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/git.rb', line 86

def config(name = nil, value = nil)
  lib = LibImpl.new
  if name && value
    # set value
    lib.config_set(name, value)
  elsif name
    # return value
    lib.config_get(name)
  else
    # return hash
    lib.config_list
  end
end

#global_config(name = nil, value = nil)



108
109
110
# File 'lib/git.rb', line 108

def global_config(name = nil, value = nil)
  self.class.global_config(name, value)
end