Thegit gem provides a Ruby interface to thegitcommand line.
Get started by obtaining a repository object by:
Methods that can be called on a repository object are documented inGit::Base
Install the gem and add to the application's Gemfile by executing:
bundle add gitto install version 1.x:
bundle add git --version "~> 1.19"If bundler is not being used to manage dependencies, install the gem by executing:
gem install gitto install version 1.x:
gem install git --version "~> 1.19"All functionality for this gem starts with the top-levelGit module. This module can be used to runnon-repo scopedgit commands such asconfig.
TheGit module also has factory methods such asopen,clone, andinit whichreturn aGit::Base object. TheGit::Base object is used to run repo-specificgit commands such asadd,commit,push, andlog.
Clone, read status, and log:
require'git'repo=Git.clone('https://github.com/ruby-git/ruby-git.git','ruby-git')repo.status.changed.each{|f|puts"changed: #{f.path}"}repo.log(5).each{|c|putsc.}Open an existing repo and commit:
require'git'repo=Git.open('/path/to/repo')repo.add(all:true)repo.commit('chore: update files')repo.pushInitialize a new repo and make the first commit:
require'git'repo=Git.init('my_project')repo.add(all:true)repo.commit('initial commit')Beyond the basics covered in Quick Start, these examples show the full range ofoptions and variations for each operation.
Configure thegit command line:
# Global config (in ~/.gitconfig)settings=Git.global_config# returns a Hashusername=Git.global_config('user.email')Git.global_config('user.email','[email protected]')# Repository configrepo=Git.open('path/to/repo')settings=repo.config# returns a Hashusername=repo.config('user.email')repo.config('user.email','[email protected]')Configure the git gem:
Git.configuredo|config|config.binary_path='/usr/local/bin/git'config.git_ssh='ssh -i ~/.ssh/id_rsa'end# orGit.config.binary_path='/usr/local/bin/git'Git.config.git_ssh='ssh -i ~/.ssh/id_rsa'How SSH configuration is determined:
git_ssh is not specified in the API call, the global config (Git.configure {|c| c.git_ssh = ... }) is used.git_ssh: nil is specified, SSH is disabled for that instance (no SSH key orscript will be used).git_ssh is a non-empty string, it is used for that instance (overriding theglobal config).You can also specify a custom SSH script on a per-repository basis:
# Use a specific SSH key for a single repositorygit=Git.open('/path/to/repo',git_ssh:'ssh -i /path/to/private_key')# Or when cloninggit=Git.clone('[email protected]:user/repo.git','local-dir',git_ssh:'ssh -i /path/to/private_key')# Or when initializinggit=Git.init('new-repo',git_ssh:'ssh -i /path/to/private_key')This is especially useful in multi-threaded applications where different repositoriesrequire different SSH credentials.
Here are the operations that need read permission only:
repo=Git.open(working_dir,:log=>Logger.new(STDOUT))repo.indexrepo.index.readable?repo.index.writable?repo.reporepo.dir# ls-tree with recursion into subtrees (list files)repo.ls_tree("HEAD",recursive:true)# log - returns a Git::Log object, which is an Enumerator of Git::Commit objects# default configuration returns a max of 30 commitsrepo.logrepo.log(200)# 200 most recent commitsrepo.log.since('2 weeks ago')# default count of commits since 2 weeks ago.repo.log(200).since('2 weeks ago')# commits since 2 weeks ago, limited to 200.repo.log.between('v2.5','v2.6')repo.log.each{|l|putsl.sha}repo.gblob('v2.5:Makefile').log.since('2 weeks ago')repo.object('HEAD^').to_s# git show / git rev-parserepo.object('HEAD^').contentsrepo.object('v2.5:Makefile').sizerepo.object('v2.5:Makefile').sharepo.gtree(treeish)repo.gblob(treeish)repo.gcommit(treeish)commit=repo.gcommit('1cc8667014381')commit.gtreecommit.parent.shacommit.parents.sizecommit..namecommit..emailcommit..date.strftime("%m-%d-%y")commit.committer.namecommit.date.strftime("%m-%d-%y")commit.tree=repo.gtree("HEAD^{tree}")tree.blobstree.subtreestree.children# blobs and subtreesrepo.rev_parse('v2.0.0:README.md')repo.branches# returns Git::Branch objectsrepo.branches.localrepo.current_branchrepo.branches.remoterepo.branches[:main].gcommitrepo.branches['origin/main'].gcommitrepo.grep('hello')# implies HEADrepo.blob('v2.5:Makefile').grep('hello')repo.tag('v2.5').grep('hello','docs/')repo.describe()repo.describe('0djf2aa')repo.describe('HEAD',{:all=>true,:tags=>true})repo.diff(commit1,commit2).sizerepo.diff(commit1,commit2).statsrepo.diff(commit1,commit2).name_statusrepo.gtree('v2.5').diff('v2.6').insertionsrepo.diff('gitsearch1','v2.5').path('lib/')repo.diff('gitsearch1','v2.5').path('lib/','docs/','README.md')# multiple pathsrepo.diff('gitsearch1',repo.gtree('v2.5'))repo.diff('gitsearch1','v2.5').path('docs/').patchrepo.gtree('v2.5').diff('v2.6').patchrepo.gtree('v2.5').diff('v2.6').eachdo|file_diff|putsfile_diff.pathputsfile_diff.patchputsfile_diff.blob(:src).contentsendrepo.worktrees# returns Git::Worktree objectsrepo.worktrees.countrepo.worktrees.eachdo|worktree|worktree.dirworktree.gcommitworktree.to_send# Check repository integrity with fsckresult=repo.fsckresult.dangling.each{|obj|puts"dangling #{obj.type}: #{obj.sha}"}result.missing.each{|obj|puts"missing #{obj.type}: #{obj.sha}"}# Check if repository has any issuesputs"Repository is clean"ifresult.empty?# fsck with optionsresult=repo.fsck(unreachable:true,strict:true)# Suppress dangling object outputresult=repo.fsck(dangling:false)repo.config('user.name')# returns 'Scott Chacon'repo.config# returns whole config hash# Configuration can be set when cloning using the :config option.# This option can be an single configuration String or an Array# if multiple config items need to be set.#repo=Git.clone(git_uri,destination_path,:config=>['core.sshCommand=ssh -i /home/user/.ssh/id_rsa','submodule.recurse=true'])repo.# returns array of Git::Tag objectsrepo.show()repo.show('HEAD')repo.show('v2.8','README.md')Git.ls_remote('https://github.com/ruby-git/ruby-git.git')# returns a hash containing the available references of the repo.Git.ls_remote('/path/to/local/repo')Git.ls_remote()# same as Git.ls_remote('.')Git.default_branch('https://github.com/ruby-git/ruby-git')#=> 'main'And here are the operations that will need to write to your git repository.
repo=Git.init# default is the current directoryrepo=Git.init('project')repo=Git.init('/home/schacon/proj',{:repository=>'/opt/git/proj.git',:index=>'/tmp/index'})# Clone from a git urlgit_url='https://github.com/ruby-git/ruby-git.git'repo=Git.clone(git_url)# Clone into /tmp/clone/ruby-git-cleanname='ruby-git-clean'path='/tmp/clone'repo=Git.clone(git_url,name,:path=>path)repo.dir#=> /tmp/clone/ruby-git-cleanrepo.config('user.name','Scott Chacon')repo.config('user.email','[email protected]')# Clone can take a filter to tell the serve to send a partial clonerepo=Git.clone(git_url,name,:path=>path,:filter=>'tree:0')# Clone can control single-branch behavior (nil default keeps current git behavior)repo=Git.clone(git_url,name,:path=>path,:depth=>1,:single_branch=>false)# Clone can take an optional loggerlogger=Logger.new(STDOUT)repo=Git.clone(git_url,'my-repo',:log=>logger)repo.add# git add -- "."repo.add(:all=>true)# git add --all -- "."repo.add('file_path')# git add -- "file_path"repo.add(['file_path_1','file_path_2'])# git add -- "file_path_1" "file_path_2"repo.remove()# git rm -f -- "."repo.remove('file.txt')# git rm -f -- "file.txt"repo.remove(['file.txt','file2.txt'])# git rm -f -- "file.txt" "file2.txt"repo.remove('file.txt',:recursive=>true)# git rm -f -r -- "file.txt"repo.remove('file.txt',:cached=>true)# git rm -f --cached -- "file.txt"repo.commit('message')repo.commit_all('message')# Sign a commit using the gpg key configured in the user.signingkey config settingrepo.config('user.signingkey','0A46826A')repo.commit('message',gpg_sign:true)# Sign a commit using a specified gpg keykey_id='0A46826A'repo.commit('message',gpg_sign:key_id)# Skip signing a commit (overriding any global gpgsign setting)repo.commit('message',no_gpg_sign:true)repo=Git.clone(git_url,'myrepo')repo.chdirdoFile.write('test-file','blahblahblah')repo.status.changed.eachdo|file|putsfile.blob(:index).contentsendendrepo.reset# defaults to HEADrepo.reset_hard(Git::Commit)repo.branch('new_branch')# creates new or fetches existingrepo.branch('new_branch').checkoutrepo.branch('new_branch').deleterepo.branch('existing_branch').checkoutrepo.branch('main').contains?('existing_branch')# delete remote branchrepo.push('origin','remote_branch_name',force:true,delete:true)repo.checkout('new_branch')repo.checkout('new_branch',new_branch:true,start_point:'main')repo.checkout(repo.branch('new_branch'))repo.branch(name).merge(branch2)repo.branch(branch2).merge# merges HEAD with branch2repo.branch(name).in_branch(){# add files } # auto-commitsrepo.merge('new_branch')repo.merge('new_branch','merge commit message',no_ff:true)repo.merge('origin/remote_branch')repo.merge(repo.branch('main'))repo.merge([branch1,branch2])repo.merge_base('branch1','branch2')r=repo.add_remote(name,uri)# Git::Remoter=repo.add_remote(name,Git::Base)# Git::Remoterepo.remotes# array of Git::Remotesrepo.remote(name).fetchrepo.remote(name).removerepo.remote(name).mergerepo.remote(name).merge(branch)repo.remote_set_branches('origin','*',add:true)# append additional fetch refspecsrepo.remote_set_branches('origin','feature','release/*')# replace fetch refspecsrepo.fetchrepo.fetch(repo.remotes.first)repo.fetch('origin',{:ref=>'some/ref/head'})repo.fetch(all:true,force:true,depth:2)repo.fetch('origin',{:'update-head-ok'=>true})repo.pullrepo.pull(Git::Repo,Git::Branch)# fetch and a mergerepo.add_tag('tag_name')# returns Git::Tagrepo.add_tag('tag_name','object_reference')repo.add_tag('tag_name','object_reference',{:options=>'here'})repo.add_tag('tag_name',{:options=>'here'})repo.delete_tag('tag_name')repo.repackrepo.pushrepo.push(repo.remote('name'))# delete remote branchrepo.push('origin','remote_branch_name',force:true,delete:true)# push all branches to remote at one timerepo.push('origin',all:true)repo.worktree('/tmp/new_worktree').addrepo.worktree('/tmp/new_worktree','branch1').addrepo.worktree('/tmp/new_worktree').removerepo.worktrees.pruneSome examples of more low-level index and tree operations
repo.with_temp_indexdorepo.read_tree(tree3)# calls self.index.read_treerepo.read_tree(tree1,:prefix=>'hi/')c=repo.commit_tree('message')# or #t=repo.write_treec=repo.commit_tree(t,:message=>'message',:parents=>[sha1,sha2])repo.branch('branch_name').update_ref(c)repo.update_ref(branch,c)repo.with_temp_workingdo# new blank working directoryrepo.checkoutrepo.checkout(another_index)repo.commit# commits to temp_indexendendrepo.set_index('/path/to/index')repo.with_index(path)do# calls set_index, then switches back afterendrepo.with_working(dir)do# calls set_working, then switches back afterendrepo.with_temp_working(dir)dorepo.checkout_index(:prefix=>dir,:path_limiter=>path)# do file workrepo.commit# commits to indexendThe git gem will only raise anArgumentError or an error that is a subclass ofGit::Error. It does not explicitly raise any other types of errors.
It is recommended to rescueGit::Error to catch any runtime error raised by thisgem unless you need more specific error handling.
begin# some git operationrescueGit::Error=>eputs"An error occurred: #{e.message}"endSeeGit::Error for more information.
The timeout feature was added in git gem version2.0.0.
A timeout for git command line operations can be set either globally or for specificmethod calls that accept a:timeout parameter.
The timeout value must be a real, non-negativeNumeric value that specifies anumber of seconds agit command will be given to complete before being sent a KILLsignal. This library may hang if thegit command does not terminate after receivingthe KILL signal.
When a command times out, it is killed by sending it theSIGKILL signal and aGit::TimeoutError is raised. This error derives from theGit::SignaledError andGit::Error.
If the timeout value is0 ornil, no timeout will be enforced.
If a method accepts a:timeout parameter and a receives a non-nil value, the valueof this parameter will override the global timeout value. In this context, a value ofnil (which is usually the default) will use the global timeout value and a value of0 will turn off timeout enforcement for that method call no matter what the globalvalue is.
To set a global timeout, use theGit.config object:
Git.config.timeout=nil# a value of nil or 0 means no timeout is enforcedGit.config.timeout=1.5# can be any real, non-negative Numeric interpreted as number of secondsThe global timeout can be overridden for a specific method if the method accepts a:timeout parameter:
repo_url='https://github.com/ruby-git/ruby-git.git'Git.clone(repo_url)# Use the global timeout valueGit.clone(repo_url,timeout:nil)# Also uses the global timeout valueGit.clone(repo_url,timeout:0)# Do not enforce a timeoutGit.clone(repo_url,timeout:10.5)# Timeout after 10.5 seconds raising Git::SignaledErrorIf the command takes too long, aGit::TimeoutError will be raised:
beginGit.clone(repo_url,timeout:10)rescueGit::TimeoutError=>ee.result.tapdo|r|r.class#=> Git::CommandLineResultr.status#=> #<Process::Status: pid 62173 SIGKILL (signal 9)>r.status.timeout?#=> truer.git_cmd# The git command ran as an array of stringsr.stdout# The command's output to stdout until it was terminatedr.stderr# The command's output to stderr until it was terminatedendendThis gem uses ActiveSupport's deprecation mechanism to report deprecation warnings.
You can silence deprecation warnings by adding this line to your source code:
Git::Deprecation.behavior=:silenceSeethe Active Support Deprecationdocumentationfor more details.
If deprecation warnings are silenced, you should reenable them before upgrading thegit gem to the next major version. This will make it easier to identify changesneeded for the upgrade.
These documents set expectations for behavior, contribution workflows, AI-assistedchanges, decision making, maintainer roles, and licensing. Please review them beforeopening issues or pull requests.
| Document | Description |
|---|---|
| CODE_OF_CONDUCT | We follow the Ruby community Code of Conduct; expect respectful, harassment-free participation and report concerns to maintainers. |
| CONTRIBUTING | How to report issues, submit PRs with Conventional Commits, meet coding/testing standards, and follow the Code of Conduct. |
| AI_POLICY | AI-assisted contributions are welcome. Contributors are expected to read and apply the AI Policy, and ensure any AI-assisted work meets our quality, security, and licensing standards. |
| Ruby version support policy | Supported Ruby runtimes and platforms; bump decisions and CI coverage expectations. |
| Git version support policy | Minimum supported git version and how version bumps are communicated and enforced. |
| GOVERNANCE | Principles-first governance defining maintainer/project lead roles, least-privilege access, consensus/majority decisions, and nomination/emeritus steps. |
| MAINTAINERS | Lists active maintainers (Project Lead noted) and emeritus alumni with links; see governance for role scope. |
| LICENSE | MIT License terms for using, modifying, and redistributing this project. |
This gem is expected to function correctly on:
It is this project's intent to support the latest version of JRuby on Windows oncetheprocess_executer gem properlysupports subprocess status reporting on JRuby for Windows (seemain-branch/process_executer#156).
This gem requires git version 2.28.0 or greater as specified in the gemspec. Thisrequirement reflects:
Git 2.28.0 was released on July 27, 2020. While this gem may work with earlierversions of git, compatibility with versions prior to 2.28.0 is not tested orguaranteed. Users on older git versions should upgrade to at least 2.28.0.
The supported git version may be increased in future major or minor releases of thisgem as new git features are adopted or as maintaining backward compatibility becomesimpractical. Such changes will be clearly documented in the CHANGELOG and releasenotes.
We have adopted a formalAI Policy to clarify expectations forAI-assisted contributions. Please review it before opening a PR to ensure yourchanges are fully understood, meet our quality bar, and respect licensingrequirements.
We chose a principles-based policy to respect contributors’ time and expertise. It’squick to read, easy to remember, and avoids unnecessary policy overhead while stillsetting clear expectations.
The git gem is undergoing a significant architectural redesign for the upcomingv5.0.0 release. The current architecture has several design challenges that make itdifficult to maintain and evolve. This redesign aims to address these issues byintroducing a clearer, more robust, and more testable structure.
We have prepared detailed documents outlining the analysis of the currentarchitecture and the proposed changes. We encourage our community and contributors toreview them:
Your feedback is welcome! Please feel free to open an issue to discuss the proposedchanges.
DON'T PANIC!
While this is a major internal refactoring, our goal is to keep the primary publicAPI on the main repository object as stable as possible. Most users who rely ondocumented methods like
g.commit,g.add, andg.statusshould find thetransition to v5.0.0 straightforward.The breaking changes will primarily affect users who have been relying on theinternal g.lib accessor, which will be removed as part of this cleanup. For moredetails, please see the "Impact on Users" section inthe redesigndocument.
To improve code consistency and maintainability, theruby-git project has nowadoptedRuboCop as our static code analyzer and formatter.
This integration is a key part of our ongoing commitment to makingruby-git ahigh-quality, stable, and easy-to-contribute-to project. All new contributions willbe expected to adhere to the style guidelines enforced by our RuboCop configuration.
RuboCop can be run from the project's Rakefile:
rake rubocopRuboCop is also run as part of the default rake task (by runningrake) that is runin our Continuous Integration workflow.
Going forward, any PRs that have any Robocop offenses will not be merged. In certainrare cases, it might be acceptable to disable a RuboCop check for the most limitedscope possible.
If you have a problem fixing a RuboCop offense, don't be afraid to ask acontributor.
On June 6th, 2025, the default branch was renamed from 'master' to 'main'.
Instructions for renaming your local or forked branch to match can be found in thegistDefault Branch NameChange.
To enhance our development workflow, enable automated changelog generation, and pavethe way for Continuous Delivery, theruby-git project has adopted theConventionalCommits standard for all commitmessages.
Going forward, all commits to this repositoryMUST adhere to the ConventionalCommits standard. Commits not adhering to this standard will cause the CI build tofail. PRs will not be merged if they include non-conventional commits.
A git pre-commit hook may be installed to validate your conventional commit messagesbefore pushing them to GitHub by runningbin/setup in the project root.
Read more about this change in theCommit Message Guidelines section ofCONTRIBUTING.md