examples: add a basic for-each-ref example This is quite close to running "git for-each-ref" except: 1. It does not take any formatting or selection options at all. 2. The output is not sorted. I wrote it to look at debugging some issues with ref iteration, but there's no reason it can't live on as an example command.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
diff --git a/examples/.gitignore b/examples/.gitignore
index b652e28..083c883 100644
--- a/examples/.gitignore
+++ b/examples/.gitignore
@@ -9,4 +9,5 @@ log
rev-parse
status
tag
+for-each-ref
*.dSYM
diff --git a/examples/Makefile b/examples/Makefile
index e866b7f..11b0199 100644
--- a/examples/Makefile
+++ b/examples/Makefile
@@ -4,6 +4,7 @@ CC = gcc
CFLAGS = -g -I../include -I../src -Wall -Wextra -Wmissing-prototypes -Wno-missing-field-initializers
LFLAGS = -L../build -lgit2 -lz
APPS = general showindex diff rev-list cat-file status log rev-parse init blame tag
+APPS += for-each-ref
all: $(APPS)
diff --git a/examples/for-each-ref.c b/examples/for-each-ref.c
new file mode 100644
index 0000000..d6846bb
--- /dev/null
+++ b/examples/for-each-ref.c
@@ -0,0 +1,46 @@
+#include <git2.h>
+#include <stdio.h>
+#include "common.h"
+
+static int show_ref(git_reference *ref, void *data)
+{
+ git_repository *repo = data;
+ git_reference *resolved = NULL;
+ char hex[GIT_OID_HEXSZ+1];
+ const git_oid *oid;
+ git_object *obj;
+
+ if (git_reference_type(ref) == GIT_REF_SYMBOLIC)
+ check_lg2(git_reference_resolve(&resolved, ref),
+ "Unable to resolve symbolic reference",
+ git_reference_name(ref));
+
+ oid = git_reference_target(resolved ? resolved : ref);
+ git_oid_fmt(hex, oid);
+ hex[GIT_OID_HEXSZ] = 0;
+ check_lg2(git_object_lookup(&obj, repo, oid, GIT_OBJ_ANY),
+ "Unable to lookup object", hex);
+
+ printf("%s %-6s\t%s\n",
+ hex,
+ git_object_type2string(git_object_type(obj)),
+ git_reference_name(ref));
+
+ if (resolved)
+ git_reference_free(resolved);
+ return 0;
+}
+
+int main(int argc, char **argv)
+{
+ git_repository *repo;
+
+ if (argc != 1 || argv[1] /* silence -Wunused-parameter */)
+ fatal("Sorry, no for-each-ref options supported yet", NULL);
+
+ check_lg2(git_repository_open(&repo, "."),
+ "Could not open repository", NULL);
+ check_lg2(git_reference_foreach(repo, show_ref, repo),
+ "Could not iterate over references", NULL);
+ return 0;
+}