The Git Gem provides an API that can be used to create, read, and manipulate Git repositories by wrapping system calls to the git binary. The API can be used for working with Git in complex interactions including branching and merging, object inspection and manipulation, history, patch generation and more.
Installation
You can install it as a gem:
1
$ gem install git
or add it into a Gemfile (Bundler):
1 2 3
# Gemfile
gem 'git', '1.9.1'
Then, run bundle install.
1
$ bundle install
Usages
Major Objects
Git::Base - The object returned from a Git.open or Git.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. the Git::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 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.
Git::Status - returns from a @git.status command. It is an Enumerable that returns Git:Status::StatusFile objects for each object in git, which includes files in the working directory, 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 holds Git::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 the Git::Object::Commit objects that encompass your log query, which can be constructed through methods on the Git::Log object, like:
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('.')
And here are the operations that will need to write to your git repository.
# Sign a commit using the gpg key configured in the user.signingkey config setting g.config('user.signingkey', '0A46826A') g.commit('message', gpg_sign:true)
# Sign a commit using a specified gpg key key_id = '0A46826A' g.commit('message', gpg_sign: key_id)
g = Git.clone(repo, 'myrepo') g.chdir do new_file('test-file', 'blahblahblah') g.status.changed.each do |file| puts file.blob(:index).contents end end
g.reset # defaults to HEAD g.reset_hard(Git::Commit)
g.branch('new_branch') # creates new or fetches existing g.branch('new_branch').checkout g.branch('new_branch').delete g.branch('existing_branch').checkout g.branch('master').contains?('existing_branch')