Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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.

License

NotificationsYou must be signed in to change notification settings

ruby-git/ruby-git

Repository files navigation

Gem VersionDocumentationChange LogBuild StatusConventional Commits

📢 Default Branch Rename 📢

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.

📢 We've Switched to Conventional Commits 📢

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

Summary

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

Install the gem and add to the application's Gemfile by executing:

bundle add git

to 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 git

to install version 1.x:

gem install git --version"~> 1.19"

Major Objects

Git::Base - The object returned from aGit.open orGit.clone. Most major actions are called from this object.

Git::Object - The base object for your tree, blob and commit objects, returned from@git.gtree or@git.object calls. theGit::AbstractObject will have most of the calls in common for all those objects.

Git::Diff - returns from a@git.diff command. It is an Enumerable that returnsGit::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.

Git::Status - returns from a@git.status command. It is an Enumerable that returnsGit:Status::StatusFile objects for each object in git, which includes files in the workingdirectory, in the index and in the repository. Similar to running 'git status' on the command line to determine untracked and changed files.

Git::Branches - Enumerable object that holdsGit::Branch objects. You can call .local or .remote on it to filter to just your local or remote branches.

Git::Remote- A reference to a remote repository that is tracked by this repository.

Git::Log - An Enumerable object that references all theGit::Object::Commitobjects that encompass your log query, which can be constructed through methods ontheGit::Log object, like:

git.log.max_count(:all).object('README.md').since('10 years ago').between('v1.0.7','HEAD').map{ |commit|commit.sha}

A maximum of 30 commits are returned ifmax_count is not called. To get all commitsthat match the log query, callmax_count(:all).

Note thatgit.log.all adds the--all option to the underlyinggit log command.This asks for the logs of all refs (basically all commits reachable by HEAD,branches, and tags). This does not control the maximum number of commits returned. Tocontrol how many commits are returned, you should callmax_count.

Git::Worktrees - Enumerable object that holdsGit::Worktree objects.

Errors Raised By This Gem

The 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 bythis gem unless you need more specific error handling.

begin# some git operationrescueGit::Error=>eputs"An error occurred:#{e.message}"end

SeeGit::Error for more information.

Specifying And Handling Timeouts

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 seconds

The 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::SignaledError

If 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 terminatedendend

Examples

Here are a bunch of examples of how to use the Ruby/Git package.

Require the 'git' gem.

require'git'

Git env config

Git.configuredo |config|# If you want to use a custom git binaryconfig.binary_path='/git/bin/path'# If you need to use a custom SSH scriptconfig.git_ssh='/path/to/ssh/script'end

NOTE: Another way to specify where is thegit binary is through the environment variableGIT_PATH

Here are the operations that need read permission only.

g=Git.open(working_dir,:log=>Logger.new(STDOUT))g.indexg.index.readable?g.index.writable?g.repog.dir# ls-tree with recursion into subtrees (list files)g.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 commitsg.logg.log(200)# 200 most recent commitsg.log.since('2 weeks ago')# default count of commits since 2 weeks ago.g.log(200).since('2 weeks ago')# commits since 2 weeks ago, limited to 200.g.log.between('v2.5','v2.6')g.log.each{|l|putsl.sha}g.gblob('v2.5:Makefile').log.since('2 weeks ago')g.object('HEAD^').to_s# git show / git rev-parseg.object('HEAD^').contentsg.object('v2.5:Makefile').sizeg.object('v2.5:Makefile').shag.gtree(treeish)g.gblob(treeish)g.gcommit(treeish)commit=g.gcommit('1cc8667014381')commit.gtreecommit.parent.shacommit.parents.sizecommit.author.namecommit.author.emailcommit.author.date.strftime("%m-%d-%y")commit.committer.namecommit.date.strftime("%m-%d-%y")commit.messagetree=g.gtree("HEAD^{tree}")tree.blobstree.subtreestree.children# blobs and subtreesg.rev_parse('v2.0.0:README.md')g.branches# returns Git::Branch objectsg.branches.localg.current_branchg.branches.remoteg.branches[:main].gcommitg.branches['origin/main'].gcommitg.grep('hello')# implies HEADg.blob('v2.5:Makefile').grep('hello')g.tag('v2.5').grep('hello','docs/')g.describe()g.describe('0djf2aa')g.describe('HEAD',{:all=>true,:tags=>true})g.diff(commit1,commit2).sizeg.diff(commit1,commit2).statsg.diff(commit1,commit2).name_statusg.gtree('v2.5').diff('v2.6').insertionsg.diff('gitsearch1','v2.5').path('lib/')g.diff('gitsearch1',@git.gtree('v2.5'))g.diff('gitsearch1','v2.5').path('docs/').patchg.gtree('v2.5').diff('v2.6').patchg.gtree('v2.5').diff('v2.6').eachdo |file_diff|putsfile_diff.pathputsfile_diff.patchputsfile_diff.blob(:src).contentsendg.worktrees# returns Git::Worktree objectsg.worktrees.countg.worktrees.eachdo |worktree|worktree.dirworktree.gcommitworktree.to_sendg.config('user.name')# returns 'Scott Chacon'g.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.#g=Git.clone(git_uri,destination_path,:config=>['core.sshCommand=ssh -i /home/user/.ssh/id_rsa','submodule.recurse=true'])g.tags# returns array of Git::Tag objectsg.show()g.show('HEAD')g.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.

