{"id":13463112,"url":"https://github.com/ruby-git/ruby-git","last_synced_at":"2025-05-13T21:03:00.260Z","repository":{"id":65332335,"uuid":"130","full_name":"ruby-git/ruby-git","owner":"ruby-git","description":"Ruby/Git is a Ruby library that can be used to create, read and manipulate Git repositories by wrapping system calls to the git binary.","archived":false,"fork":false,"pushed_at":"2025-02-28T01:41:06.000Z","size":1242,"stargazers_count":1762,"open_issues_count":12,"forks_count":533,"subscribers_count":35,"default_branch":"master","last_synced_at":"2025-04-30T07:48:22.794Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ruby-git.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2008-01-27T17:23:23.000Z","updated_at":"2025-04-26T15:36:51.000Z","dependencies_parsed_at":"2024-02-22T03:28:37.263Z","dependency_job_id":"1577a61d-889b-47ff-831c-ebbf080e1d1e","html_url":"https://github.com/ruby-git/ruby-git","commit_stats":{"total_commits":556,"total_committers":116,"mean_commits":4.793103448275862,"dds":0.7230215827338129,"last_synced_commit":"81932be8783834c87635bf7976126307f2054d90"},"previous_names":["schacon/ruby-git"],"tags_count":58,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ruby-git%2Fruby-git","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ruby-git%2Fruby-git/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ruby-git%2Fruby-git/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ruby-git%2Fruby-git/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ruby-git","download_url":"https://codeload.github.com/ruby-git/ruby-git/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251843661,"owners_count":21652855,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T13:00:46.175Z","updated_at":"2025-05-06T02:58:30.678Z","avatar_url":"https://github.com/ruby-git.png","language":"Ruby","readme":"\u003c!--\n# @markup markdown\n# @title README\n--\u003e\n\n# The Git Gem\n\n[![Gem Version](https://badge.fury.io/rb/git.svg)](https://badge.fury.io/rb/git)\n[![Documentation](https://img.shields.io/badge/Documentation-Latest-green)](https://rubydoc.info/gems/git/)\n[![Change Log](https://img.shields.io/badge/CHANGELOG-Latest-green)](https://rubydoc.info/gems/git/file/CHANGELOG.md)\n[![Build Status](https://github.com/ruby-git/ruby-git/workflows/CI/badge.svg?branch=master)](https://github.com/ruby-git/ruby-git/actions?query=workflow%3ACI)\n[![Code Climate](https://codeclimate.com/github/ruby-git/ruby-git.png)](https://codeclimate.com/github/ruby-git/ruby-git)\n\n* [Summary](#summary)\n* [v2.x Release](#v2x-release)\n* [Install](#install)\n* [Major Objects](#major-objects)\n* [Errors Raised By This Gem](#errors-raised-by-this-gem)\n* [Specifying And Handling Timeouts](#specifying-and-handling-timeouts)\n* [Examples](#examples)\n* [Ruby version support policy](#ruby-version-support-policy)\n* [License](#license)\n\n## Summary\n\nThe [git gem](https://rubygems.org/gems/git) provides a Ruby interface to the `git`\ncommand line.\n\nGet started by obtaining a repository object by:\n\n* opening an existing working copy with [Git.open](https://rubydoc.info/gems/git/Git#open-class_method)\n* initializing a new repository with [Git.init](https://rubydoc.info/gems/git/Git#init-class_method)\n* cloning a repository with [Git.clone](https://rubydoc.info/gems/git/Git#clone-class_method)\n\nMethods that can be called on a repository object are documented in [Git::Base](https://rubydoc.info/gems/git/Git/Base)\n\n## v2.x Release\n\ngit 2.0.0 has recently been released. Please give it a try.\n\n**If you have problems with the 2.x release, open an issue and use the 1.x version\ninstead.** We will do our best to fix your issues in a timely fashion.\n\n**JRuby on Windows is not yet supported by the 2.x release line. Users running JRuby\non Windows should continue to use the 1.x release line.**\n\nThe changes in this major release include:\n\n* Added a dependency on the activesupport gem to use the deprecation functionality\n* Create a policy of supported Ruby versions to support only non-EOL Ruby versions\n* Create a policy of supported Git CLI versions (released 2020-12-25)\n* Update the required Ruby version to at least 3.0 (released 2020-07-27)\n* Update the required Git command line version to at least 2.28\n* Update how CLI commands are called to use the [process_executer](https://github.com/main-branch/process_executer)\n  gem which is built on top of [Kernel.spawn](https://ruby-doc.org/3.3.0/Kernel.html#method-i-spawn).\n  See [PR #684](https://github.com/ruby-git/ruby-git/pull/684) for more details\n  on the motivation for this implementation.\n\nThe `master` branch will be used for `2.x` development. If needed, fixes for `1.x`\nversion will be done on the `v1` branch.\n\n## Install\n\nInstall the gem and add to the application's Gemfile by executing:\n\n```shell\nbundle add git\n```\n\nto install version 1.x:\n\n```shell\nbundle add git --version \"~\u003e 1.19\"\n```\n\nIf bundler is not being used to manage dependencies, install the gem by executing:\n\n```shell\ngem install git\n```\n\nto install version 1.x:\n\n```shell\ngem install git --version \"~\u003e 1.19\"\n```\n\n## Major Objects\n\n**Git::Base** - The object returned from a `Git.open` or `Git.clone`. Most major actions are called from this object.\n\n**Git::Object** - The base object for your tree, blob and commit objects, returned from `@git.gtree` or `@git.object` calls.  the `Git::AbstractObject` will have most of the calls in common for all those objects.\n\n**Git::Diff** - returns from a `@git.diff` command.  It is an Enumerable that returns `Git::Diff:DiffFile` objects from which you can get per file patches and insertion/deletion statistics.  You can also get total statistics from the Git::Diff object directly.\n\n**Git::Status** - returns from a `@git.status` command.  It is an Enumerable that returns\n`Git:Status::StatusFile` objects for each object in git, which includes files in the working\ndirectory, in the index and in the repository.  Similar to running 'git status' on the command line to determine untracked and changed files.\n\n**Git::Branches** - Enumerable object that holds `Git::Branch objects`.  You can call .local or .remote on it to filter to just your local or remote branches.\n\n**Git::Remote**- A reference to a remote repository that is tracked by this repository.\n\n**Git::Log** - An Enumerable object that references all the `Git::Object::Commit`\nobjects that encompass your log query, which can be constructed through methods on\nthe `Git::Log object`, like:\n\n```ruby\ngit.log\n  .max_count(:all)\n  .object('README.md')\n  .since('10 years ago')\n  .between('v1.0.7', 'HEAD')\n  .map { |commit| commit.sha }\n```\n\nA maximum of 30 commits are returned if `max_count` is not called. To get all commits\nthat match the log query, call `max_count(:all)`.\n\nNote that `git.log.all` adds the `--all` option to the underlying `git log` command.\nThis asks for the logs of all refs (basically all commits reachable by HEAD,\nbranches, and tags). This does not control the maximum number of commits returned. To\ncontrol how many commits are returned, you should call `max_count`.\n\n**Git::Worktrees** - Enumerable object that holds `Git::Worktree objects`.\n\n## Errors Raised By This Gem\n\nThe git gem will only raise an `ArgumentError` or an error that is a subclass of\n`Git::Error`. It does not explicitly raise any other types of errors.\n\nIt is recommended to rescue `Git::Error` to catch any runtime error raised by\nthis gem unless you need more specific error handling.\n\n```ruby\nbegin\n  # some git operation\nrescue Git::Error =\u003e e\n  puts \"An error occurred: #{e.message}\"\nend\n```\n\nSee [`Git::Error`](https://rubydoc.info/gems/git/Git/Error) for more information.\n\n## Specifying And Handling Timeouts\n\nThe timeout feature was added in git gem version `2.0.0`.\n\nA timeout for git command line operations can be set either globally or for specific\nmethod calls that accept a `:timeout` parameter.\n\nThe timeout value must be a real, non-negative `Numeric` value that specifies a\nnumber of seconds a `git` command will be given to complete before being sent a KILL\nsignal. This library may hang if the `git` command does not terminate after receiving\nthe KILL signal.\n\nWhen a command times out, it is killed by sending it the `SIGKILL` signal and a\n`Git::TimeoutError` is raised. This error derives from the `Git::SignaledError` and\n`Git::Error`.\n\nIf the timeout value is `0` or `nil`, no timeout will be enforced.\n\nIf a method accepts a `:timeout` parameter and a receives a non-nil value, the value\nof this parameter will override the global timeout value. In this context, a value of\n`nil` (which is usually the default) will use the global timeout value and a value of\n`0` will turn off timeout enforcement for that method call no matter what the global\nvalue is.\n\nTo set a global timeout, use the `Git.config` object:\n\n```ruby\nGit.config.timeout = nil # a value of nil or 0 means no timeout is enforced\nGit.config.timeout = 1.5 # can be any real, non-negative Numeric interpreted as number of seconds\n```\n\nThe global timeout can be overridden for a specific method if the method accepts a\n`:timeout` parameter:\n\n```ruby\nrepo_url = 'https://github.com/ruby-git/ruby-git.git'\nGit.clone(repo_url) # Use the global timeout value\nGit.clone(repo_url, timeout: nil) # Also uses the global timeout value\nGit.clone(repo_url, timeout: 0) # Do not enforce a timeout\nGit.clone(repo_url, timeout: 10.5)  # Timeout after 10.5 seconds raising Git::SignaledError\n```\n\nIf the command takes too long, a `Git::TimeoutError` will be raised:\n\n```ruby\nbegin\n  Git.clone(repo_url, timeout: 10)\nrescue Git::TimeoutError =\u003e e\n  e.result.tap do |r|\n    r.class #=\u003e Git::CommandLineResult\n    r.status #=\u003e #\u003cProcess::Status: pid 62173 SIGKILL (signal 9)\u003e\n    r.status.timeout? #=\u003e true\n    r.git_cmd # The git command ran as an array of strings\n    r.stdout # The command's output to stdout until it was terminated\n    r.stderr # The command's output to stderr until it was terminated\n  end\nend\n```\n\n## Examples\n\nHere are a bunch of examples of how to use the Ruby/Git package.\n\nRequire the 'git' gem.\n\n```ruby\nrequire 'git'\n```\n\nGit env config\n\n```ruby\nGit.configure do |config|\n  # If you want to use a custom git binary\n  config.binary_path = '/git/bin/path'\n\n  # If you need to use a custom SSH script\n  config.git_ssh = '/path/to/ssh/script'\nend\n```\n\n_NOTE: Another way to specify where is the `git` binary is through the environment variable `GIT_PATH`_\n\nHere are the operations that need read permission only.\n\n```ruby\ng = Git.open(working_dir, :log =\u003e Logger.new(STDOUT))\n\ng.index\ng.index.readable?\ng.index.writable?\ng.repo\ng.dir\n\n# ls-tree with recursion into subtrees (list files)\ng.ls_tree(\"HEAD\", recursive: true)\n\n# log - returns a Git::Log object, which is an Enumerator of Git::Commit objects\n# default configuration returns a max of 30 commits\ng.log\ng.log(200) # 200 most recent commits\ng.log.since('2 weeks ago') # default count of commits since 2 weeks ago.\ng.log(200).since('2 weeks ago') # commits since 2 weeks ago, limited to 200.\ng.log.between('v2.5', 'v2.6')\ng.log.each {|l| puts l.sha }\ng.gblob('v2.5:Makefile').log.since('2 weeks ago')\n\ng.object('HEAD^').to_s  # git show / git rev-parse\ng.object('HEAD^').contents\ng.object('v2.5:Makefile').size\ng.object('v2.5:Makefile').sha\n\ng.gtree(treeish)\ng.gblob(treeish)\ng.gcommit(treeish)\n\n\ncommit = g.gcommit('1cc8667014381')\n\ncommit.gtree\ncommit.parent.sha\ncommit.parents.size\ncommit.author.name\ncommit.author.email\ncommit.author.date.strftime(\"%m-%d-%y\")\ncommit.committer.name\ncommit.date.strftime(\"%m-%d-%y\")\ncommit.message\n\ntree = g.gtree(\"HEAD^{tree}\")\n\ntree.blobs\ntree.subtrees\ntree.children # blobs and subtrees\n\ng.rev_parse('v2.0.0:README.md')\n\ng.branches # returns Git::Branch objects\ng.branches.local\ng.current_branch\ng.branches.remote\ng.branches[:master].gcommit\ng.branches['origin/master'].gcommit\n\ng.grep('hello')  # implies HEAD\ng.blob('v2.5:Makefile').grep('hello')\ng.tag('v2.5').grep('hello', 'docs/')\ng.describe()\ng.describe('0djf2aa')\ng.describe('HEAD', {:all =\u003e true, :tags =\u003e true})\n\ng.diff(commit1, commit2).size\ng.diff(commit1, commit2).stats\ng.diff(commit1, commit2).name_status\ng.gtree('v2.5').diff('v2.6').insertions\ng.diff('gitsearch1', 'v2.5').path('lib/')\ng.diff('gitsearch1', @git.gtree('v2.5'))\ng.diff('gitsearch1', 'v2.5').path('docs/').patch\ng.gtree('v2.5').diff('v2.6').patch\n\ng.gtree('v2.5').diff('v2.6').each do |file_diff|\n  puts file_diff.path\n  puts file_diff.patch\n  puts file_diff.blob(:src).contents\nend\n\ng.worktrees # returns Git::Worktree objects\ng.worktrees.count\ng.worktrees.each do |worktree|\n  worktree.dir\n  worktree.gcommit\n  worktree.to_s\nend\n\ng.config('user.name')  # returns 'Scott Chacon'\ng.config # returns whole config hash\n\n# Configuration can be set when cloning using the :config option.\n# This option can be an single configuration String or an Array\n# if multiple config items need to be set.\n#\ng = Git.clone(\n  git_uri, destination_path,\n  :config =\u003e [\n    'core.sshCommand=ssh -i /home/user/.ssh/id_rsa',\n    'submodule.recurse=true'\n  ]\n)\n\ng.tags # returns array of Git::Tag objects\n\ng.show()\ng.show('HEAD')\ng.show('v2.8', 'README.md')\n\nGit.ls_remote('https://github.com/ruby-git/ruby-git.git') # returns a hash containing the available references of the repo.\nGit.ls_remote('/path/to/local/repo')\nGit.ls_remote() # same as Git.ls_remote('.')\n\nGit.default_branch('https://github.com/ruby-git/ruby-git') #=\u003e 'master'\n```\n\nAnd here are the operations that will need to write to your git repository.\n\n```ruby\ng = Git.init\n  Git.init('project')\n  Git.init('/home/schacon/proj',\n  { :repository =\u003e '/opt/git/proj.git',\n      :index =\u003e '/tmp/index'} )\n\n# Clone from a git url\ngit_url = 'https://github.com/ruby-git/ruby-git.git'\n# Clone into the ruby-git directory\ng = Git.clone(git_url)\n\n# Clone into /tmp/clone/ruby-git-clean\nname = 'ruby-git-clean'\npath = '/tmp/clone'\ng = Git.clone(git_url, name, :path =\u003e path)\ng.dir #=\u003e /tmp/clone/ruby-git-clean\n\ng.config('user.name', 'Scott Chacon')\ng.config('user.email', 'email@email.com')\n\n# Clone can take a filter to tell the serve to send a partial clone\ng = Git.clone(git_url, name, :path =\u003e path, :filter =\u003e 'tree:0')\n\n# Clone can take an optional logger\nlogger = Logger.new\ng = Git.clone(git_url, NAME, :log =\u003e logger)\n\ng.add                                   # git add -- \".\"\ng.add(:all=\u003etrue)                       # git add --all -- \".\"\ng.add('file_path')                      # git add -- \"file_path\"\ng.add(['file_path_1', 'file_path_2'])   # git add -- \"file_path_1\" \"file_path_2\"\n\ng.remove()                                # git rm -f -- \".\"\ng.remove('file.txt')                      # git rm -f -- \"file.txt\"\ng.remove(['file.txt', 'file2.txt'])       # git rm -f -- \"file.txt\" \"file2.txt\"\ng.remove('file.txt', :recursive =\u003e true)  # git rm -f -r -- \"file.txt\"\ng.remove('file.txt', :cached =\u003e true)     # git rm -f --cached -- \"file.txt\"\n\ng.commit('message')\ng.commit_all('message')\n\n# Sign a commit using the gpg key configured in the user.signingkey config setting\ng.config('user.signingkey', '0A46826A')\ng.commit('message', gpg_sign: true)\n\n# Sign a commit using a specified gpg key\nkey_id = '0A46826A'\ng.commit('message', gpg_sign: key_id)\n\n# Skip signing a commit (overriding any global gpgsign setting)\ng.commit('message', no_gpg_sign: true)\n\ng = Git.clone(repo, 'myrepo')\ng.chdir do\nnew_file('test-file', 'blahblahblah')\ng.status.changed.each do |file|\n  puts file.blob(:index).contents\nend\nend\n\ng.reset # defaults to HEAD\ng.reset_hard(Git::Commit)\n\ng.branch('new_branch') # creates new or fetches existing\ng.branch('new_branch').checkout\ng.branch('new_branch').delete\ng.branch('existing_branch').checkout\ng.branch('master').contains?('existing_branch')\n\n# delete remote branch\ng.push('origin', 'remote_branch_name', force: true, delete: true)\n\ng.checkout('new_branch')\ng.checkout('new_branch', new_branch: true, start_point: 'master')\ng.checkout(g.branch('new_branch'))\n\ng.branch(name).merge(branch2)\ng.branch(branch2).merge  # merges HEAD with branch2\n\ng.branch(name).in_branch(message) { # add files }  # auto-commits\ng.merge('new_branch')\ng.merge('new_branch', 'merge commit message', no_ff: true)\ng.merge('origin/remote_branch')\ng.merge(g.branch('master'))\ng.merge([branch1, branch2])\n\ng.merge_base('branch1', 'branch2')\n\nr = g.add_remote(name, uri)  # Git::Remote\nr = g.add_remote(name, Git::Base)  # Git::Remote\n\ng.remotes  # array of Git::Remotes\ng.remote(name).fetch\ng.remote(name).remove\ng.remote(name).merge\ng.remote(name).merge(branch)\n\ng.fetch\ng.fetch(g.remotes.first)\ng.fetch('origin', {:ref =\u003e 'some/ref/head'} )\ng.fetch(all: true, force: true, depth: 2)\ng.fetch('origin', {:'update-head-ok' =\u003e true})\n\ng.pull\ng.pull(Git::Repo, Git::Branch) # fetch and a merge\n\ng.add_tag('tag_name') # returns Git::Tag\ng.add_tag('tag_name', 'object_reference')\ng.add_tag('tag_name', 'object_reference', {:options =\u003e 'here'})\ng.add_tag('tag_name', {:options =\u003e 'here'})\n\nOptions:\n  :a | :annotate\n  :d\n  :f\n  :m | :message\n  :s\n\ng.delete_tag('tag_name')\n\ng.repack\n\ng.push\ng.push(g.remote('name'))\n\n# delete remote branch\ng.push('origin', 'remote_branch_name', force: true, delete: true)\n\n# push all branches to remote at one time\ng.push('origin', all: true)\n\ng.worktree('/tmp/new_worktree').add\ng.worktree('/tmp/new_worktree', 'branch1').add\ng.worktree('/tmp/new_worktree').remove\ng.worktrees.prune\n```\n\nSome examples of more low-level index and tree operations\n\n```ruby\ng.with_temp_index do\n\n  g.read_tree(tree3) # calls self.index.read_tree\n  g.read_tree(tree1, :prefix =\u003e 'hi/')\n\n  c = g.commit_tree('message')\n  # or #\n  t = g.write_tree\n  c = g.commit_tree(t, :message =\u003e 'message', :parents =\u003e [sha1, sha2])\n\n  g.branch('branch_name').update_ref(c)\n  g.update_ref(branch, c)\n\n  g.with_temp_working do # new blank working directory\n    g.checkout\n    g.checkout(another_index)\n    g.commit # commits to temp_index\n  end\nend\n\ng.set_index('/path/to/index')\n\n\ng.with_index(path) do\n  # calls set_index, then switches back after\nend\n\ng.with_working(dir) do\n# calls set_working, then switches back after\nend\n\ng.with_temp_working(dir) do\n  g.checkout_index(:prefix =\u003e dir, :path_limiter =\u003e path)\n  # do file work\n  g.commit # commits to index\nend\n```\n\n## Ruby version support policy\n\nThis gem will be expected to function correctly on:\n\n* All non-EOL versions of the MRI Ruby on Mac, Linux, and Windows\n* The latest version of JRuby on Linux\n* The latest version of Truffle Ruby on Linus\n\nIt is this project's intent to support the latest version of JRuby on Windows\nonce the following JRuby bug is fixed:\n\njruby/jruby#7515\n\n## License\n\nLicensed under MIT License Copyright (c) 2008  Scott Chacon. See LICENSE for further\ndetails.\n","funding_links":[],"categories":["Developer Tools","Ruby","Happy Exploring 🤘"],"sub_categories":["git Tools"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fruby-git%2Fruby-git","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fruby-git%2Fruby-git","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fruby-git%2Fruby-git/lists"}