]>
git.proxmox.com Git - libgit2.git/blob - examples/general.c
2 * libgit2 "general" example - shows basic libgit2 concepts
4 * Written by the libgit2 contributors
6 * To the extent possible under law, the author(s) have dedicated all copyright
7 * and related and neighboring rights to this software to the public domain
8 * worldwide. This software is distributed without any warranty.
10 * You should have received a copy of the CC0 Public Domain Dedication along
11 * with this software. If not, see
12 * <http://creativecommons.org/publicdomain/zero/1.0/>.
16 * [**libgit2**][lg] is a portable, pure C implementation of the Git core
17 * methods provided as a re-entrant linkable library with a solid API,
18 * allowing you to write native speed custom Git applications in any
19 * language which supports C bindings.
21 * This file is an example of using that API in a real, compilable C file.
22 * As the API is updated, this file will be updated to demonstrate the new
25 * If you're trying to write something in C using [libgit2][lg], you should
26 * also check out the generated [API documentation][ap]. We try to link to
27 * the relevant sections of the API docs in each section in this file.
29 * **libgit2** (for the most part) only implements the core plumbing
30 * functions, not really the higher level porcelain stuff. For a primer on
31 * Git Internals that you will need to know to work with Git at this level,
32 * check out [Chapter 10][pg] of the Pro Git book.
34 * [lg]: http://libgit2.github.com
35 * [ap]: http://libgit2.github.com/libgit2
36 * [pg]: https://git-scm.com/book/en/v2/Git-Internals-Plumbing-and-Porcelain
42 * Including the `git2.h` header will include all the other libgit2 headers
43 * that you need. It should be the only thing you need to include in order
44 * to compile properly and get all the libgit2 API.
50 static void oid_parsing(git_oid
*out
);
51 static void object_database(git_repository
*repo
, git_oid
*oid
);
52 static void commit_writing(git_repository
*repo
);
53 static void commit_parsing(git_repository
*repo
);
54 static void tag_parsing(git_repository
*repo
);
55 static void tree_parsing(git_repository
*repo
);
56 static void blob_parsing(git_repository
*repo
);
57 static void revwalking(git_repository
*repo
);
58 static void index_walking(git_repository
*repo
);
59 static void reference_listing(git_repository
*repo
);
60 static void config_files(const char *repo_path
, git_repository
*repo
);
63 * Almost all libgit2 functions return 0 on success or negative on error.
64 * This is not production quality error checking, but should be sufficient
67 static void check_error(int error_code
, const char *action
)
69 const git_error
*error
= giterr_last();
73 printf("Error %d %s - %s\n", error_code
, action
,
74 (error
&& error
->message
) ? error
->message
: "???");
79 int main (int argc
, char** argv
)
87 * Initialize the library, this will set up any global state which libgit2 needs
88 * including threading and crypto
93 * ### Opening the Repository
95 * There are a couple of methods for opening a repository, this being the
96 * simplest. There are also [methods][me] for specifying the index file
97 * and work tree locations, here we assume they are in the normal places.
99 * (Try running this program against tests/resources/testrepo.git.)
101 * [me]: http://libgit2.github.com/libgit2/#HEAD/group/repository
103 repo_path
= (argc
> 1) ? argv
[1] : "/opt/libgit2-test/.git";
105 error
= git_repository_open(&repo
, repo_path
);
106 check_error(error
, "opening repository");
109 object_database(repo
, &oid
);
110 commit_writing(repo
);
111 commit_parsing(repo
);
117 reference_listing(repo
);
118 config_files(repo_path
, repo
);
121 * Finally, when you're done with the repository, you can free it as well.
123 git_repository_free(repo
);
129 * ### SHA-1 Value Conversions
131 static void oid_parsing(git_oid
*oid
)
133 char out
[GIT_OID_HEXSZ
+1];
134 char hex
[] = "4a202b346bb0fb0db7eff3cffeb3c70babbd2045";
136 printf("*Hex to Raw*\n");
139 * For our first example, we will convert a 40 character hex value to the
140 * 20 byte raw SHA1 value.
142 * The `git_oid` is the structure that keeps the SHA value. We will use
143 * this throughout the example for storing the value of the current SHA
144 * key we're working with.
146 git_oid_fromstr(oid
, hex
);
148 // Once we've converted the string into the oid value, we can get the raw
149 // value of the SHA by accessing `oid.id`
151 // Next we will convert the 20 byte raw SHA1 value to a human readable 40
153 printf("\n*Raw to Hex*\n");
154 out
[GIT_OID_HEXSZ
] = '\0';
157 * If you have a oid, you can easily get the hex value of the SHA as well.
159 git_oid_fmt(out
, oid
);
162 * If you have a oid, you can easily get the hex value of the SHA as well.
164 git_oid_fmt(out
, oid
);
165 printf("SHA hex string: %s\n", out
);
169 * ### Working with the Object Database
171 * **libgit2** provides [direct access][odb] to the object database. The
172 * object database is where the actual objects are stored in Git. For
173 * working with raw objects, we'll need to get this structure from the
176 * [odb]: http://libgit2.github.com/libgit2/#HEAD/group/odb
178 static void object_database(git_repository
*repo
, git_oid
*oid
)
180 char oid_hex
[GIT_OID_HEXSZ
+1] = { 0 };
181 const unsigned char *data
;
182 const char *str_type
;
188 git_repository_odb(&odb
, repo
);
191 * #### Raw Object Reading
194 printf("\n*Raw Object Read*\n");
197 * We can read raw objects directly from the object database if we have
198 * the oid (SHA) of the object. This allows us to access objects without
199 * knowing their type and inspect the raw bytes unparsed.
201 error
= git_odb_read(&obj
, odb
, oid
);
202 check_error(error
, "finding object in repository");
205 * A raw object only has three properties - the type (commit, blob, tree
206 * or tag), the size of the raw data and the raw, unparsed data itself.
207 * For a commit or tag, that raw data is human readable plain ASCII
208 * text. For a blob it is just file contents, so it could be text or
209 * binary data. For a tree it is a special binary format, so it's unlikely
210 * to be hugely helpful as a raw object.
212 data
= (const unsigned char *)git_odb_object_data(obj
);
213 otype
= git_odb_object_type(obj
);
216 * We provide methods to convert from the object type which is an enum, to
217 * a string representation of that value (and vice-versa).
219 str_type
= git_object_type2string(otype
);
220 printf("object length and type: %d, %s\nobject data: %s\n",
221 (int)git_odb_object_size(obj
),
225 * For proper memory management, close the object when you are done with
226 * it or it will leak memory.
228 git_odb_object_free(obj
);
231 * #### Raw Object Writing
234 printf("\n*Raw Object Write*\n");
237 * You can also write raw object data to Git. This is pretty cool because
238 * it gives you direct access to the key/value properties of Git. Here
239 * we'll write a new blob object that just contains a simple string.
240 * Notice that we have to specify the object type as the `git_otype` enum.
242 git_odb_write(oid
, odb
, "test data", sizeof("test data") - 1, GIT_OBJ_BLOB
);
245 * Now that we've written the object, we can check out what SHA1 was
246 * generated when the object was written to our database.
248 git_oid_fmt(oid_hex
, oid
);
249 printf("Written Object: %s\n", oid_hex
);
252 * Free the object database after usage.
258 * #### Writing Commits
260 * libgit2 provides a couple of methods to create commit objects easily as
261 * well. There are four different create signatures, we'll just show one
262 * of them here. You can read about the other ones in the [commit API
265 * [cd]: http://libgit2.github.com/libgit2/#HEAD/group/commit
267 static void commit_writing(git_repository
*repo
)
269 git_oid tree_id
, parent_id
, commit_id
;
272 git_signature
*author
, *committer
;
273 char oid_hex
[GIT_OID_HEXSZ
+1] = { 0 };
275 printf("\n*Commit Writing*\n");
278 * Creating signatures for an authoring identity and time is simple. You
279 * will need to do this to specify who created a commit and when. Default
280 * values for the name and email should be found in the `user.name` and
281 * `user.email` configuration options. See the `config` section of this
282 * example file to see how to access config values.
284 git_signature_new(&author
,
285 "Scott Chacon", "schacon@gmail.com", 123456789, 60);
286 git_signature_new(&committer
,
287 "Scott A Chacon", "scott@github.com", 987654321, 90);
290 * Commit objects need a tree to point to and optionally one or more
291 * parents. Here we're creating oid objects to create the commit with,
292 * but you can also use
294 git_oid_fromstr(&tree_id
, "f60079018b664e4e79329a7ef9559c8d9e0378d1");
295 git_tree_lookup(&tree
, repo
, &tree_id
);
296 git_oid_fromstr(&parent_id
, "5b5b025afb0b4c913b4c338a42934a3863bf3644");
297 git_commit_lookup(&parent
, repo
, &parent_id
);
300 * Here we actually create the commit object with a single call with all
301 * the values we need to create the commit. The SHA key is written to the
302 * `commit_id` variable here.
305 &commit_id
, /* out id */
307 NULL
, /* do not update the HEAD */
310 NULL
, /* use default message encoding */
316 * Now we can take a look at the commit SHA we've generated.
318 git_oid_fmt(oid_hex
, &commit_id
);
319 printf("New Commit: %s\n", oid_hex
);
322 * Free all objects used in the meanwhile.
325 git_commit_free(parent
);
326 git_signature_free(author
);
327 git_signature_free(committer
);
333 * libgit2 has methods to parse every object type in Git so you don't have
334 * to work directly with the raw data. This is much faster and simpler
335 * than trying to deal with the raw data yourself.
339 * #### Commit Parsing
341 * [Parsing commit objects][pco] is simple and gives you access to all the
342 * data in the commit - the author (name, email, datetime), committer
343 * (same), tree, message, encoding and parent(s).
345 * [pco]: http://libgit2.github.com/libgit2/#HEAD/group/commit
347 static void commit_parsing(git_repository
*repo
)
349 const git_signature
*author
, *cmtter
;
350 git_commit
*commit
, *parent
;
352 char oid_hex
[GIT_OID_HEXSZ
+1];
354 unsigned int parents
, p
;
358 printf("\n*Commit Parsing*\n");
360 git_oid_fromstr(&oid
, "8496071c1b46c854b31185ea97743be6a8774479");
362 error
= git_commit_lookup(&commit
, repo
, &oid
);
363 check_error(error
, "looking up commit");
366 * Each of the properties of the commit object are accessible via methods,
367 * including commonly needed variations, such as `git_commit_time` which
368 * returns the author time and `git_commit_message` which gives you the
369 * commit message (as a NUL-terminated string).
371 message
= git_commit_message(commit
);
372 author
= git_commit_author(commit
);
373 cmtter
= git_commit_committer(commit
);
374 time
= git_commit_time(commit
);
377 * The author and committer methods return [git_signature] structures,
378 * which give you name, email and `when`, which is a `git_time` structure,
379 * giving you a timestamp and timezone offset.
381 printf("Author: %s (%s)\nCommitter: %s (%s)\nDate: %s\nMessage: %s\n",
382 author
->name
, author
->email
,
383 cmtter
->name
, cmtter
->email
,
384 ctime(&time
), message
);
387 * Commits can have zero or more parents. The first (root) commit will
388 * have no parents, most commits will have one (i.e. the commit it was
389 * based on) and merge commits will have two or more. Commits can
390 * technically have any number, though it's rare to have more than two.
392 parents
= git_commit_parentcount(commit
);
393 for (p
= 0;p
< parents
;p
++) {
394 memset(oid_hex
, 0, sizeof(oid_hex
));
396 git_commit_parent(&parent
, commit
, p
);
397 git_oid_fmt(oid_hex
, git_commit_id(parent
));
398 printf("Parent: %s\n", oid_hex
);
399 git_commit_free(parent
);
402 git_commit_free(commit
);
408 * You can parse and create tags with the [tag management API][tm], which
409 * functions very similarly to the commit lookup, parsing and creation
410 * methods, since the objects themselves are very similar.
412 * [tm]: http://libgit2.github.com/libgit2/#HEAD/group/tag
414 static void tag_parsing(git_repository
*repo
)
420 const char *name
, *message
;
423 printf("\n*Tag Parsing*\n");
426 * We create an oid for the tag object if we know the SHA and look it up
427 * the same way that we would a commit (or any other object).
429 git_oid_fromstr(&oid
, "b25fa35b38051e4ae45d4222e795f9df2e43f1d1");
431 error
= git_tag_lookup(&tag
, repo
, &oid
);
432 check_error(error
, "looking up tag");
435 * Now that we have the tag object, we can extract the information it
436 * generally contains: the target (usually a commit object), the type of
437 * the target object (usually 'commit'), the name ('v1.0'), the tagger (a
438 * git_signature - name, email, timestamp), and the tag message.
440 git_tag_target((git_object
**)&commit
, tag
);
441 name
= git_tag_name(tag
); /* "test" */
442 type
= git_tag_target_type(tag
); /* GIT_OBJ_COMMIT (otype enum) */
443 message
= git_tag_message(tag
); /* "tag message\n" */
444 printf("Tag Name: %s\nTag Type: %s\nTag Message: %s\n",
445 name
, git_object_type2string(type
), message
);
448 * Free both the commit and tag after usage.
450 git_commit_free(commit
);
457 * [Tree parsing][tp] is a bit different than the other objects, in that
458 * we have a subtype which is the tree entry. This is not an actual
459 * object type in Git, but a useful structure for parsing and traversing
462 * [tp]: http://libgit2.github.com/libgit2/#HEAD/group/tree
464 static void tree_parsing(git_repository
*repo
)
466 const git_tree_entry
*entry
;
472 printf("\n*Tree Parsing*\n");
475 * Create the oid and lookup the tree object just like the other objects.
477 git_oid_fromstr(&oid
, "f60079018b664e4e79329a7ef9559c8d9e0378d1");
478 git_tree_lookup(&tree
, repo
, &oid
);
481 * Getting the count of entries in the tree so you can iterate over them
484 cnt
= git_tree_entrycount(tree
); /* 2 */
485 printf("tree entries: %d\n", (int) cnt
);
487 entry
= git_tree_entry_byindex(tree
, 0);
488 printf("Entry name: %s\n", git_tree_entry_name(entry
)); /* "README" */
491 * You can also access tree entries by name if you know the name of the
492 * entry you're looking for.
494 entry
= git_tree_entry_byname(tree
, "README");
495 git_tree_entry_name(entry
); /* "README" */
498 * Once you have the entry object, you can access the content or subtree
499 * (or commit, in the case of submodules) that it points to. You can also
500 * get the mode if you want.
502 git_tree_entry_to_object(&obj
, repo
, entry
); /* blob */
505 * Remember to close the looked-up object and tree once you are done using it
507 git_object_free(obj
);
514 * The last object type is the simplest and requires the least parsing
515 * help. Blobs are just file contents and can contain anything, there is
516 * no structure to it. The main advantage to using the [simple blob
517 * api][ba] is that when you're creating blobs you don't have to calculate
518 * the size of the content. There is also a helper for reading a file
519 * from disk and writing it to the db and getting the oid back so you
520 * don't have to do all those steps yourself.
522 * [ba]: http://libgit2.github.com/libgit2/#HEAD/group/blob
524 static void blob_parsing(git_repository
*repo
)
529 printf("\n*Blob Parsing*\n");
531 git_oid_fromstr(&oid
, "1385f264afb75a56a5bec74243be9b367ba4ca08");
532 git_blob_lookup(&blob
, repo
, &oid
);
535 * You can access a buffer with the raw contents of the blob directly.
536 * Note that this buffer may not be contain ASCII data for certain blobs
537 * (e.g. binary files): do not consider the buffer a NULL-terminated
538 * string, and use the `git_blob_rawsize` attribute to find out its exact
541 printf("Blob Size: %ld\n", (long)git_blob_rawsize(blob
)); /* 8 */
542 git_blob_rawcontent(blob
); /* "content" */
545 * Free the blob after usage.
553 * The libgit2 [revision walking api][rw] provides methods to traverse the
554 * directed graph created by the parent pointers of the commit objects.
555 * Since all commits point back to the commit that came directly before
556 * them, you can walk this parentage as a graph and find all the commits
557 * that were ancestors of (reachable from) a given starting point. This
558 * can allow you to create `git log` type functionality.
560 * [rw]: http://libgit2.github.com/libgit2/#HEAD/group/revwalk
562 static void revwalking(git_repository
*repo
)
564 const git_signature
*cauth
;
571 printf("\n*Revwalking*\n");
573 git_oid_fromstr(&oid
, "5b5b025afb0b4c913b4c338a42934a3863bf3644");
576 * To use the revwalker, create a new walker, tell it how you want to sort
577 * the output and then push one or more starting points onto the walker.
578 * If you want to emulate the output of `git log` you would push the SHA
579 * of the commit that HEAD points to into the walker and then start
580 * traversing them. You can also 'hide' commits that you want to stop at
581 * or not see any of their ancestors. So if you want to emulate `git log
582 * branch1..branch2`, you would push the oid of `branch2` and hide the oid
585 git_revwalk_new(&walk
, repo
);
586 git_revwalk_sorting(walk
, GIT_SORT_TOPOLOGICAL
| GIT_SORT_REVERSE
);
587 git_revwalk_push(walk
, &oid
);
590 * Now that we have the starting point pushed onto the walker, we start
591 * asking for ancestors. It will return them in the sorting order we asked
592 * for as commit oids. We can then lookup and parse the committed pointed
593 * at by the returned OID; note that this operation is specially fast
594 * since the raw contents of the commit object will be cached in memory
596 while ((git_revwalk_next(&oid
, walk
)) == 0) {
597 error
= git_commit_lookup(&wcommit
, repo
, &oid
);
598 check_error(error
, "looking up commit during revwalk");
600 cmsg
= git_commit_message(wcommit
);
601 cauth
= git_commit_author(wcommit
);
602 printf("%s (%s)\n", cmsg
, cauth
->email
);
604 git_commit_free(wcommit
);
608 * Like the other objects, be sure to free the revwalker when you're done
609 * to prevent memory leaks. Also, make sure that the repository being
610 * walked it not deallocated while the walk is in progress, or it will
611 * result in undefined behavior
613 git_revwalk_free(walk
);
617 * ### Index File Manipulation *
618 * The [index file API][gi] allows you to read, traverse, update and write
619 * the Git index file (sometimes thought of as the staging area).
621 * [gi]: http://libgit2.github.com/libgit2/#HEAD/group/index
623 static void index_walking(git_repository
*repo
)
626 unsigned int i
, ecount
;
628 printf("\n*Index Walking*\n");
631 * You can either open the index from the standard location in an open
632 * repository, as we're doing here, or you can open and manipulate any
633 * index file with `git_index_open_bare()`. The index for the repository
634 * will be located and loaded from disk.
636 git_repository_index(&index
, repo
);
639 * For each entry in the index, you can get a bunch of information
640 * including the SHA (oid), path and mode which map to the tree objects
641 * that are written out. It also has filesystem properties to help
642 * determine what to inspect for changes (ctime, mtime, dev, ino, uid,
643 * gid, file_size and flags) All these properties are exported publicly in
644 * the `git_index_entry` struct
646 ecount
= git_index_entrycount(index
);
647 for (i
= 0; i
< ecount
; ++i
) {
648 const git_index_entry
*e
= git_index_get_byindex(index
, i
);
650 printf("path: %s\n", e
->path
);
651 printf("mtime: %d\n", (int)e
->mtime
.seconds
);
652 printf("fs: %d\n", (int)e
->file_size
);
655 git_index_free(index
);
661 * The [reference API][ref] allows you to list, resolve, create and update
662 * references such as branches, tags and remote references (everything in
663 * the .git/refs directory).
665 * [ref]: http://libgit2.github.com/libgit2/#HEAD/group/reference
667 static void reference_listing(git_repository
*repo
)
669 git_strarray ref_list
;
672 printf("\n*Reference Listing*\n");
675 * Here we will implement something like `git for-each-ref` simply listing
676 * out all available references and the object SHA they resolve to.
678 * Now that we have the list of reference names, we can lookup each ref
679 * one at a time and resolve them to the SHA, then print both values out.
682 git_reference_list(&ref_list
, repo
);
684 for (i
= 0; i
< ref_list
.count
; ++i
) {
686 char oid_hex
[GIT_OID_HEXSZ
+1] = GIT_OID_HEX_ZERO
;
689 refname
= ref_list
.strings
[i
];
690 git_reference_lookup(&ref
, repo
, refname
);
692 switch (git_reference_type(ref
)) {
694 git_oid_fmt(oid_hex
, git_reference_target(ref
));
695 printf("%s [%s]\n", refname
, oid_hex
);
698 case GIT_REF_SYMBOLIC
:
699 printf("%s => %s\n", refname
, git_reference_symbolic_target(ref
));
702 fprintf(stderr
, "Unexpected reference type\n");
706 git_reference_free(ref
);
709 git_strarray_free(&ref_list
);
715 * The [config API][config] allows you to list and updatee config values
716 * in any of the accessible config file locations (system, global, local).
718 * [config]: http://libgit2.github.com/libgit2/#HEAD/group/config
720 static void config_files(const char *repo_path
, git_repository
* repo
)
723 char config_path
[256];
726 git_config
*snap_cfg
;
728 printf("\n*Config Listing*\n");
731 * Open a config object so we can read global values from it.
733 sprintf(config_path
, "%s/config", repo_path
);
734 check_error(git_config_open_ondisk(&cfg
, config_path
), "opening config");
736 if (git_config_get_int32(&autocorrect
, cfg
, "help.autocorrect") == 0)
737 printf("Autocorrect: %d\n", autocorrect
);
739 check_error(git_repository_config_snapshot(&snap_cfg
, repo
), "config snapshot");
740 git_config_get_string(&email
, snap_cfg
, "user.email");
741 printf("Email: %s\n", email
);
744 * Remember to free the configurations after usage.
746 git_config_free(cfg
);
747 git_config_free(snap_cfg
);