From a7ed746093f42fd61f38a0a9ea5ef73c45f11efa Mon Sep 17 00:00:00 2001 From: Russell Belfer Date: Fri, 15 Feb 2013 15:58:13 -0800 Subject: [PATCH 1/3] Add rudimentary error checks and reformat comments There were a number of functions assigning their return value to `error` without much explanation. I added in some rudimentary error checking to help flesh out the example. Also, I reformatted all of the comments down to 80 cols (and in some cases, slightly updated the wording). --- examples/general.c | 349 ++++++++++++++++++++++++++------------------- 1 file changed, 205 insertions(+), 144 deletions(-) diff --git a/examples/general.c b/examples/general.c index a042be011..c7853fa62 100644 --- a/examples/general.c +++ b/examples/general.c @@ -1,19 +1,20 @@ -// [**libgit2**][lg] is a portable, pure C implementation of the Git core methods -// provided as a re-entrant linkable library with a solid API, allowing you -// to write native speed custom Git applications in any language which -// supports C bindings. +// [**libgit2**][lg] is a portable, pure C implementation of the Git core +// methods provided as a re-entrant linkable library with a solid API, +// 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 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 will also want -// to check out the generated [API documentation][ap]. We've -// tried to link to the relevant sections of the API docs in each section in this file. +// 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 +// the relevant sections of the API docs in each section in this file. // -// **libgit2** only implements the core plumbing functions, not really the higher -// level porcelain stuff. For a primer on Git Internals that you will need to know -// to work with Git at this level, check out [Chapter 9][pg] of the Pro Git book. +// **libgit2** (for the most part) only implements the core plumbing +// functions, not really the higher level porcelain stuff. For a primer on +// Git Internals that you will need to know to work with Git at this level, +// check out [Chapter 9][pg] of the Pro Git book. // // [lg]: http://libgit2.github.com // [ap]: http://libgit2.github.com/libgit2 @@ -21,43 +22,63 @@ // ### 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 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 #include +// 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) +{ + if (!error_code) + return; + + const git_error *error = giterr_last(); + + printf("Error %d %s - %s\n", error_code, action, + (error && error->message) ? error->message : "???"); + + exit(1); +} + int main (int argc, char** argv) { // ### Opening the Repository - // There are a couple of methods for opening a repository, this being the simplest. - // There are also [methods][me] for specifying the index file and work tree locations, here - // we are assuming they are in the normal places. + // There are a couple of methods for opening a repository, this being the + // simplest. There are also [methods][me] for specifying the index file + // and work tree locations, here we assume they are in the normal places. // // [me]: http://libgit2.github.com/libgit2/#HEAD/group/repository + int error; + const char *repo_path = (argc > 1) ? argv[1] : "/opt/libgit2-test/.git"; git_repository *repo; - if (argc > 1) { - git_repository_open(&repo, argv[1]); - } else { - git_repository_open(&repo, "/opt/libgit2-test/.git"); - } + + error = git_repository_open(&repo, repo_path); + check_error(error, "opening repository"); // ### SHA-1 Value Conversions - // For our first example, we will convert a 40 character hex value to the 20 byte raw SHA1 value. + // For our first example, we will convert a 40 character hex value to the + // 20 byte raw SHA1 value. printf("*Hex to Raw*\n"); char hex[] = "fd6e612585290339ea8bf39c692a7ff6a29cb7c3"; - // The `git_oid` is the structure that keeps the SHA value. We will use this throughout the example - // for storing the value of the current SHA key we're working with. + // The `git_oid` is the structure that keeps the SHA value. We will use + // this throughout the example for storing the value of the current SHA + // key we're working with. git_oid oid; git_oid_fromstr(&oid, hex); - // Once we've converted the string into the oid value, we can get the raw value of the SHA. + // Once we've converted the string into the oid value, we can get the raw + // value of the SHA. printf("Raw 20 bytes: [%.20s]\n", (&oid)->id); - // Next we will convert the 20 byte raw SHA1 value to a human readable 40 char hex value. + // Next we will convert the 20 byte raw SHA1 value to a human readable 40 + // char hex value. printf("\n*Raw to Hex*\n"); char out[41]; out[40] = '\0'; @@ -67,10 +88,12 @@ int main (int argc, char** argv) printf("SHA hex string: %s\n", out); // ### Working with the Object Database - // **libgit2** provides [direct access][odb] to the object database. - // The object database is where the actual objects are stored in Git. For + + // **libgit2** provides [direct access][odb] to the object database. The + // 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 // repository. + // // [odb]: http://libgit2.github.com/libgit2/#HEAD/group/odb git_odb *odb; git_repository_odb(&odb, repo); @@ -82,55 +105,60 @@ int main (int argc, char** argv) git_otype otype; const unsigned char *data; const char *str_type; - int error; - // 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 knowing thier type and inspect - // the raw bytes unparsed. + // 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 + // knowing thier type and inspect the raw bytes unparsed. error = git_odb_read(&obj, odb, &oid); + check_error(error, "finding object in repository"); - // A raw object only has three properties - the type (commit, blob, tree or tag), the size - // of the raw data and the raw, unparsed data itself. 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 binary data. For a tree it is a special binary format, so it's unlikely to be - // hugely helpful as a raw object. + // A raw object only has three properties - the type (commit, blob, tree + // or tag), the size of the raw data and the raw, unparsed data itself. + // 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 + // binary data. For a tree it is a special binary format, so it's unlikely + // to be hugely helpful as a raw object. data = (const unsigned char *)git_odb_object_data(obj); otype = git_odb_object_type(obj); - // We provide methods to convert from the object type which is an enum, to a string - // representation of that value (and vice-versa). + // We provide methods to convert from the object type which is an enum, to + // a string representation of that value (and vice-versa). str_type = git_object_type2string(otype); printf("object length and type: %d, %s\n", (int)git_odb_object_size(obj), str_type); - // For proper memory management, close the object when you are done with it or it will leak - // memory. + // For proper memory management, close the object when you are done with + // it or it will leak memory. git_odb_object_free(obj); // #### Raw Object Writing printf("\n*Raw Object Write*\n"); - // You can also write raw object data to Git. This is pretty cool because 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. + // You can also write raw object data to Git. This is pretty cool because + // 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. git_odb_write(&oid, odb, "test data", sizeof("test data") - 1, GIT_OBJ_BLOB); - // Now that we've written the object, we can check out what SHA1 was generated when the - // object was written to our database. + // Now that we've written the object, we can check out what SHA1 was + // generated when the object was written to our database. git_oid_fmt(out, &oid); printf("Written Object: %s\n", out); // ### Object Parsing - // 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. + + // 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. // #### Commit Parsing - // [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). + + // [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). + // // [pco]: http://libgit2.github.com/libgit2/#HEAD/group/commit printf("\n*Commit Parsing*\n"); @@ -139,27 +167,31 @@ int main (int argc, char** argv) git_oid_fromstr(&oid, "f0877d0b841d75172ec404fc9370173dfffc20d1"); error = git_commit_lookup(&commit, repo, &oid); + check_error(error, "looking up commit"); const git_signature *author, *cmtter; const char *message; time_t ctime; unsigned int parents, p; - // 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 `_message` - // which gives you the commit message. + // 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 + // commit message (as a NUL-terminated string). message = git_commit_message(commit); author = git_commit_author(commit); cmtter = git_commit_committer(commit); ctime = git_commit_time(commit); - // 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. + // 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. printf("Author: %s (%s)\n", author->name, author->email); - // Commits can have zero or more parents. The first (root) commit will have no parents, most commits - // will have one, which is the commit it was based on, and merge commits will have two or more. - // Commits can technically have any number, though it's pretty rare to have more than two. + // 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 + // 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. parents = git_commit_parentcount(commit); for (p = 0;p < parents;p++) { git_commit *parent; @@ -169,15 +201,17 @@ int main (int argc, char** argv) git_commit_free(parent); } - // 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. + // 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_commit_free(commit); // #### Writing Commits + + // libgit2 provides a couple of methods to create commit objects easily as + // well. There are four different create signatures, we'll just show one + // of them here. You can read about the other ones in the [commit API + // docs][cd]. // - // libgit2 provides a couple of methods to create commit objects easily as well. There are four - // different create signatures, we'll just show one of them here. You can read about the other - // ones in the [commit API docs][cd]. // [cd]: http://libgit2.github.com/libgit2/#HEAD/group/commit printf("\n*Commit Writing*\n"); @@ -185,24 +219,27 @@ int main (int argc, char** argv) git_tree *tree; git_commit *parent; - // Creating signatures for an authoring identity and time is pretty simple - you will need to have - // this to create a commit in order to specify who created it and when. Default values for the name - // and email should be found in the `user.name` and `user.email` configuration options. See the `config` - // section of this example file to see how to access config values. - git_signature_new((git_signature **)&author, "Scott Chacon", "schacon@gmail.com", - 123456789, 60); - git_signature_new((git_signature **)&cmtter, "Scott A Chacon", "scott@github.com", - 987654321, 90); + // 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 + // values for the name and email should be found in the `user.name` and + // `user.email` configuration options. See the `config` section of this + // example file to see how to access config values. + git_signature_new((git_signature **)&author, + "Scott Chacon", "schacon@gmail.com", 123456789, 60); + git_signature_new((git_signature **)&cmtter, + "Scott A Chacon", "scott@github.com", 987654321, 90); - // 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, but you can also use + // 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, + // but you can also use git_oid_fromstr(&tree_id, "28873d96b4e8f4e33ea30f4c682fd325f7ba56ac"); git_tree_lookup(&tree, repo, &tree_id); git_oid_fromstr(&parent_id, "f0877d0b841d75172ec404fc9370173dfffc20d1"); git_commit_lookup(&parent, repo, &parent_id); - // 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 `commit_id` variable here. + // 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 + // `commit_id` variable here. git_commit_create_v( &commit_id, /* out id */ repo, @@ -219,35 +256,42 @@ int main (int argc, char** argv) printf("New Commit: %s\n", out); // #### Tag Parsing - // You can parse and create tags with the [tag management API][tm], which functions very similarly - // to the commit lookup, parsing and creation methods, since the objects themselves are very similar. + + // You can parse and create tags with the [tag management API][tm], which + // functions very similarly to the commit lookup, parsing and creation + // methods, since the objects themselves are very similar. + // // [tm]: http://libgit2.github.com/libgit2/#HEAD/group/tag printf("\n*Tag Parsing*\n"); git_tag *tag; const char *tmessage, *tname; git_otype ttype; - // We create an oid for the tag object if we know the SHA and look it up in the repository the same - // way that we would a commit (or any other) object. + // We create an oid for the tag object if we know the SHA and look it up + // the same way that we would a commit (or any other object). git_oid_fromstr(&oid, "bc422d45275aca289c51d79830b45cecebff7c3a"); error = git_tag_lookup(&tag, repo, &oid); + check_error(error, "looking up tag"); - // Now that we have the tag object, we can extract the information it 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. + // Now that we have the tag object, we can extract the information it + // 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); - tname = git_tag_name(tag); // "test" - ttype = git_tag_target_type(tag); // GIT_OBJ_COMMIT (otype enum) - tmessage = git_tag_message(tag); // "tag message\n" + tname = git_tag_name(tag); // "test" + ttype = git_tag_target_type(tag); // GIT_OBJ_COMMIT (otype enum) + tmessage = git_tag_message(tag); // "tag message\n" printf("Tag Message: %s\n", tmessage); git_commit_free(commit); // #### Tree Parsing - // [Tree parsing][tp] is a bit different than the other objects, in that we have a subtype which is the - // tree entry. This is not an actual object type in Git, but a useful structure for parsing and - // traversing tree entries. + + // [Tree parsing][tp] is a bit different than the other objects, in that + // we have a subtype which is the tree entry. This is not an actual + // object type in Git, but a useful structure for parsing and traversing + // tree entries. // // [tp]: http://libgit2.github.com/libgit2/#HEAD/group/tree printf("\n*Tree Parsing*\n"); @@ -259,31 +303,36 @@ int main (int argc, char** argv) git_oid_fromstr(&oid, "2a741c18ac5ff082a7caaec6e74db3075a1906b5"); git_tree_lookup(&tree, repo, &oid); - // Getting the count of entries in the tree so you can iterate over them if you want to. + // Getting the count of entries in the tree so you can iterate over them + // if you want to. size_t cnt = git_tree_entrycount(tree); // 3 printf("tree entries: %d\n", (int)cnt); entry = git_tree_entry_byindex(tree, 0); printf("Entry name: %s\n", git_tree_entry_name(entry)); // "hello.c" - // You can also access tree entries by name if you know the name of the entry you're looking for. + // 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, "hello.c"); git_tree_entry_name(entry); // "hello.c" - // Once you have the entry object, you can access the content or subtree (or commit, in the case - // of submodules) that it points to. You can also get the mode if you want. + // Once you have the entry object, you can access the content or subtree + // (or commit, in the case of submodules) that it points to. You can also + // get the mode if you want. git_tree_entry_to_object(&objt, repo, entry); // blob // Remember to close the looked-up object once you are done using it git_object_free(objt); // #### Blob Parsing - // - // The last object type is the simplest and requires the least parsing help. Blobs are just file - // contents and can contain anything, there is no structure to it. The main advantage to using the - // [simple blob api][ba] is that when you're creating blobs you don't have to calculate the size - // of the content. There is also a helper for reading a file from disk and writing it to the db and - // getting the oid back so you don't have to do all those steps yourself. + + // The last object type is the simplest and requires the least parsing + // help. Blobs are just file contents and can contain anything, there is + // no structure to it. The main advantage to using the [simple blob + // api][ba] is that when you're creating blobs you don't have to calculate + // the size of the content. There is also a helper for reading a file + // from disk and writing it to the db and getting the oid back so you + // don't have to do all those steps yourself. // // [ba]: http://libgit2.github.com/libgit2/#HEAD/group/blob @@ -294,19 +343,21 @@ int main (int argc, char** argv) git_blob_lookup(&blob, repo, &oid); // 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 (e.g. binary files): - // do not consider the buffer a NULL-terminated string, and use the `git_blob_rawsize` attribute to - // find out its exact size in bytes + // 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 + // string, and use the `git_blob_rawsize` attribute to find out its exact + // size in bytes printf("Blob Size: %ld\n", (long)git_blob_rawsize(blob)); // 8 git_blob_rawcontent(blob); // "content" // ### 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. + + // 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 @@ -316,11 +367,13 @@ int main (int argc, char** argv) git_oid_fromstr(&oid, "f0877d0b841d75172ec404fc9370173dfffc20d1"); - // 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 + // 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); @@ -329,28 +382,32 @@ int main (int argc, char** argv) const git_signature *cauth; const char *cmsg; - // Now that we have the starting point pushed onto the walker, we can 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 commited 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 + // 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 commited 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 + // 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); // ### 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). + + // 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 @@ -359,15 +416,18 @@ int main (int argc, char** argv) git_index *index; unsigned int i, ecount; - // 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. + // 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 + // 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); @@ -380,24 +440,25 @@ int main (int argc, char** argv) git_index_free(index); // ### 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). + + // 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 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. + // Here we will implement something like `git for-each-ref` simply listing + // out all available references and the object SHA they resolve to. git_strarray ref_list; git_reference_list(&ref_list, repo, GIT_REF_LISTALL); const char *refname; git_reference *ref; - // 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. + // 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. for (i = 0; i < ref_list.count; ++i) { refname = ref_list.strings[i]; git_reference_lookup(&ref, repo, refname); @@ -420,9 +481,9 @@ int main (int argc, char** argv) git_strarray_free(&ref_list); // ### Config Files - // - // The [config API][config] allows you to list and updatee config values in - // any of the accessible config file locations (system, global, local). + + // 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 From 71d62d3905723c0263ca00a1d68825e2c35fb987 Mon Sep 17 00:00:00 2001 From: Russell Belfer Date: Fri, 15 Feb 2013 16:01:31 -0800 Subject: [PATCH 2/3] Fix memory leak in p_getaddrinfo on Amiga If gethostbyname() fails on platforms with NO_ADDRINFO, the code leaks the struct addrinfo that was allocated. This fixes that (and a number of code formatting issues in that area of code in src/posix.c). --- src/posix.c | 49 +++++++++++++++++++++++-------------------------- 1 file changed, 23 insertions(+), 26 deletions(-) diff --git a/src/posix.c b/src/posix.c index 95cd28edc..5d526d33c 100644 --- a/src/posix.c +++ b/src/posix.c @@ -13,25 +13,28 @@ #ifndef GIT_WIN32 #ifdef NO_ADDRINFO + int p_getaddrinfo( const char *host, const char *port, struct addrinfo *hints, struct addrinfo **info) { - GIT_UNUSED(hints); - struct addrinfo *ainfo, *ai; int p = 0; - + + GIT_UNUSED(hints); + if ((ainfo = malloc(sizeof(struct addrinfo))) == NULL) return -1; - - if ((ainfo->ai_hostent = gethostbyname(host)) == NULL) + + if ((ainfo->ai_hostent = gethostbyname(host)) == NULL) { + free(ainfo); return -2; - + } + ainfo->ai_servent = getservbyname(port, 0); - + if (ainfo->ai_servent) ainfo->ai_port = ainfo->ai_servent->s_port; else @@ -50,14 +53,14 @@ int p_getaddrinfo( ainfo->ai_addrlen = sizeof(struct sockaddr_in); *info = ainfo; - + if (ainfo->ai_hostent->h_addr_list[1] == NULL) { ainfo->ai_next = NULL; return 0; } - + ai = ainfo; - + for (p = 1; ainfo->ai_hostent->h_addr_list[p] != NULL; p++) { ai->ai_next = malloc(sizeof(struct addrinfo)); memcpy(&ai->ai_next, ainfo, sizeof(struct addrinfo)); @@ -67,7 +70,7 @@ int p_getaddrinfo( ai->ai_next->ai_addr = (struct addrinfo *)&ai->ai_next->ai_addr_in; ai = ai->ai_next; } - + ai->ai_next = NULL; return 0; } @@ -75,9 +78,9 @@ int p_getaddrinfo( void p_freeaddrinfo(struct addrinfo *info) { struct addrinfo *p, *next; - + p = info; - + while(p != NULL) { next = p->ai_next; free(p); @@ -88,27 +91,19 @@ void p_freeaddrinfo(struct addrinfo *info) const char *p_gai_strerror(int ret) { switch(ret) { - case -1: - return "Out of memory"; - break; - - case -2: - return "Address lookup failed"; - break; - - default: - return "Unknown error"; - break; + case -1: return "Out of memory"; break; + case -2: return "Address lookup failed"; break; + default: return "Unknown error"; break; } } + #endif /* NO_ADDRINFO */ int p_open(const char *path, int flags, ...) { mode_t mode = 0; - if (flags & O_CREAT) - { + if (flags & O_CREAT) { va_list arg_list; va_start(arg_list, flags); @@ -159,6 +154,7 @@ int p_rename(const char *from, const char *to) int p_read(git_file fd, void *buf, size_t cnt) { char *b = buf; + while (cnt) { ssize_t r; #ifdef GIT_WIN32 @@ -183,6 +179,7 @@ int p_read(git_file fd, void *buf, size_t cnt) int p_write(git_file fd, const void *buf, size_t cnt) { const char *b = buf; + while (cnt) { ssize_t r; #ifdef GIT_WIN32 From 56543a609aa7adb14b308046445ddd48f44322b7 Mon Sep 17 00:00:00 2001 From: Russell Belfer Date: Fri, 15 Feb 2013 16:02:45 -0800 Subject: [PATCH 3/3] Clear up warnings from cppcheck The cppcheck static analyzer generates warnings for a bunch of places in the libgit2 code base. All the ones fixed in this commit are actually false positives, but I've reorganized the code to hopefully make it easier for static analysis tools to correctly understand the structure. I wouldn't do this if I felt like it was making the code harder to read or worse for humans, but in this case, these fixes don't seem too bad and will hopefully make it easier for better analysis tools to get at any real issues. --- src/checkout.c | 10 +++++++--- src/diff_output.c | 15 ++++++++------- src/notes.c | 2 +- src/refs.c | 2 +- src/transports/winhttp.c | 2 +- tests-clar/clar_libgit2.c | 16 ++++++++++------ tests-clar/core/env.c | 2 ++ 7 files changed, 30 insertions(+), 19 deletions(-) diff --git a/src/checkout.c b/src/checkout.c index 0ce283beb..59cd218a9 100644 --- a/src/checkout.c +++ b/src/checkout.c @@ -64,6 +64,7 @@ static int checkout_notify( { git_diff_file wdfile; const git_diff_file *baseline = NULL, *target = NULL, *workdir = NULL; + const char *path = NULL; if (!data->opts.notify_cb) return 0; @@ -81,6 +82,8 @@ static int checkout_notify( wdfile.mode = wditem->mode; workdir = &wdfile; + + path = wditem->path; } if (delta) { @@ -101,11 +104,12 @@ static int checkout_notify( baseline = &delta->old_file; break; } + + path = delta->old_file.path; } return data->opts.notify_cb( - why, delta ? delta->old_file.path : wditem->path, - baseline, target, workdir, data->opts.notify_payload); + why, path, baseline, target, workdir, data->opts.notify_payload); } static bool checkout_is_workdir_modified( @@ -683,7 +687,7 @@ static int blob_content_to_file( { int error = -1, nb_filters = 0; mode_t file_mode = opts->file_mode; - bool dont_free_filtered = false; + bool dont_free_filtered; git_buf unfiltered = GIT_BUF_INIT, filtered = GIT_BUF_INIT; git_vector filters = GIT_VECTOR_INIT; diff --git a/src/diff_output.c b/src/diff_output.c index 26b073aad..88ccc9d45 100644 --- a/src/diff_output.c +++ b/src/diff_output.c @@ -1280,14 +1280,15 @@ static void set_data_from_buffer( { file->size = (git_off_t)buffer_len; file->mode = 0644; - - if (!buffer) - file->flags |= GIT_DIFF_FILE_NO_DATA; - else - git_odb_hash(&file->oid, buffer, buffer_len, GIT_OBJ_BLOB); - map->len = buffer_len; - map->data = (char *)buffer; + + if (!buffer) { + file->flags |= GIT_DIFF_FILE_NO_DATA; + map->data = NULL; + } else { + map->data = (char *)buffer; + git_odb_hash(&file->oid, buffer, buffer_len, GIT_OBJ_BLOB); + } } typedef struct { diff --git a/src/notes.c b/src/notes.c index eff80bc82..f5537db3f 100644 --- a/src/notes.c +++ b/src/notes.c @@ -147,7 +147,7 @@ static int manipulate_note_in_tree_r( int fanout, int current_error)) { - int error = -1; + int error; git_tree *subtree = NULL, *new = NULL; char subtree_name[3]; diff --git a/src/refs.c b/src/refs.c index 7dabfefae..866c230e6 100644 --- a/src/refs.c +++ b/src/refs.c @@ -1493,7 +1493,7 @@ int git_reference_foreach( /* list all the packed references first */ if (list_flags & GIT_REF_PACKED) { const char *ref_name; - void *ref; + void *ref = NULL; GIT_UNUSED(ref); if (packed_load(repo) < 0) diff --git a/src/transports/winhttp.c b/src/transports/winhttp.c index 64bfece34..970fa53bd 100644 --- a/src/transports/winhttp.c +++ b/src/transports/winhttp.c @@ -88,7 +88,7 @@ static int apply_basic_credential(HINTERNET request, git_cred *cred) git_cred_userpass_plaintext *c = (git_cred_userpass_plaintext *)cred; git_buf buf = GIT_BUF_INIT, raw = GIT_BUF_INIT; wchar_t *wide = NULL; - int error = -1, wide_len; + int error = -1, wide_len = 0; git_buf_printf(&raw, "%s:%s", c->username, c->password); diff --git a/tests-clar/clar_libgit2.c b/tests-clar/clar_libgit2.c index 63efd5954..698aa90f0 100644 --- a/tests-clar/clar_libgit2.c +++ b/tests-clar/clar_libgit2.c @@ -86,14 +86,18 @@ int cl_setenv(const char *name, const char *value) git__utf8_to_16(name_utf16, GIT_WIN_PATH, name); - if (value != NULL) + if (value) { git__utf8_to_16(value_utf16, GIT_WIN_PATH, value); + cl_assert(SetEnvironmentVariableW(name_utf16, value_utf16)); + } else { + /* Windows XP returns 0 (failed) when passing NULL for lpValue when + * lpName does not exist in the environment block. This behavior + * seems to have changed in later versions. Don't check return value + * of SetEnvironmentVariable when passing NULL for lpValue. + */ + SetEnvironmentVariableW(name_utf16, NULL); + } - /* Windows XP returns 0 (failed) when passing NULL for lpValue when lpName - * does not exist in the environment block. This behavior seems to have changed - * in later versions. Don't fail when SetEnvironmentVariable fails, if we passed - * NULL for lpValue. */ - cl_assert(SetEnvironmentVariableW(name_utf16, value ? value_utf16 : NULL) || !value); return 0; } diff --git a/tests-clar/core/env.c b/tests-clar/core/env.c index fa48de17e..2f5e91f71 100644 --- a/tests-clar/core/env.c +++ b/tests-clar/core/env.c @@ -74,6 +74,8 @@ void test_core_env__0(void) char **val; memset(testfile, 0, sizeof(testfile)); + cl_assert_equal_s("", testfile); + memcpy(testfile, "testfile", 8); cl_assert_equal_s("testfile", testfile);