Commit dcd759b8 by Patrick Steinhardt Committed by GitHub

Merge pull request #3897 from pks-t/pks/squelch-example-warnings

Squelch example warnings, enable CI
parents 610cff13 ec3f5a9c
...@@ -75,15 +75,14 @@ int print_matched_cb(const char *path, const char *matched_pathspec, void *paylo ...@@ -75,15 +75,14 @@ int print_matched_cb(const char *path, const char *matched_pathspec, void *paylo
{ {
struct print_payload p = *(struct print_payload*)(payload); struct print_payload p = *(struct print_payload*)(payload);
int ret; int ret;
git_status_t status; unsigned status;
(void)matched_pathspec; (void)matched_pathspec;
if (git_status_file((unsigned int*)(&status), p.repo, path)) { if (git_status_file(&status, p.repo, path)) {
return -1; //abort return -1;
} }
if (status & GIT_STATUS_WT_MODIFIED || if (status & GIT_STATUS_WT_MODIFIED || status & GIT_STATUS_WT_NEW) {
status & GIT_STATUS_WT_NEW) {
printf("add '%s'\n", path); printf("add '%s'\n", path);
ret = 0; ret = 0;
} else { } else {
......
...@@ -146,6 +146,25 @@ int match_uint16_arg( ...@@ -146,6 +146,25 @@ int match_uint16_arg(
return 1; return 1;
} }
int match_uint32_arg(
uint32_t *out, struct args_info *args, const char *opt)
{
const char *found = match_numeric_arg(args, opt);
uint16_t val;
char *endptr = NULL;
if (!found)
return 0;
val = (uint32_t)strtoul(found, &endptr, 0);
if (!endptr || *endptr != '\0')
fatal("expected number after argument", opt);
if (out)
*out = val;
return 1;
}
static int match_int_internal( static int match_int_internal(
int *out, const char *str, int allow_negative, const char *opt) int *out, const char *str, int allow_negative, const char *opt)
{ {
......
...@@ -73,6 +73,15 @@ extern int match_uint16_arg( ...@@ -73,6 +73,15 @@ extern int match_uint16_arg(
uint16_t *out, struct args_info *args, const char *opt); uint16_t *out, struct args_info *args, const char *opt);
/** /**
* Check current `args` entry against `opt` string parsing as uint32. If
* `opt` matches exactly, take the next arg as a uint16_t value; if `opt`
* is a prefix (equal sign optional), take the remainder of the arg as a
* uint32_t value; otherwise return 0.
*/
extern int match_uint32_arg(
uint32_t *out, struct args_info *args, const char *opt);
/**
* Check current `args` entry against `opt` string parsing as int. If * Check current `args` entry against `opt` string parsing as int. If
* `opt` matches exactly, take the next arg as an int value; if it matches * `opt` matches exactly, take the next arg as an int value; if it matches
* as a prefix (equal sign optional), take the remainder of the arg as a * as a prefix (equal sign optional), take the remainder of the arg as a
......
...@@ -293,11 +293,11 @@ static void parse_opts(struct opts *o, int argc, char *argv[]) ...@@ -293,11 +293,11 @@ static void parse_opts(struct opts *o, int argc, char *argv[])
else if (is_prefixed(a, "-B") || is_prefixed(a, "--break-rewrites")) else if (is_prefixed(a, "-B") || is_prefixed(a, "--break-rewrites"))
/* TODO: parse thresholds */ /* TODO: parse thresholds */
o->findopts.flags |= GIT_DIFF_FIND_REWRITES; o->findopts.flags |= GIT_DIFF_FIND_REWRITES;
else if (!match_uint16_arg( else if (!match_uint32_arg(
&o->diffopts.context_lines, &args, "-U") && &o->diffopts.context_lines, &args, "-U") &&
!match_uint16_arg( !match_uint32_arg(
&o->diffopts.context_lines, &args, "--unified") && &o->diffopts.context_lines, &args, "--unified") &&
!match_uint16_arg( !match_uint32_arg(
&o->diffopts.interhunk_lines, &args, "--inter-hunk-context") && &o->diffopts.interhunk_lines, &args, "--inter-hunk-context") &&
!match_uint16_arg( !match_uint16_arg(
&o->diffopts.id_abbrev, &args, "--abbrev") && &o->diffopts.id_abbrev, &args, "--abbrev") &&
......
...@@ -12,39 +12,58 @@ ...@@ -12,39 +12,58 @@
* <http://creativecommons.org/publicdomain/zero/1.0/>. * <http://creativecommons.org/publicdomain/zero/1.0/>.
*/ */
// [**libgit2**][lg] is a portable, pure C implementation of the Git core /**
// methods provided as a re-entrant linkable library with a solid API, * [**libgit2**][lg] is a portable, pure C implementation of the Git core
// allowing you to write native speed custom Git applications in any * methods provided as a re-entrant linkable library with a solid API,
// language which supports C bindings. * allowing you to write native speed custom Git applications in any
// * language which supports C bindings.
// This file is an example of using that API in a real, compilable C file. *
// As the API is updated, this file will be updated to demonstrate the new * This file is an example of using that API in a real, compilable C file.
// functionality. * As the API is updated, this file will be updated to demonstrate the new
// * functionality.
// If you're trying to write something in C using [libgit2][lg], you should *
// also check out the generated [API documentation][ap]. We try to link to * If you're trying to write something in C using [libgit2][lg], you should
// the relevant sections of the API docs in each section in this file. * also check out the generated [API documentation][ap]. We try to link to
// * the relevant sections of the API docs in each section in this file.
// **libgit2** (for the most part) only implements the core plumbing *
// functions, not really the higher level porcelain stuff. For a primer on * **libgit2** (for the most part) only implements the core plumbing
// Git Internals that you will need to know to work with Git at this level, * functions, not really the higher level porcelain stuff. For a primer on
// check out [Chapter 10][pg] of the Pro Git book. * Git Internals that you will need to know to work with Git at this level,
// * check out [Chapter 10][pg] of the Pro Git book.
// [lg]: http://libgit2.github.com *
// [ap]: http://libgit2.github.com/libgit2 * [lg]: http://libgit2.github.com
// [pg]: https://git-scm.com/book/en/v2/Git-Internals-Plumbing-and-Porcelain * [ap]: http://libgit2.github.com/libgit2
* [pg]: https://git-scm.com/book/en/v2/Git-Internals-Plumbing-and-Porcelain
// ### Includes */
// Including the `git2.h` header will include all the other libgit2 headers /**
// that you need. It should be the only thing you need to include in order * ### Includes
// to compile properly and get all the libgit2 API. *
* Including the `git2.h` header will include all the other libgit2 headers
* that you need. It should be the only thing you need to include in order
* to compile properly and get all the libgit2 API.
*/
#include <git2.h> #include <git2.h>
#include <stdio.h> #include <stdio.h>
#include <string.h>
// Almost all libgit2 functions return 0 on success or negative on error.
// This is not production quality error checking, but should be sufficient static void oid_parsing(git_oid *out);
// as an example. static void object_database(git_repository *repo, git_oid *oid);
static void commit_writing(git_repository *repo);
static void commit_parsing(git_repository *repo);
static void tag_parsing(git_repository *repo);
static void tree_parsing(git_repository *repo);
static void blob_parsing(git_repository *repo);
static void revwalking(git_repository *repo);
static void index_walking(git_repository *repo);
static void reference_listing(git_repository *repo);
static void config_files(const char *repo_path);
/**
* Almost all libgit2 functions return 0 on success or negative on error.
* This is not production quality error checking, but should be sufficient
* as an example.
*/
static void check_error(int error_code, const char *action) static void check_error(int error_code, const char *action)
{ {
const git_error *error = giterr_last(); const git_error *error = giterr_last();
...@@ -52,479 +71,645 @@ static void check_error(int error_code, const char *action) ...@@ -52,479 +71,645 @@ static void check_error(int error_code, const char *action)
return; return;
printf("Error %d %s - %s\n", error_code, action, printf("Error %d %s - %s\n", error_code, action,
(error && error->message) ? error->message : "???"); (error && error->message) ? error->message : "???");
exit(1); exit(1);
} }
int main (int argc, char** argv) int main (int argc, char** argv)
{ {
// Initialize the library, this will set up any global state which libgit2 needs int error;
// including threading and crypto git_oid oid;
git_libgit2_init(); char *repo_path;
git_repository *repo;
// ### Opening the Repository
/**
// There are a couple of methods for opening a repository, this being the * Initialize the library, this will set up any global state which libgit2 needs
// simplest. There are also [methods][me] for specifying the index file * including threading and crypto
// and work tree locations, here we assume they are in the normal places. */
// git_libgit2_init();
// (Try running this program against tests/resources/testrepo.git.)
// /**
// [me]: http://libgit2.github.com/libgit2/#HEAD/group/repository * ### Opening the Repository
int error; *
const char *repo_path = (argc > 1) ? argv[1] : "/opt/libgit2-test/.git"; * There are a couple of methods for opening a repository, this being the
git_repository *repo; * simplest. There are also [methods][me] for specifying the index file
* and work tree locations, here we assume they are in the normal places.
error = git_repository_open(&repo, repo_path); *
check_error(error, "opening repository"); * (Try running this program against tests/resources/testrepo.git.)
*
// ### SHA-1 Value Conversions * [me]: http://libgit2.github.com/libgit2/#HEAD/group/repository
*/
// For our first example, we will convert a 40 character hex value to the repo_path = (argc > 1) ? argv[1] : "/opt/libgit2-test/.git";
// 20 byte raw SHA1 value.
printf("*Hex to Raw*\n"); error = git_repository_open(&repo, repo_path);
char hex[] = "4a202b346bb0fb0db7eff3cffeb3c70babbd2045"; check_error(error, "opening repository");
// The `git_oid` is the structure that keeps the SHA value. We will use oid_parsing(&oid);
// this throughout the example for storing the value of the current SHA object_database(repo, &oid);
// key we're working with. commit_writing(repo);
git_oid oid; commit_parsing(repo);
git_oid_fromstr(&oid, hex); tag_parsing(repo);
tree_parsing(repo);
// Once we've converted the string into the oid value, we can get the raw blob_parsing(repo);
// value of the SHA by accessing `oid.id` revwalking(repo);
index_walking(repo);
// Next we will convert the 20 byte raw SHA1 value to a human readable 40 reference_listing(repo);
// char hex value. config_files(repo_path);
printf("\n*Raw to Hex*\n");
char out[GIT_OID_HEXSZ+1]; /**
out[GIT_OID_HEXSZ] = '\0'; * Finally, when you're done with the repository, you can free it as well.
*/
// If you have a oid, you can easily get the hex value of the SHA as well. git_repository_free(repo);
git_oid_fmt(out, &oid);
printf("SHA hex string: %s\n", out); return 0;
}
// ### Working with the Object Database
/**
// **libgit2** provides [direct access][odb] to the object database. The * ### SHA-1 Value Conversions
// object database is where the actual objects are stored in Git. For */
// working with raw objects, we'll need to get this structure from the static void oid_parsing(git_oid *oid)
// repository. {
// char out[GIT_OID_HEXSZ+1];
// [odb]: http://libgit2.github.com/libgit2/#HEAD/group/odb char hex[] = "4a202b346bb0fb0db7eff3cffeb3c70babbd2045";
git_odb *odb;
git_repository_odb(&odb, repo); printf("*Hex to Raw*\n");
// #### Raw Object Reading /**
* For our first example, we will convert a 40 character hex value to the
printf("\n*Raw Object Read*\n"); * 20 byte raw SHA1 value.
git_odb_object *obj; *
git_otype otype; * The `git_oid` is the structure that keeps the SHA value. We will use
const unsigned char *data; * this throughout the example for storing the value of the current SHA
const char *str_type; * key we're working with.
*/
// We can read raw objects directly from the object database if we have git_oid_fromstr(oid, hex);
// the oid (SHA) of the object. This allows us to access objects without
// knowing their type and inspect the raw bytes unparsed. // Once we've converted the string into the oid value, we can get the raw
error = git_odb_read(&obj, odb, &oid); // value of the SHA by accessing `oid.id`
check_error(error, "finding object in repository");
// Next we will convert the 20 byte raw SHA1 value to a human readable 40
// A raw object only has three properties - the type (commit, blob, tree // char hex value.
// or tag), the size of the raw data and the raw, unparsed data itself. printf("\n*Raw to Hex*\n");
// For a commit or tag, that raw data is human readable plain ASCII out[GIT_OID_HEXSZ] = '\0';
// text. For a blob it is just file contents, so it could be text or
// binary data. For a tree it is a special binary format, so it's unlikely /**
// to be hugely helpful as a raw object. * If you have a oid, you can easily get the hex value of the SHA as well.
data = (const unsigned char *)git_odb_object_data(obj); */
otype = git_odb_object_type(obj); git_oid_fmt(out, oid);
// We provide methods to convert from the object type which is an enum, to /**
// a string representation of that value (and vice-versa). * If you have a oid, you can easily get the hex value of the SHA as well.
str_type = git_object_type2string(otype); */
printf("object length and type: %d, %s\n", git_oid_fmt(out, oid);
(int)git_odb_object_size(obj), printf("SHA hex string: %s\n", out);
str_type); }
// For proper memory management, close the object when you are done with /**
// it or it will leak memory. * ### Working with the Object Database
git_odb_object_free(obj); *
* **libgit2** provides [direct access][odb] to the object database. The
// #### Raw Object Writing * object database is where the actual objects are stored in Git. For
* working with raw objects, we'll need to get this structure from the
printf("\n*Raw Object Write*\n"); * repository.
*
// You can also write raw object data to Git. This is pretty cool because * [odb]: http://libgit2.github.com/libgit2/#HEAD/group/odb
// it gives you direct access to the key/value properties of Git. Here */
// we'll write a new blob object that just contains a simple string. static void object_database(git_repository *repo, git_oid *oid)
// Notice that we have to specify the object type as the `git_otype` enum. {
git_odb_write(&oid, odb, "test data", sizeof("test data") - 1, GIT_OBJ_BLOB); char oid_hex[GIT_OID_HEXSZ+1] = { 0 };
const unsigned char *data;
// Now that we've written the object, we can check out what SHA1 was const char *str_type;
// generated when the object was written to our database. int error;
git_oid_fmt(out, &oid); git_odb_object *obj;
printf("Written Object: %s\n", out); git_odb *odb;
git_otype otype;
// ### Object Parsing
git_repository_odb(&odb, repo);
// libgit2 has methods to parse every object type in Git so you don't have
// to work directly with the raw data. This is much faster and simpler /**
// than trying to deal with the raw data yourself. * #### Raw Object Reading
*/
// #### Commit Parsing
printf("\n*Raw Object Read*\n");
// [Parsing commit objects][pco] is simple and gives you access to all the
// data in the commit - the author (name, email, datetime), committer /**
// (same), tree, message, encoding and parent(s). * We can read raw objects directly from the object database if we have
// * the oid (SHA) of the object. This allows us to access objects without
// [pco]: http://libgit2.github.com/libgit2/#HEAD/group/commit * knowing their type and inspect the raw bytes unparsed.
*/
printf("\n*Commit Parsing*\n"); error = git_odb_read(&obj, odb, oid);
check_error(error, "finding object in repository");
git_commit *commit;
git_oid_fromstr(&oid, "8496071c1b46c854b31185ea97743be6a8774479"); /**
* A raw object only has three properties - the type (commit, blob, tree
error = git_commit_lookup(&commit, repo, &oid); * or tag), the size of the raw data and the raw, unparsed data itself.
check_error(error, "looking up commit"); * For a commit or tag, that raw data is human readable plain ASCII
* text. For a blob it is just file contents, so it could be text or
const git_signature *author, *cmtter; * binary data. For a tree it is a special binary format, so it's unlikely
const char *message; * to be hugely helpful as a raw object.
time_t ctime; */
unsigned int parents, p; data = (const unsigned char *)git_odb_object_data(obj);
otype = git_odb_object_type(obj);
// Each of the properties of the commit object are accessible via methods,
// including commonly needed variations, such as `git_commit_time` which /**
// returns the author time and `git_commit_message` which gives you the * We provide methods to convert from the object type which is an enum, to
// commit message (as a NUL-terminated string). * a string representation of that value (and vice-versa).
message = git_commit_message(commit); */
author = git_commit_author(commit); str_type = git_object_type2string(otype);
cmtter = git_commit_committer(commit); printf("object length and type: %d, %s\nobject data: %s\n",
ctime = git_commit_time(commit); (int)git_odb_object_size(obj),
str_type, data);
// The author and committer methods return [git_signature] structures,
// which give you name, email and `when`, which is a `git_time` structure, /**
// giving you a timestamp and timezone offset. * For proper memory management, close the object when you are done with
printf("Author: %s (%s)\n", author->name, author->email); * it or it will leak memory.
*/
// Commits can have zero or more parents. The first (root) commit will git_odb_object_free(obj);
// have no parents, most commits will have one (i.e. the commit it was
// based on) and merge commits will have two or more. Commits can /**
// technically have any number, though it's rare to have more than two. * #### Raw Object Writing
parents = git_commit_parentcount(commit); */
for (p = 0;p < parents;p++) {
git_commit *parent; printf("\n*Raw Object Write*\n");
git_commit_parent(&parent, commit, p);
git_oid_fmt(out, git_commit_id(parent)); /**
printf("Parent: %s\n", out); * You can also write raw object data to Git. This is pretty cool because
git_commit_free(parent); * it gives you direct access to the key/value properties of Git. Here
} * we'll write a new blob object that just contains a simple string.
* Notice that we have to specify the object type as the `git_otype` enum.
// Don't forget to close the object to prevent memory leaks. You will have */
// to do this for all the objects you open and parse. git_odb_write(oid, odb, "test data", sizeof("test data") - 1, GIT_OBJ_BLOB);
git_commit_free(commit);
/**
// #### Writing Commits * Now that we've written the object, we can check out what SHA1 was
* generated when the object was written to our database.
// libgit2 provides a couple of methods to create commit objects easily as */
// well. There are four different create signatures, we'll just show one git_oid_fmt(oid_hex, oid);
// of them here. You can read about the other ones in the [commit API printf("Written Object: %s\n", oid_hex);
// docs][cd]. }
//
// [cd]: http://libgit2.github.com/libgit2/#HEAD/group/commit /**
* #### Writing Commits
printf("\n*Commit Writing*\n"); *
git_oid tree_id, parent_id, commit_id; * libgit2 provides a couple of methods to create commit objects easily as
git_tree *tree; * well. There are four different create signatures, we'll just show one
git_commit *parent; * of them here. You can read about the other ones in the [commit API
* docs][cd].
// Creating signatures for an authoring identity and time is simple. You *
// will need to do this to specify who created a commit and when. Default * [cd]: http://libgit2.github.com/libgit2/#HEAD/group/commit
// values for the name and email should be found in the `user.name` and */
// `user.email` configuration options. See the `config` section of this static void commit_writing(git_repository *repo)
// example file to see how to access config values. {
git_signature_new((git_signature **)&author, git_oid tree_id, parent_id, commit_id;
"Scott Chacon", "schacon@gmail.com", 123456789, 60); git_tree *tree;
git_signature_new((git_signature **)&cmtter, git_commit *parent;
"Scott A Chacon", "scott@github.com", 987654321, 90); const git_signature *author, *cmtter;
char oid_hex[GIT_OID_HEXSZ+1] = { 0 };
// Commit objects need a tree to point to and optionally one or more
// parents. Here we're creating oid objects to create the commit with, printf("\n*Commit Writing*\n");
// but you can also use
git_oid_fromstr(&tree_id, "f60079018b664e4e79329a7ef9559c8d9e0378d1"); /**
git_tree_lookup(&tree, repo, &tree_id); * Creating signatures for an authoring identity and time is simple. You
git_oid_fromstr(&parent_id, "5b5b025afb0b4c913b4c338a42934a3863bf3644"); * will need to do this to specify who created a commit and when. Default
git_commit_lookup(&parent, repo, &parent_id); * values for the name and email should be found in the `user.name` and
* `user.email` configuration options. See the `config` section of this
// Here we actually create the commit object with a single call with all * example file to see how to access config values.
// the values we need to create the commit. The SHA key is written to the */
// `commit_id` variable here. git_signature_new((git_signature **)&author,
git_commit_create_v( "Scott Chacon", "schacon@gmail.com", 123456789, 60);
&commit_id, /* out id */ git_signature_new((git_signature **)&cmtter,
repo, "Scott A Chacon", "scott@github.com", 987654321, 90);
NULL, /* do not update the HEAD */
author, /**
cmtter, * Commit objects need a tree to point to and optionally one or more
NULL, /* use default message encoding */ * parents. Here we're creating oid objects to create the commit with,
"example commit", * but you can also use
tree, */
1, parent); git_oid_fromstr(&tree_id, "f60079018b664e4e79329a7ef9559c8d9e0378d1");
git_tree_lookup(&tree, repo, &tree_id);
// Now we can take a look at the commit SHA we've generated. git_oid_fromstr(&parent_id, "5b5b025afb0b4c913b4c338a42934a3863bf3644");
git_oid_fmt(out, &commit_id); git_commit_lookup(&parent, repo, &parent_id);
printf("New Commit: %s\n", out);
/**
// #### Tag Parsing * Here we actually create the commit object with a single call with all
* the values we need to create the commit. The SHA key is written to the
// You can parse and create tags with the [tag management API][tm], which * `commit_id` variable here.
// functions very similarly to the commit lookup, parsing and creation */
// methods, since the objects themselves are very similar. git_commit_create_v(
// &commit_id, /* out id */
// [tm]: http://libgit2.github.com/libgit2/#HEAD/group/tag repo,
printf("\n*Tag Parsing*\n"); NULL, /* do not update the HEAD */
git_tag *tag; author,
const char *tmessage, *tname; cmtter,
git_otype ttype; NULL, /* use default message encoding */
"example commit",
// We create an oid for the tag object if we know the SHA and look it up tree,
// the same way that we would a commit (or any other object). 1, parent);
git_oid_fromstr(&oid, "b25fa35b38051e4ae45d4222e795f9df2e43f1d1");
/**
error = git_tag_lookup(&tag, repo, &oid); * Now we can take a look at the commit SHA we've generated.
check_error(error, "looking up tag"); */
git_oid_fmt(oid_hex, &commit_id);
// Now that we have the tag object, we can extract the information it printf("New Commit: %s\n", oid_hex);
// generally contains: the target (usually a commit object), the type of }
// the target object (usually 'commit'), the name ('v1.0'), the tagger (a
// git_signature - name, email, timestamp), and the tag message. /**
git_tag_target((git_object **)&commit, tag); * ### Object Parsing
tname = git_tag_name(tag); // "test" *
ttype = git_tag_target_type(tag); // GIT_OBJ_COMMIT (otype enum) * libgit2 has methods to parse every object type in Git so you don't have
tmessage = git_tag_message(tag); // "tag message\n" * to work directly with the raw data. This is much faster and simpler
printf("Tag Message: %s\n", tmessage); * than trying to deal with the raw data yourself.
*/
git_commit_free(commit);
/**
// #### Tree Parsing * #### Commit Parsing
*
// [Tree parsing][tp] is a bit different than the other objects, in that * [Parsing commit objects][pco] is simple and gives you access to all the
// we have a subtype which is the tree entry. This is not an actual * data in the commit - the author (name, email, datetime), committer
// object type in Git, but a useful structure for parsing and traversing * (same), tree, message, encoding and parent(s).
// tree entries. *
// * [pco]: http://libgit2.github.com/libgit2/#HEAD/group/commit
// [tp]: http://libgit2.github.com/libgit2/#HEAD/group/tree */
printf("\n*Tree Parsing*\n"); static void commit_parsing(git_repository *repo)
{
const git_tree_entry *entry; const git_signature *author, *cmtter;
git_object *objt; git_commit *commit, *parent;
git_oid oid;
// Create the oid and lookup the tree object just like the other objects. char oid_hex[GIT_OID_HEXSZ+1];
git_oid_fromstr(&oid, "2a741c18ac5ff082a7caaec6e74db3075a1906b5"); const char *message;
git_tree_lookup(&tree, repo, &oid); unsigned int parents, p;
int error;
// Getting the count of entries in the tree so you can iterate over them time_t time;
// if you want to.
size_t cnt = git_tree_entrycount(tree); // 3 printf("\n*Commit Parsing*\n");
printf("tree entries: %d\n", (int)cnt);
git_oid_fromstr(&oid, "8496071c1b46c854b31185ea97743be6a8774479");
entry = git_tree_entry_byindex(tree, 0);
printf("Entry name: %s\n", git_tree_entry_name(entry)); // "hello.c" error = git_commit_lookup(&commit, repo, &oid);
check_error(error, "looking up commit");
// You can also access tree entries by name if you know the name of the
// entry you're looking for. /**
entry = git_tree_entry_byname(tree, "README"); * Each of the properties of the commit object are accessible via methods,
git_tree_entry_name(entry); // "hello.c" * including commonly needed variations, such as `git_commit_time` which
* returns the author time and `git_commit_message` which gives you the
// Once you have the entry object, you can access the content or subtree * commit message (as a NUL-terminated string).
// (or commit, in the case of submodules) that it points to. You can also */
// get the mode if you want. message = git_commit_message(commit);
git_tree_entry_to_object(&objt, repo, entry); // blob author = git_commit_author(commit);
cmtter = git_commit_committer(commit);
// Remember to close the looked-up object once you are done using it time = git_commit_time(commit);
git_object_free(objt);
/**
// #### Blob Parsing * The author and committer methods return [git_signature] structures,
* which give you name, email and `when`, which is a `git_time` structure,
// The last object type is the simplest and requires the least parsing * giving you a timestamp and timezone offset.
// help. Blobs are just file contents and can contain anything, there is */
// no structure to it. The main advantage to using the [simple blob printf("Author: %s (%s)\nCommitter: %s (%s)\nDate: %s\nMessage: %s\n",
// api][ba] is that when you're creating blobs you don't have to calculate author->name, author->email,
// the size of the content. There is also a helper for reading a file cmtter->name, cmtter->email,
// from disk and writing it to the db and getting the oid back so you ctime(&time), message);
// don't have to do all those steps yourself.
// /**
// [ba]: http://libgit2.github.com/libgit2/#HEAD/group/blob * Commits can have zero or more parents. The first (root) commit will
* have no parents, most commits will have one (i.e. the commit it was
printf("\n*Blob Parsing*\n"); * based on) and merge commits will have two or more. Commits can
git_blob *blob; * technically have any number, though it's rare to have more than two.
*/
git_oid_fromstr(&oid, "1385f264afb75a56a5bec74243be9b367ba4ca08"); parents = git_commit_parentcount(commit);
git_blob_lookup(&blob, repo, &oid); for (p = 0;p < parents;p++) {
memset(oid_hex, 0, sizeof(oid_hex));
// You can access a buffer with the raw contents of the blob directly.
// Note that this buffer may not be contain ASCII data for certain blobs git_commit_parent(&parent, commit, p);
// (e.g. binary files): do not consider the buffer a NULL-terminated git_oid_fmt(oid_hex, git_commit_id(parent));
// string, and use the `git_blob_rawsize` attribute to find out its exact printf("Parent: %s\n", oid_hex);
// size in bytes git_commit_free(parent);
printf("Blob Size: %ld\n", (long)git_blob_rawsize(blob)); // 8 }
git_blob_rawcontent(blob); // "content"
git_commit_free(commit);
// ### Revwalking }
// The libgit2 [revision walking api][rw] provides methods to traverse the /**
// directed graph created by the parent pointers of the commit objects. * #### Tag Parsing
// Since all commits point back to the commit that came directly before *
// them, you can walk this parentage as a graph and find all the commits * You can parse and create tags with the [tag management API][tm], which
// that were ancestors of (reachable from) a given starting point. This * functions very similarly to the commit lookup, parsing and creation
// can allow you to create `git log` type functionality. * methods, since the objects themselves are very similar.
// *
// [rw]: http://libgit2.github.com/libgit2/#HEAD/group/revwalk * [tm]: http://libgit2.github.com/libgit2/#HEAD/group/tag
*/
printf("\n*Revwalking*\n"); static void tag_parsing(git_repository *repo)
git_revwalk *walk; {
git_commit *wcommit; git_commit *commit;
git_otype type;
git_oid_fromstr(&oid, "5b5b025afb0b4c913b4c338a42934a3863bf3644"); git_tag *tag;
git_oid oid;
// To use the revwalker, create a new walker, tell it how you want to sort const char *name, *message;
// the output and then push one or more starting points onto the walker. int error;
// If you want to emulate the output of `git log` you would push the SHA
// of the commit that HEAD points to into the walker and then start printf("\n*Tag Parsing*\n");
// traversing them. You can also 'hide' commits that you want to stop at
// or not see any of their ancestors. So if you want to emulate `git log /**
// branch1..branch2`, you would push the oid of `branch2` and hide the oid * We create an oid for the tag object if we know the SHA and look it up
// of `branch1`. * the same way that we would a commit (or any other object).
git_revwalk_new(&walk, repo); */
git_revwalk_sorting(walk, GIT_SORT_TOPOLOGICAL | GIT_SORT_REVERSE); git_oid_fromstr(&oid, "b25fa35b38051e4ae45d4222e795f9df2e43f1d1");
git_revwalk_push(walk, &oid);
error = git_tag_lookup(&tag, repo, &oid);
const git_signature *cauth; check_error(error, "looking up tag");
const char *cmsg;
/**
// Now that we have the starting point pushed onto the walker, we start * Now that we have the tag object, we can extract the information it
// asking for ancestors. It will return them in the sorting order we asked * generally contains: the target (usually a commit object), the type of
// for as commit oids. We can then lookup and parse the committed pointed * the target object (usually 'commit'), the name ('v1.0'), the tagger (a
// at by the returned OID; note that this operation is specially fast * git_signature - name, email, timestamp), and the tag message.
// since the raw contents of the commit object will be cached in memory */
while ((git_revwalk_next(&oid, walk)) == 0) { git_tag_target((git_object **)&commit, tag);
error = git_commit_lookup(&wcommit, repo, &oid); name = git_tag_name(tag); /* "test" */
check_error(error, "looking up commit during revwalk"); type = git_tag_target_type(tag); /* GIT_OBJ_COMMIT (otype enum) */
message = git_tag_message(tag); /* "tag message\n" */
cmsg = git_commit_message(wcommit); printf("Tag Name: %s\nTag Type: %s\nTag Message: %s\n",
cauth = git_commit_author(wcommit); name, git_object_type2string(type), message);
printf("%s (%s)\n", cmsg, cauth->email);
git_commit_free(commit);
git_commit_free(wcommit); }
}
/**
// Like the other objects, be sure to free the revwalker when you're done * #### Tree Parsing
// to prevent memory leaks. Also, make sure that the repository being *
// walked it not deallocated while the walk is in progress, or it will * [Tree parsing][tp] is a bit different than the other objects, in that
// result in undefined behavior * we have a subtype which is the tree entry. This is not an actual
git_revwalk_free(walk); * object type in Git, but a useful structure for parsing and traversing
* tree entries.
// ### Index File Manipulation *
* [tp]: http://libgit2.github.com/libgit2/#HEAD/group/tree
// The [index file API][gi] allows you to read, traverse, update and write */
// the Git index file (sometimes thought of as the staging area). static void tree_parsing(git_repository *repo)
// {
// [gi]: http://libgit2.github.com/libgit2/#HEAD/group/index const git_tree_entry *entry;
size_t cnt;
printf("\n*Index Walking*\n"); git_object *obj;
git_tree *tree;
git_index *index; git_oid oid;
unsigned int i, ecount;
printf("\n*Tree Parsing*\n");
// You can either open the index from the standard location in an open
// repository, as we're doing here, or you can open and manipulate any /**
// index file with `git_index_open_bare()`. The index for the repository * Create the oid and lookup the tree object just like the other objects.
// will be located and loaded from disk. */
git_repository_index(&index, repo); git_oid_fromstr(&oid, "f60079018b664e4e79329a7ef9559c8d9e0378d1");
git_tree_lookup(&tree, repo, &oid);
// For each entry in the index, you can get a bunch of information
// including the SHA (oid), path and mode which map to the tree objects /**
// that are written out. It also has filesystem properties to help * Getting the count of entries in the tree so you can iterate over them
// determine what to inspect for changes (ctime, mtime, dev, ino, uid, * if you want to.
// gid, file_size and flags) All these properties are exported publicly in */
// the `git_index_entry` struct cnt = git_tree_entrycount(tree); /* 2 */
ecount = git_index_entrycount(index); printf("tree entries: %d\n", (int) cnt);
for (i = 0; i < ecount; ++i) {
const git_index_entry *e = git_index_get_byindex(index, i); entry = git_tree_entry_byindex(tree, 0);
printf("Entry name: %s\n", git_tree_entry_name(entry)); /* "README" */
printf("path: %s\n", e->path);
printf("mtime: %d\n", (int)e->mtime.seconds); /**
printf("fs: %d\n", (int)e->file_size); * You can also access tree entries by name if you know the name of the
} * entry you're looking for.
*/
git_index_free(index); entry = git_tree_entry_byname(tree, "README");
git_tree_entry_name(entry); /* "README" */
// ### References
/**
// The [reference API][ref] allows you to list, resolve, create and update * Once you have the entry object, you can access the content or subtree
// references such as branches, tags and remote references (everything in * (or commit, in the case of submodules) that it points to. You can also
// the .git/refs directory). * get the mode if you want.
// */
// [ref]: http://libgit2.github.com/libgit2/#HEAD/group/reference git_tree_entry_to_object(&obj, repo, entry); /* blob */
printf("\n*Reference Listing*\n"); /**
* Remember to close the looked-up object once you are done using it
// Here we will implement something like `git for-each-ref` simply listing */
// out all available references and the object SHA they resolve to. git_object_free(obj);
git_strarray ref_list; }
git_reference_list(&ref_list, repo);
/**
const char *refname; * #### Blob Parsing
git_reference *ref; *
* The last object type is the simplest and requires the least parsing
// Now that we have the list of reference names, we can lookup each ref * help. Blobs are just file contents and can contain anything, there is
// one at a time and resolve them to the SHA, then print both values out. * no structure to it. The main advantage to using the [simple blob
for (i = 0; i < ref_list.count; ++i) { * api][ba] is that when you're creating blobs you don't have to calculate
refname = ref_list.strings[i]; * the size of the content. There is also a helper for reading a file
git_reference_lookup(&ref, repo, refname); * from disk and writing it to the db and getting the oid back so you
* don't have to do all those steps yourself.
switch (git_reference_type(ref)) { *
case GIT_REF_OID: * [ba]: http://libgit2.github.com/libgit2/#HEAD/group/blob
git_oid_fmt(out, git_reference_target(ref)); */
printf("%s [%s]\n", refname, out); static void blob_parsing(git_repository *repo)
break; {
git_blob *blob;
case GIT_REF_SYMBOLIC: git_oid oid;
printf("%s => %s\n", refname, git_reference_symbolic_target(ref));
break; printf("\n*Blob Parsing*\n");
default:
fprintf(stderr, "Unexpected reference type\n"); git_oid_fromstr(&oid, "1385f264afb75a56a5bec74243be9b367ba4ca08");
exit(1); git_blob_lookup(&blob, repo, &oid);
}
} /**
* You can access a buffer with the raw contents of the blob directly.
git_strarray_free(&ref_list); * Note that this buffer may not be contain ASCII data for certain blobs
* (e.g. binary files): do not consider the buffer a NULL-terminated
// ### Config Files * string, and use the `git_blob_rawsize` attribute to find out its exact
* size in bytes
// The [config API][config] allows you to list and updatee config values * */
// in any of the accessible config file locations (system, global, local). printf("Blob Size: %ld\n", (long)git_blob_rawsize(blob)); /* 8 */
// git_blob_rawcontent(blob); /* "content" */
// [config]: http://libgit2.github.com/libgit2/#HEAD/group/config }
printf("\n*Config Listing*\n"); /**
* ### Revwalking
*
* The libgit2 [revision walking api][rw] provides methods to traverse the
* directed graph created by the parent pointers of the commit objects.
* Since all commits point back to the commit that came directly before
* them, you can walk this parentage as a graph and find all the commits
* that were ancestors of (reachable from) a given starting point. This
* can allow you to create `git log` type functionality.
*
* [rw]: http://libgit2.github.com/libgit2/#HEAD/group/revwalk
*/
static void revwalking(git_repository *repo)
{
const git_signature *cauth;
const char *cmsg;
int error;
git_revwalk *walk;
git_commit *wcommit;
git_oid oid;
printf("\n*Revwalking*\n");
git_oid_fromstr(&oid, "5b5b025afb0b4c913b4c338a42934a3863bf3644");
/**
* To use the revwalker, create a new walker, tell it how you want to sort
* the output and then push one or more starting points onto the walker.
* If you want to emulate the output of `git log` you would push the SHA
* of the commit that HEAD points to into the walker and then start
* traversing them. You can also 'hide' commits that you want to stop at
* or not see any of their ancestors. So if you want to emulate `git log
* branch1..branch2`, you would push the oid of `branch2` and hide the oid
* of `branch1`.
*/
git_revwalk_new(&walk, repo);
git_revwalk_sorting(walk, GIT_SORT_TOPOLOGICAL | GIT_SORT_REVERSE);
git_revwalk_push(walk, &oid);
/**
* Now that we have the starting point pushed onto the walker, we start
* asking for ancestors. It will return them in the sorting order we asked
* for as commit oids. We can then lookup and parse the committed pointed
* at by the returned OID; note that this operation is specially fast
* since the raw contents of the commit object will be cached in memory
*/
while ((git_revwalk_next(&oid, walk)) == 0) {
error = git_commit_lookup(&wcommit, repo, &oid);
check_error(error, "looking up commit during revwalk");
cmsg = git_commit_message(wcommit);
cauth = git_commit_author(wcommit);
printf("%s (%s)\n", cmsg, cauth->email);
git_commit_free(wcommit);
}
/**
* Like the other objects, be sure to free the revwalker when you're done
* to prevent memory leaks. Also, make sure that the repository being
* walked it not deallocated while the walk is in progress, or it will
* result in undefined behavior
*/
git_revwalk_free(walk);
}
const char *email; /**
int32_t j; * ### Index File Manipulation *
* The [index file API][gi] allows you to read, traverse, update and write
* the Git index file (sometimes thought of as the staging area).
*
* [gi]: http://libgit2.github.com/libgit2/#HEAD/group/index
*/
static void index_walking(git_repository *repo)
{
git_index *index;
unsigned int i, ecount;
printf("\n*Index Walking*\n");
/**
* You can either open the index from the standard location in an open
* repository, as we're doing here, or you can open and manipulate any
* index file with `git_index_open_bare()`. The index for the repository
* will be located and loaded from disk.
*/
git_repository_index(&index, repo);
/**
* For each entry in the index, you can get a bunch of information
* including the SHA (oid), path and mode which map to the tree objects
* that are written out. It also has filesystem properties to help
* determine what to inspect for changes (ctime, mtime, dev, ino, uid,
* gid, file_size and flags) All these properties are exported publicly in
* the `git_index_entry` struct
*/
ecount = git_index_entrycount(index);
for (i = 0; i < ecount; ++i) {
const git_index_entry *e = git_index_get_byindex(index, i);
printf("path: %s\n", e->path);
printf("mtime: %d\n", (int)e->mtime.seconds);
printf("fs: %d\n", (int)e->file_size);
}
git_index_free(index);
}
git_config *cfg; /**
* ### References
*
* The [reference API][ref] allows you to list, resolve, create and update
* references such as branches, tags and remote references (everything in
* the .git/refs directory).
*
* [ref]: http://libgit2.github.com/libgit2/#HEAD/group/reference
*/
static void reference_listing(git_repository *repo)
{
git_strarray ref_list;
const char *refname;
git_reference *ref;
unsigned i;
char oid_hex[GIT_OID_HEXSZ+1];
printf("\n*Reference Listing*\n");
/**
* Here we will implement something like `git for-each-ref` simply listing
* out all available references and the object SHA they resolve to.
*
* Now that we have the list of reference names, we can lookup each ref
* one at a time and resolve them to the SHA, then print both values out.
*/
git_reference_list(&ref_list, repo);
for (i = 0; i < ref_list.count; ++i) {
memset(oid_hex, 0, sizeof(oid_hex));
refname = ref_list.strings[i];
git_reference_lookup(&ref, repo, refname);
switch (git_reference_type(ref)) {
case GIT_REF_OID:
git_oid_fmt(oid_hex, git_reference_target(ref));
printf("%s [%s]\n", refname, oid_hex);
break;
case GIT_REF_SYMBOLIC:
printf("%s => %s\n", refname, git_reference_symbolic_target(ref));
break;
default:
fprintf(stderr, "Unexpected reference type\n");
exit(1);
}
}
git_strarray_free(&ref_list);
}
// Open a config object so we can read global values from it. /**
char config_path[256]; * ### Config Files
sprintf(config_path, "%s/config", repo_path); *
check_error(git_config_open_ondisk(&cfg, config_path), "opening config"); * The [config API][config] allows you to list and updatee config values
* in any of the accessible config file locations (system, global, local).
*
* [config]: http://libgit2.github.com/libgit2/#HEAD/group/config
*/
static void config_files(const char *repo_path)
{
const char *email;
char config_path[256];
int32_t j;
git_config *cfg;
git_config_get_int32(&j, cfg, "help.autocorrect"); printf("\n*Config Listing*\n");
printf("Autocorrect: %d\n", j);
git_config_get_string(&email, cfg, "user.email"); /**
printf("Email: %s\n", email); * Open a config object so we can read global values from it.
*/
sprintf(config_path, "%s/config", repo_path);
check_error(git_config_open_ondisk(&cfg, config_path), "opening config");
// Finally, when you're done with the repository, you can free it as well. git_config_get_int32(&j, cfg, "help.autocorrect");
git_repository_free(repo); printf("Autocorrect: %d\n", j);
return 0; git_config_get_string(&email, cfg, "user.email");
printf("Email: %s\n", email);
} }
...@@ -55,6 +55,8 @@ static int update_cb(const char *refname, const git_oid *a, const git_oid *b, vo ...@@ -55,6 +55,8 @@ static int update_cb(const char *refname, const git_oid *a, const git_oid *b, vo
*/ */
static int transfer_progress_cb(const git_transfer_progress *stats, void *payload) static int transfer_progress_cb(const git_transfer_progress *stats, void *payload)
{ {
(void)payload;
if (stats->received_objects == stats->total_objects) { if (stats->received_objects == stats->total_objects) {
printf("Resolving deltas %d/%d\r", printf("Resolving deltas %d/%d\r",
stats->indexed_deltas, stats->total_deltas); stats->indexed_deltas, stats->total_deltas);
...@@ -71,7 +73,6 @@ int fetch(git_repository *repo, int argc, char **argv) ...@@ -71,7 +73,6 @@ int fetch(git_repository *repo, int argc, char **argv)
{ {
git_remote *remote = NULL; git_remote *remote = NULL;
const git_transfer_progress *stats; const git_transfer_progress *stats;
struct dl_data data;
git_fetch_options fetch_opts = GIT_FETCH_OPTIONS_INIT; git_fetch_options fetch_opts = GIT_FETCH_OPTIONS_INIT;
if (argc < 2) { if (argc < 2) {
...@@ -79,14 +80,13 @@ int fetch(git_repository *repo, int argc, char **argv) ...@@ -79,14 +80,13 @@ int fetch(git_repository *repo, int argc, char **argv)
return EXIT_FAILURE; return EXIT_FAILURE;
} }
// Figure out whether it's a named remote or a URL /* Figure out whether it's a named remote or a URL */
printf("Fetching %s for repo %p\n", argv[1], repo); printf("Fetching %s for repo %p\n", argv[1], repo);
if (git_remote_lookup(&remote, repo, argv[1]) < 0) { if (git_remote_lookup(&remote, repo, argv[1]) < 0)
if (git_remote_create_anonymous(&remote, repo, argv[1]) < 0) if (git_remote_create_anonymous(&remote, repo, argv[1]) < 0)
return -1; goto on_error;
}
// Set up the callbacks (only update_tips for now) /* Set up the callbacks (only update_tips for now) */
fetch_opts.callbacks.update_tips = &update_cb; fetch_opts.callbacks.update_tips = &update_cb;
fetch_opts.callbacks.sideband_progress = &progress_cb; fetch_opts.callbacks.sideband_progress = &progress_cb;
fetch_opts.callbacks.transfer_progress = transfer_progress_cb; fetch_opts.callbacks.transfer_progress = transfer_progress_cb;
...@@ -98,7 +98,7 @@ int fetch(git_repository *repo, int argc, char **argv) ...@@ -98,7 +98,7 @@ int fetch(git_repository *repo, int argc, char **argv)
* "fetch". * "fetch".
*/ */
if (git_remote_fetch(remote, NULL, &fetch_opts, "fetch") < 0) if (git_remote_fetch(remote, NULL, &fetch_opts, "fetch") < 0)
return -1; goto on_error;
/** /**
* If there are local objects (we got a thin pack), then tell * If there are local objects (we got a thin pack), then tell
......
...@@ -20,7 +20,7 @@ java -jar poxyproxy.jar -d --port 8080 --credentials foo:bar & ...@@ -20,7 +20,7 @@ java -jar poxyproxy.jar -d --port 8080 --credentials foo:bar &
mkdir _build mkdir _build
cd _build cd _build
# shellcheck disable=SC2086 # shellcheck disable=SC2086
cmake .. -DCMAKE_INSTALL_PREFIX=../_install $OPTIONS || exit $? cmake .. -DBUILD_EXAMPLES=ON -DCMAKE_INSTALL_PREFIX=../_install $OPTIONS || exit $?
make -j2 install || exit $? make -j2 install || exit $?
# If this platform doesn't support test execution, bail out now # If this platform doesn't support test execution, bail out now
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment