Dirty work state for cloning repo using arguments
[gitlite/.git] / gitlite.c
1 #include <libgen.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <sys/param.h>
6 #include <unistd.h>
7
8 #include <git2/global.h>
9 #include <git2/clone.h>
10 #include <git2/errors.h>
11
12 // Compile with:
13 // clang90 -o gitlite gitlite.c -lgit2 -I/usr/local/include -L/usr/local/lib -g
14
15 void
16 git_bail_error(int rc)
17 {
18     const git_error *err = NULL;
19
20         if (rc < 0) {
21                 err = git_error_last();
22                 if (err) 
23             printf("ERROR %d: %s\n", err->klass, err->message);
24                 else 
25             printf("ERROR %d: cannot fetch error info\n", rc);
26
27     }
28 }
29
30 void
31 util_stripext(char *path)
32 {
33         char *end = path + strlen(path);
34
35         while (end > path && *end != '.') {
36                 --end;
37         }
38
39         if (end > path) {
40                 *end = '\0';
41         }
42 }
43
44 int
45 main(int argc, char *argv[])
46 {
47         int rc;
48         //const char *url = "https://github.com/freebsd/freebsd.git";
49         const char *url = "https://github.com/freebsd/pkg.git";
50         char buff[MAXPATHLEN];
51         char *ext = NULL;
52         char *local_path = NULL;
53
54         git_clone_options clone_opts = GIT_CLONE_OPTIONS_INIT;
55         git_checkout_options co_opts = GIT_CHECKOUT_OPTIONS_INIT;
56         git_repository *cloned_repo = NULL;
57
58         co_opts.checkout_strategy = GIT_CHECKOUT_SAFE;
59         co_opts.progress_cb = NULL;
60         co_opts.progress_payload = NULL;
61         clone_opts.checkout_opts = co_opts;
62         clone_opts.fetch_opts.callbacks.sideband_progress = NULL;
63         clone_opts.fetch_opts.callbacks.transfer_progress = NULL;
64         clone_opts.fetch_opts.callbacks.credentials = NULL;
65         clone_opts.fetch_opts.callbacks.payload = NULL;
66
67         rc = git_libgit2_init();
68         git_bail_error(rc);
69
70         if (argc == 1) {
71                 fprintf(stderr, "Usage: gitlite <git-url> [path]\n");
72                 return -1;
73         }
74         
75         if (argv[1] != NULL) {
76                 url = argv[1];
77         }
78
79         if (argv[2] != NULL) {
80                 local_path = argv[2];
81         } else {
82                 ext = strdup(basename(__DECONST(char*, url)));
83                 util_stripext(__DECONST(char*, ext));
84                 asprintf(&local_path, "%s/%s", getwd(buff), ext);
85         }
86         //printf("%s\n", local_path);
87
88         rc = git_clone(&cloned_repo, url, local_path, &clone_opts);
89         git_bail_error(rc);
90
91         if (cloned_repo)
92                 git_repository_free(cloned_repo);
93
94         rc = git_libgit2_shutdown();
95         git_bail_error(rc);
96
97         if (ext != NULL)
98                 free(ext);
99
100     return (rc);
101 }