1#include "pull.h"
2
3#include "cache.h"
4#include "commit.h"
5#include "tree.h"
6
7int get_tree = 0;
8int get_history = 0;
9int get_all = 0;
10static unsigned char current_commit_sha1[20];
11
12static const char commitS[] = "commit";
13static const char treeS[] = "tree";
14static const char blobS[] = "blob";
15
16static void report_missing(const char *what, const unsigned char *missing)
17{
18 char missing_hex[41];
19
20 strcpy(missing_hex, sha1_to_hex(missing));;
21 fprintf(stderr,
22 "Cannot obtain needed %s %s\nwhile processing commit %s.\n",
23 what, missing_hex, sha1_to_hex(current_commit_sha1));
24}
25
26static int make_sure_we_have_it(const char *what, unsigned char *sha1)
27{
28 int status;
29 if (has_sha1_file(sha1))
30 return 0;
31 status = fetch(sha1);
32 if (status && what)
33 report_missing(what, sha1);
34 return status;
35}
36
37static int process_tree(unsigned char *sha1)
38{
39 struct tree *tree = lookup_tree(sha1);
40 struct tree_entry_list *entries;
41
42 if (parse_tree(tree))
43 return -1;
44
45 for (entries = tree->entries; entries; entries = entries->next) {
46 const char *what = entries->directory ? treeS : blobS;
47 if (make_sure_we_have_it(what, entries->item.tree->object.sha1))
48 return -1;
49 if (entries->directory) {
50 if (process_tree(entries->item.tree->object.sha1))
51 return -1;
52 }
53 }
54 return 0;
55}
56
57static int process_commit(unsigned char *sha1)
58{
59 struct commit *obj = lookup_commit(sha1);
60
61 if (make_sure_we_have_it(commitS, sha1))
62 return -1;
63
64 if (parse_commit(obj))
65 return -1;
66
67 if (get_tree) {
68 if (make_sure_we_have_it(treeS, obj->tree->object.sha1))
69 return -1;
70 if (process_tree(obj->tree->object.sha1))
71 return -1;
72 if (!get_all)
73 get_tree = 0;
74 }
75 if (get_history) {
76 struct commit_list *parents = obj->parents;
77 for (; parents; parents = parents->next) {
78 if (has_sha1_file(parents->item->object.sha1))
79 continue;
80 if (make_sure_we_have_it(NULL,
81 parents->item->object.sha1)) {
82 /* The server might not have it, and
83 * we don't mind.
84 */
85 continue;
86 }
87 if (process_commit(parents->item->object.sha1))
88 return -1;
89 memcpy(current_commit_sha1, sha1, 20);
90 }
91 }
92 return 0;
93}
94
95int pull(char *target)
96{
97 int retval;
98 unsigned char sha1[20];
99 retval = get_sha1_hex(target, sha1);
100 if (retval)
101 return retval;
102 retval = make_sure_we_have_it(commitS, sha1);
103 if (retval)
104 return retval;
105 memcpy(current_commit_sha1, sha1, 20);
106 return process_commit(sha1);
107}