File: git2.c

package info (click to toggle)
libgit2 0.25.1%2Breally0.24.6-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 28,512 kB
  • ctags: 15,888
  • sloc: ansic: 153,520; sh: 297; python: 175; makefile: 70; php: 65
file content (73 lines) | stat: -rw-r--r-- 1,465 bytes parent folder | download | duplicates (2)
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
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "common.h"

// This part is not strictly libgit2-dependent, but you can use this
// as a starting point for a git-like tool

struct {
	char *name;
	git_cb fn;
} commands[] = {
	{"ls-remote", ls_remote},
	{"fetch", fetch},
	{"clone", do_clone},
	{"index-pack", index_pack},
	{ NULL, NULL}
};

static int run_command(git_cb fn, int argc, char **argv)
{
	int error;
	git_repository *repo;

	// Before running the actual command, create an instance of the local
	// repository and pass it to the function.

	error = git_repository_open(&repo, ".git");
	if (error < 0)
		repo = NULL;

	// Run the command. If something goes wrong, print the error message to stderr
	error = fn(repo, argc, argv);
	if (error < 0) {
		if (giterr_last() == NULL)
			fprintf(stderr, "Error without message");
		else
			fprintf(stderr, "Bad news:\n %s\n", giterr_last()->message);
	}

	if(repo)
		git_repository_free(repo);

	return !!error;
}

int main(int argc, char **argv)
{
	int i;
	int return_code = 1;

	if (argc < 2) {
		fprintf(stderr, "usage: %s <cmd> [repo]\n", argv[0]);
		exit(EXIT_FAILURE);
	}

	git_libgit2_init();

	for (i = 0; commands[i].name != NULL; ++i) {
		if (!strcmp(argv[1], commands[i].name)) {
			return_code = run_command(commands[i].fn, --argc, ++argv);
			goto shutdown;
		}
	}

	fprintf(stderr, "Command not found: %s\n", argv[1]);

shutdown:
	git_libgit2_shutdown();

	return return_code;
}