g=Git.initGit.init('project')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'# Clone into the ruby-git directoryg=Git.clone(git_url)# Clone into /tmp/clone/ruby-git-cleanname='ruby-git-clean'path='/tmp/clone'g=Git.clone(git_url,name,:path=>path)g.dir#=> /tmp/clone/ruby-git-cleang.config('user.name','Scott Chacon')g.config('user.email','email@email.com')# Clone can take a filter to tell the serve to send a partial cloneg=Git.clone(git_url,name,:path=>path,:filter=>'tree:0')# Clone can take an optional loggerlogger=Logger.newg=Git.clone(git_url,NAME,:log=>logger)g.add# git add -- "."g.add(:all=>true)# git add --all -- "."g.add('file_path')# git add -- "file_path"g.add(['file_path_1','file_path_2'])# git add -- "file_path_1" "file_path_2"g.remove()# git rm -f -- "."g.remove('file.txt')# git rm -f -- "file.txt"g.remove(['file.txt','file2.txt'])# git rm -f -- "file.txt" "file2.txt"g.remove('file.txt',:recursive=>true)# git rm -f -r -- "file.txt"g.remove('file.txt',:cached=>true)# git rm -f --cached -- "file.txt"g.commit('message')g.commit_all('message')# Sign a commit using the gpg key configured in the user.signingkey config settingg.config('user.signingkey','0A46826A')g.commit('message',gpg_sign:true)# Sign a commit using a specified gpg keykey_id='0A46826A'g.commit('message',gpg_sign:key_id)# Skip signing a commit (overriding any global gpgsign setting)g.commit('message',no_gpg_sign:true)g=Git.clone(repo,'myrepo')g.chdirdonew_file('test-file','blahblahblah')g.status.changed.eachdo |file|putsfile.blob(:index).contentsendendg.reset# defaults to HEADg.reset_hard(Git::Commit)g.branch('new_branch')# creates new or fetches existingg.branch('new_branch').checkoutg.branch('new_branch').deleteg.branch('existing_branch').checkoutg.branch('main').contains?('existing_branch')# delete remote branchg.push('origin','remote_branch_name',force:true,delete:true)g.checkout('new_branch')g.checkout('new_branch',new_branch:true,start_point:'main')g.checkout(g.branch('new_branch'))g.branch(name).merge(branch2)g.branch(branch2).merge# merges HEAD with branch2g.branch(name).in_branch(message){# add files }  # auto-commitsg.merge('new_branch')g.merge('new_branch','merge commit message',no_ff:true)g.merge('origin/remote_branch')g.merge(g.branch('main'))g.merge([branch1,branch2])g.merge_base('branch1','branch2')r=g.add_remote(name,uri)# Git::Remoter=g.add_remote(name,Git::Base)# Git::Remoteg.remotes# array of Git::Remotesg.remote(name).fetchg.remote(name).removeg.remote(name).mergeg.remote(name).merge(branch)g.fetchg.fetch(g.remotes.first)g.fetch('origin',{:ref=>'some/ref/head'})g.fetch(all:true,force:true,depth:2)g.fetch('origin',{:'update-head-ok'=>true})g.pullg.pull(Git::Repo,Git::Branch)# fetch and a mergeg.add_tag('tag_name')# returns Git::Tagg.add_tag('tag_name','object_reference')g.add_tag('tag_name','object_reference',{:options=>'here'})g.add_tag('tag_name',{:options=>'here'})Options::a |:annotate:d:f:m |:message:sg.delete_tag('tag_name')g.repackg.pushg.push(g.remote('name'))# delete remote branchg.push('origin','remote_branch_name',force:true,delete:true)# push all branches to remote at one timeg.push('origin',all:true)g.worktree('/tmp/new_worktree').addg.worktree('/tmp/new_worktree','branch1').addg.worktree('/tmp/new_worktree').removeg.worktrees.prune

Some examples of more low-level index and tree operations

g.with_temp_indexdog.read_tree(tree3)# calls self.index.read_treeg.read_tree(tree1,:prefix=>'hi/')c=g.commit_tree('message')# or #t=g.write_treec=g.commit_tree(t,:message=>'message',:parents=>[sha1,sha2])g.branch('branch_name').update_ref(c)g.update_ref(branch,c)g.with_temp_workingdo# new blank working directoryg.checkoutg.checkout(another_index)g.commit# commits to temp_indexendendg.set_index('/path/to/index')g.with_index(path)do# calls set_index, then switches back afterendg.with_working(dir)do# calls set_working, then switches back afterendg.with_temp_working(dir)dog.checkout_index(:prefix=>dir,:path_limiter=>path)# do file workg.commit# commits to indexend

Ruby version support policy

This gem will be expected to function correctly on:

  • All non-EOL versions of the MRI Ruby on Mac, Linux, and Windows
  • The latest version of JRuby on Linux
  • The latest version of Truffle Ruby on Linus

It is this project's intent to support the latest version of JRuby on Windowsonce the following JRuby bug is fixed:

jruby/jruby#7515

License

Licensed under MIT License Copyright (c) 2008 Scott Chacon. See LICENSE for furtherdetails.

About

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.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors107

Languages


[8]ページ先頭

©2009-2025 Movatter.jp