Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
R

rugged

> 开发工具
Open source

ruby bindings to libgit2

2.3K stars0 likes1 views
WebsiteGitHub

About

ruby bindings to libgit2

Rugged

libgit2 bindings in Ruby

Rugged is a library for accessing libgit2 in Ruby. It gives you the speed and portability of libgit2 with the beauty of the Ruby language.

libgit2

libgit2 is a pure C implementation of the Git core methods. It's designed to be fast and portable. For more information about libgit2, check out libgit2's website or browse the libgit2 organization on GitHub.

Install

Rugged is a self-contained gem. You can install it by running:

$ gem install rugged

Prerequisites

You need to have CMake and pkg-config installed on your system to be able to build the included version of libgit2.

Debian, Including Ubuntu

All Debian-derived Linux distros provide apt:

bash
$ sudo apt install libgit2-dev cmake pkg-config

Note that you only need libgit2-dev if you want to build with the system libgit2 rather than the vendored version. In this case, note that the major and minor versions of libgit2 and rugged must match.

Mac

On OS X, after installing Homebrew, you can get the required packages with:

bash
$ brew install cmake pkg-config

Please follow the above in case installation of the gem fails with ERROR: CMake is required to build Rugged..

Options

If you want to build Rugged with HTTPS and SSH support, check out the list of optional libgit2 dependencies.

For SSH suport you have 2 options: libssh2 (recommended) or OpenSSH command execution (handy when you want to configure SSH behavior through .ssh/config):

  1. To use Libssh2, ensure libssh2 library is present and either pass the required CMAKE_FLAGS:
bash
CMAKE_FLAGS='-DUSE_SSH=ON' gem install rugged

or the --with-ssh build option:

bash
gem install rugged -- --with-ssh
  1. To execute external OpenSSH commands instead of libssh2, either pass the required CMAKE_FLAGS:
bash
CMAKE_FLAGS='-DUSE_SSH=exec' gem install rugged

or the --with-ssh-exec build option:

bash
gem install rugged -- --with-ssh-exec

If you're using bundler and want to bundle libgit2 with Rugged, you can use the :submodules option:

ruby
gem 'rugged', git: 'git://github.com/libgit2/rugged.git', submodules: true

If you would like to bundle rugged with SSH support add the --with-ssh or --with-ssh-exec build option to the bundler config:

bash
bundle config build.rugged --with-ssh

Usage

To load Rugged, you'll usually want to add something like this:

ruby
require 'rugged'

Use the system provided libgit2

By default, Rugged builds and uses a bundled version of libgit2. If you want to use the system library instead, you can install rugged as follows:

gem install rugged -- --use-system-libraries

Or if you are using bundler:

bundle config build.rugged --use-system-libraries
bundle install

However, note that Rugged does only support specific versions of libgit2.

Usage

Rugged gives you access to the many parts of a Git repository. You can read and write objects, walk a tree, access the staging area, and lots more. Let's look at each area individually.

Repositories

Instantiation

The repository is naturally central to Git. Rugged has a Repository class that you can instantiate with a path to open an existing repository :

ruby
repo = Rugged::Repository.new('path/to/my/repository')
# => #<Rugged::Repository:2228536260 {path: "path/to/my/repository/.git/"}>

You can create a new repository with init_at. Add a second parameter :bare to make a bare repository:

ruby
Rugged::Repository.init_at('.', :bare)

You can also let Rugged discover the path to the .git directory if you give it a subdirectory.

ruby
Rugged::Repository.discover("/Users/me/projects/repo/lib/subdir/")
# => "/Users/me/projects/repo/.git/"

Once your Repository instantiated (in the following examples, as repo), you can access or modify it.

Accessing a Repository

…

Writing to a Repository

There's a few ways to write to a repository. To write directly from your instantiated repository object:

ruby
sha = repo.write(content, type)

You can also use the Commit object directly to craft a commit; this is a bit more high-level, so it may be preferable:

…

Objects

