diff --git a/book/B-embedding-git/sections/libgit2.asc b/book/B-embedding-git/sections/libgit2.asc index 2e006fdc0..cd29ebc05 100644 --- a/book/B-embedding-git/sections/libgit2.asc +++ b/book/B-embedding-git/sections/libgit2.asc @@ -10,27 +10,43 @@ Here's a whirlwind tour: [source,c] ---- -// Open a repository -git_repository *repo; -int error = git_repository_open(&repo, "/path/to/repository"); - -// Dereference HEAD to a commit -git_object *head_commit; -error = git_revparse_single(&head_commit, repo, "HEAD^{commit}"); -git_commit *commit = (git_commit*)head_commit; - -// Print some of the commit's properties -printf("%s", git_commit_message(commit)); -const git_signature *author = git_commit_author(commit); -printf("%s <%s>\n", author->name, author->email); -const git_oid *tree_id = git_commit_tree_id(commit); +// If the name of this file is "head_commit_print.c", Compile this with: +// CC head_commit_print.c -o head_commit_print -lgit2 +// where CC is the C compiler of your choice (eg. gcc, clang, ...) +#include +#include -// Cleanup -git_commit_free(commit); -git_repository_free(repo); +int main() +{ + // Initialize global state of git + git_libgit2_init(); + + // Open a repository + git_repository *repo; + int error = git_repository_open(&repo, "/path/to/repository"); + + // Dereference HEAD to a commit + git_object *head_commit; + error = git_revparse_single(&head_commit, repo, "HEAD^{commit}"); + git_commit *commit = (git_commit*)head_commit; + + // Print some of the commit's properties + printf("%s", git_commit_message(commit)); + const git_signature *author = git_commit_author(commit); + printf("%s <%s>\n", author->name, author->email); + const git_oid *tree_id = git_commit_tree_id(commit); + + // Cleanup + git_commit_free(commit); + git_repository_free(repo); + + // Freeing resources from git_libgit2_init() + git_libgit2_shutdown(); +} ---- -The first couple of lines open a Git repository. +The first line in the main function initializes the global state for using libgit2 library functions. +The next couple of lines open a Git repository. The `git_repository` type represents a handle to a repository with a cache in memory. This is the simplest method, for when you know the exact path to a repository's working directory or `.git` folder. There's also the `git_repository_open_ext` which includes options for searching, `git_clone` and friends for making a local clone of a remote repository, and `git_repository_init` for creating an entirely new repository.