tag.c: Refactor parse_tag_buffer to be saner to program
[git.git] / tag.c
blobceb86557c5eedb03cbdc81929b7d109b44d440d5
1 #include "cache.h"
2 #include "tag.h"
3 #include "commit.h"
4 #include "tree.h"
5 #include "blob.h"
7 const char *tag_type = "tag";
9 struct object *deref_tag(struct object *o, const char *warn, int warnlen)
11 while (o && o->type == OBJ_TAG)
12 if (((struct tag *)o)->tagged)
13 o = parse_object(((struct tag *)o)->tagged->sha1);
14 else
15 o = NULL;
16 if (!o && warn) {
17 if (!warnlen)
18 warnlen = strlen(warn);
19 error("missing object referenced by '%.*s'", warnlen, warn);
21 return o;
24 struct tag *lookup_tag(const unsigned char *sha1)
26 struct object *obj = lookup_object(sha1);
27 if (!obj)
28 return create_object(sha1, OBJ_TAG, alloc_tag_node());
29 if (!obj->type)
30 obj->type = OBJ_TAG;
31 if (obj->type != OBJ_TAG) {
32 error("Object %s is a %s, not a tag",
33 sha1_to_hex(sha1), typename(obj->type));
34 return NULL;
36 return (struct tag *) obj;
39 int parse_tag_buffer(struct tag *item, void *data, unsigned long size)
41 unsigned char sha1[20];
42 char type[20];
43 const char *bufptr = data;
44 const char *tail = bufptr + size;
45 const char *nl;
47 if (item->object.parsed)
48 return 0;
49 item->object.parsed = 1;
51 if (size < 64)
52 return -1;
53 if (memcmp("object ", bufptr, 7) || get_sha1_hex(bufptr + 7, sha1) || bufptr[47] != '\n')
54 return -1;
55 bufptr += 48; /* "object " + sha1 + "\n" */
57 if (prefixcmp(bufptr, "type "))
58 return -1;
59 bufptr += 5;
60 nl = memchr(bufptr, '\n', tail - bufptr);
61 if (!nl || sizeof(type) <= (nl - bufptr))
62 return -1;
63 strncpy(type, bufptr, nl - bufptr);
64 type[nl - bufptr] = '\0';
65 bufptr = nl + 1;
67 if (!strcmp(type, blob_type)) {
68 item->tagged = &lookup_blob(sha1)->object;
69 } else if (!strcmp(type, tree_type)) {
70 item->tagged = &lookup_tree(sha1)->object;
71 } else if (!strcmp(type, commit_type)) {
72 item->tagged = &lookup_commit(sha1)->object;
73 } else if (!strcmp(type, tag_type)) {
74 item->tagged = &lookup_tag(sha1)->object;
75 } else {
76 error("Unknown type %s", type);
77 item->tagged = NULL;
80 if (prefixcmp(bufptr, "tag "))
81 return -1;
82 bufptr += 4;
83 nl = memchr(bufptr, '\n', tail - bufptr);
84 if (!nl)
85 return -1;
86 item->tag = xmemdupz(bufptr, nl - bufptr);
87 bufptr = nl + 1;
89 return 0;
92 int parse_tag(struct tag *item)
94 enum object_type type;
95 void *data;
96 unsigned long size;
97 int ret;
99 if (item->object.parsed)
100 return 0;
101 data = read_sha1_file(item->object.sha1, &type, &size);
102 if (!data)
103 return error("Could not read %s",
104 sha1_to_hex(item->object.sha1));
105 if (type != OBJ_TAG) {
106 free(data);
107 return error("Object %s not a tag",
108 sha1_to_hex(item->object.sha1));
110 ret = parse_tag_buffer(item, data, size);
111 free(data);
112 return ret;