Object is the main object class - it shouldn't be created directly, but all of these methods should be useful in their derived classes.

ruby
obj = repo.lookup(sha)
obj.oid  # object sha
obj.type # One of :commit, :tree, :blob or :tag

robj = obj.read_raw
str  = robj.data
int  = robj.len

There are four base object types in Git: blobs, commits, tags, and trees. Each of these object types have a corresponding class within Rugged.

Commit Objects

ruby
commit = repo.lookup('a0ae5566e3c8a3bddffab21022056f0b5e03ef07')
# => #<Rugged::Commit:2245304380>

commit.message
# => "Add `Repository#blob_at`\n"

commit.time
# => Sat Apr 07 21:23:25 -0700 2012

commit.author
# => {:email=>"tanoku@gmail.com", :name=>"Vicent Mart\303\255", :time=>Sun Apr 08 04:23:25 UTC 2012}

commit.tree
# => #<Rugged::Tree:2245269740>

commit.parents
# => [#<Rugged::Commit:2245264600 {message: "Merge pull request #47 from isaac/remotes\n\nAdd Rugged::Repository#remotes", tree: #<Rugged::Tree:2245264240 {oid: 6a2aee58a41fa007d07aa55565e2231f9b39b4a9}>]

You can also write new objects to the database this way:

ruby
author = {:email=>"[email protected]", :time=>Time.now, :name=>"Vicent Mart\303\255"}

Rugged::Commit.create(r,
	:author => author,
	:message => "Hello world\n\n",
	:committer => author,
	:parents => ["2cb831a8aea28b2c1b9c63385585b864e4d3bad1"],
	:tree => some_tree,
	:update_ref => "HEAD") #=> "f148106ca58764adc93ad4e2d6b1d168422b9796"

Tag Objects

ruby
tag  = repo.lookup(tag_sha)

object = tag.target
sha    = tag.target.oid
str    = tag.target_type # :commit, :tag, :blob
str    = tag.name        # "v1.0"
str    = tag.message
person = tag.tagger

Tree Objects

ruby
tree = repo.lookup('779fbb1e17e666832773a9825875300ea736c2da')
# => #<Rugged::Tree:2245194360>

# number of tree entries
tree.count

tree[0]           # or...
tree.first        # or...
tree.get_entry(0)
# => {:type=>:blob, :oid=>"99e7edb53db9355f10c6f2dfaa5a183f205d93bf", :filemode=>33188, :name=>".gitignore"}

The tree object is an Enumerable, so you can also do stuff like this:

ruby
tree.each { |e| puts e[:oid] }
tree.sort { |a, b| a[:oid] <=> b[:oid] }.map { |e| e[:name] }.join(':')

And there are some Rugged-specific methods, too:

ruby
tree.each_tree { |entry| puts entry[:name] }  # list subdirs
tree.each_blob { |entry| puts entry[:name] }  # list only files

You can also write trees with the TreeBuilder:

…

Blob Objects

Blob objects represent the data in the files of a Tree Object.

ruby
blob = repo.lookup('e1253910439ea902cf49be8a9f02f3c08d89ac73')
blob.content # => Gives you the content of the blob.

Streaming Blob Objects

There is currently no way to stream data from a blob, because libgit2 itself does not (yet) support streaming blobs out of the git object database. While there are hooks and interfaces for supporting it, the default file system backend always loads the entire blob contents into memory.

If you need to access a Blob object through an IO-like API, you can wrap it with the StringIO class. Note that the only advantage here is a stream-compatible interface, the complete blob object will still be loaded into memory. Below is an example for streaming a Blob using the Sinatra framework:

ruby
# Sinatra endpoint
get "/blobs/:sha" do
  repo = Rugged::Repository.new(my_repo_path)
  blob = repo.lookup params[:sha]

  headers({
    "Vary" => "Accept",
    "Connection" => "keep-alive",
    "Transfer-Encoding" => "chunked",
    "Content-Type" => "application/octet-stream",
  })

  stream do |out|
    StringIO.new(blob.content).each(8000) do |chunk|
      out << chunk
    end
  end
