jbranchaud
jbranchaud

Reputation: 6087

How to programmatically create a commit with Rugged?

I am trying to programmatically create a commit to an existing repository using Rugged (the Ruby binding of libgit2). I have tried to follow the documentation provided in the Rugged README, but I think it doesn't quite match up with the current state of the codebase. I keep getting errors when I try running the following code:

require 'rugged'
# Create an instance of the existing repository
repo = Rugged::Repository.new('/full/path/to/repo')
# grab the current Time object for now
curr_time = Time.now
# write a new blob to the repository, hang on to the object id
oid = repo.write("Some content for the this blob - #{curr_time}.", 'blob')
# get the index for this repository
index = repo.index
# add the blob to the index
index.add(:path => 'newfile.txt', :oid => oid, :mode => 0100644)
curr_tree = index.write_tree(repo)
curr_ref = 'HEAD'
author = {:email=>'[email protected]',:time=>curr_time,:name=>'username'}
new_commit = Rugged::Commit.create(repo,
    :author => author,
    :message => "Some Commit Message at #{curr_time}.",
    :committer => author,
    :parents => [repo.head.target],
    :tree => curr_tree,
    :update_ref => curr_ref)

The current error I am getting says that there is something wrong with the index.add line. It says TypeError: wrong argument type nil (expected Fixnum).

Any help on better understanding how to create a new commit with rugged would be much appreciated.

Update

I just updated Rugged 0.16.0 to Rugged 0.18.0.gh.de28323 by running gem install --prerelease rugged. The code I detailed above seems to work now. I am not sure why it didn't work with 0.16.0. This person seemed to have the same problem which they detailed in this answer.

Upvotes: 6

Views: 1291

Answers (1)

Carlos Martín Nieto
Carlos Martín Nieto

Reputation: 5277

It looks like you're passing in nil to index.add where it doesn't accept one, and the error in that line is just a symptom of failing to check for errors earlier. The second parameter to repo.write should be a symbol, not a string, so it's most likely returning nil to signal an error. Passing :blob instead of 'blob' should fix it.

You can take a look at https://github.com/libgit2/docurium/blob/master/lib/docurium.rb#L115-L116 and surrounding code which we're using to generate libgit2's own documentation.

Upvotes: 3

Related Questions