showindex.c 1.94 KB
Newer Older
Ben Straub committed
1
/*
2
 * libgit2 "showindex" example - shows how to extract data from the index
Ben Straub committed
3
 *
4 5 6 7 8 9 10 11 12
 * Written by the libgit2 contributors
 *
 * To the extent possible under law, the author(s) have dedicated all copyright
 * and related and neighboring rights to this software to the public domain
 * worldwide. This software is distributed without any warranty.
 *
 * You should have received a copy of the CC0 Public Domain Dedication along
 * with this software. If not, see
 * <http://creativecommons.org/publicdomain/zero/1.0/>.
Ben Straub committed
13 14 15
 */

#include "common.h"
Scott Chacon committed
16 17 18

int main (int argc, char** argv)
{
19 20 21
	git_index *index;
	unsigned int i, ecount;
	char *dir = ".";
22
	size_t dirlen;
23 24
	char out[GIT_OID_HEXSZ+1];
	out[GIT_OID_HEXSZ] = '\0';
25

26
	git_libgit2_init();
27

Ben Straub committed
28 29
	if (argc > 2)
		fatal("usage: showindex [<repo-dir>]", NULL);
30 31 32
	if (argc > 1)
		dir = argv[1];

33 34
	dirlen = strlen(dir);
	if (dirlen > 5 && strcmp(dir + dirlen - 5, "index") == 0) {
Ben Straub committed
35
		check_lg2(git_index_open(&index, dir), "could not open index", dir);
36
	} else {
Ben Straub committed
37 38 39 40
		git_repository *repo;
		check_lg2(git_repository_open_ext(&repo, dir, 0, NULL), "could not open repository", dir);
		check_lg2(git_repository_index(&index, repo), "could not open repository index", NULL);
		git_repository_free(repo);
41 42
	}

43
	git_index_read(index, 0);
44 45 46 47 48 49 50 51

	ecount = git_index_entrycount(index);
	if (!ecount)
		printf("Empty index\n");

	for (i = 0; i < ecount; ++i) {
		const git_index_entry *e = git_index_get_byindex(index, i);

52
		git_oid_fmt(out, &e->id);
53 54 55 56

		printf("File Path: %s\n", e->path);
		printf("    Stage: %d\n", git_index_entry_stage(e));
		printf(" Blob SHA: %s\n", out);
57 58 59 60
		printf("File Mode: %07o\n", e->mode);
		printf("File Size: %d bytes\n", (int)e->file_size);
		printf("Dev/Inode: %d/%d\n", (int)e->dev, (int)e->ino);
		printf("  UID/GID: %d/%d\n", (int)e->uid, (int)e->gid);
61 62 63 64 65 66
		printf("    ctime: %d\n", (int)e->ctime.seconds);
		printf("    mtime: %d\n", (int)e->mtime.seconds);
		printf("\n");
	}

	git_index_free(index);
67
	git_libgit2_shutdown();
68

69
	return 0;
Scott Chacon committed
70
}