end

Commit Walker

Rugged::Walker is a class designed to help you traverse a set of commits over a repository.

You first push head SHAs onto the walker, and then call next to get a list of the reachable commit objects one at a time. You can also hide() commits if you are not interested in anything beneath them (useful in situations like when you're running something like git log master ^origin/master).

ruby
walker = Rugged::Walker.new(repo)
walker.sorting(Rugged::SORT_TOPO | Rugged::SORT_REVERSE) # optional
walker.push(hex_sha_interesting)
walker.hide(hex_sha_uninteresting)
walker.each { |c| puts c.inspect }
walker.reset

Index ("staging") area

We can inspect and manipulate the Git Index as well. To work with the index inside an existing repository, instantiate it by using the Repository.index method instead of manually opening the Index by its path.

ruby
index = Rugged::Index.new(path)

# Re-read the index file from disk.
index.reload

# Count up index entries.
count = index.count

# The collection of index entries.
index.entries

# Iterating over index entries.
index.each { |i| puts i.inspect }

# Get a particular entry in the index.
index[path]

# Unstage.
index.remove(path)

# Stage. Also updates existing entry if there is one.
index.add(ientry)

# Stage. Create ientry from file in path, updates the index.
index.add(path)

Refs

You can access references through the Rugged::ReferenceCollection object returned by Repository#references.

ruby
ref = repo.references["refs/heads/master"]

sha = ref.target_id
str = ref.type   # :direct
str = ref.name   # "refs/heads/master"

You can also easily iterate over all references:

ruby
repo.references.each do |ref|
  puts ref.name
end

Or only over references that match the given pattern (glob):

ruby
repo.references.each("refs/tags/*") do |ref|
  puts ref.name
end

It is also easy to create, update, rename or delete a reference:

ruby
ref = repo.references.create("refs/heads/unit_test", some_commit_sha)

repo.references.update(ref, new_sha) # or...
repo.references.update("refs/heads/unit_test", new_sha)

repo.references.rename(ref, "refs/heads/blead") # or...
repo.references.rename("refs/heads/unit_test", "refs/heads/blead")

repo.references.delete(ref) # or...
repo.references.delete("refs/heads/unit_test") # or...

Finally, you can access the reflog for any branch:

ruby
ref = repo.references["refs/heads/master"]
entry = ref.log.first
sha   = entry[:id_old]
sha   = entry[:id_new]
str   = entry[:message]
prsn  = entry[:committer]

Branches

The Rugged::BranchCollection object returned by Repository#branches will help you with all of your branch-related needs.

Iterate over all branches:

ruby
repo.branches.each_name().sort
# => ["master", "origin/HEAD", "origin/master", "origin/packed"]

repo.branches.each_name(:local).sort
# => ["master"]

repo.branches.each_name(:remote).sort
# => ["origin/HEAD", "origin/master", "origin/packed"]

Look up branches and get attributes:

ruby
branch = repo.branches["master"]
branch.name # => 'master'
branch.canonical_name # => 'refs/heads/master'

Look up the id for the target of a branch:

ruby
repo.branches["master"].target_id
# => "36060c58702ed4c2a40832c51758d5344201d89a"

Creation and deletion:

ruby
branch = repo.branches.create("test_branch", "HEAD")

repo.branches.rename("test_branch", "new_branch") # or...
repo.branches.rename("refs/heads/test_branch", "new_branch") # or...
repo.branches.rename(ref, "new_branch") # or...

repo.branches.delete("test_branch") # or...
repo.branches.delete("refs/heads/test_branch") # or...
repo.branches.delete(ref) # or...

Diffs

There are various ways to

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Cgitlibgit2ruby

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category开发工具
PricingOpen source

> Related tools

V
VS Code
流行的开源代码编辑器
G
Git
分布式版本控制系统
V
Vite
下一代前端构建工具