Skip to content

Commit 25b2ad0

Browse files
committed
Extended Rugged example
1 parent 645ea37 commit 25b2ad0

File tree

1 file changed

+33
-2
lines changed

1 file changed

+33
-2
lines changed

book/B-embedding-git/sections/libgit2.asc

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,13 +69,44 @@ tree = commit.tree
6969
As you can see, the code is much less cluttered.
7070
Firstly, Rugged uses exceptions; it can raise things like `ConfigError` or `ObjectError` to signal error conditions.
7171
Secondly, there's no explicit freeing of resources, since Ruby is garbage-collected.
72-
Let's take a look at a slightly more complicated example:
72+
Let's take a look at a slightly more complicated example: crafting a commit from scratch
7373

7474
[source,ruby]
7575
----
76-
# TODO
76+
blob_id = repo.write("Blob contents", :blob) # <1>
77+
78+
index = repo.index
79+
index.read_tree(repo.head.target.tree)
80+
index.add(:path => 'newfile.txt', :oid => blob_id) # <2>
81+
82+
sig = {
83+
:email => "[email protected]",
84+
:name => "Bob User",
85+
:time => Time.now,
86+
}
87+
88+
commit_id = Rugged::Commit.create(repo,
89+
:tree => index.write_tree(repo), # <3>
90+
:author => sig,
91+
:committer => sig, # <4>
92+
:message => "Add newfile.txt", # <5>
93+
:parents => repo.empty? ? [] : [ repo.head.target ].compact, # <6>
94+
:update_ref => 'HEAD', # <7>
95+
)
96+
commit = repo.lookup(commit_id) # <8>
7797
----
7898

99+
<1> Create a new blob, which contains the contents of a new file.
100+
<2> Populate the index with the head commit's tree, and add the new file at the path `newfile.txt`.
101+
<3> This creates a new tree in the ODB, and uses it for the new commit.
102+
<4> We use the same signature for both the author and committer fields.
103+
<5> The commit message.
104+
<6> When creating a commit, you have to specify the new commit's parents.
105+
This uses the tip of HEAD for the single parent.
106+
<7> Rugged (and Libgit2) can optionally update a reference when making a commit.
107+
<8> The return value is the SHA-1 hash of a new commit object, which you can then use to get a `Commit` object.
108+
109+
79110
==== Advanced Functionality
80111

81112
// TODO: backend, remote

0 commit comments

Comments
 (0)