notes: convert write_notes_tree to object_id
[git/git.git] / notes-cache.c
CommitLineData
a941d5e3
JK
1#include "cache.h"
2#include "notes-cache.h"
3#include "commit.h"
4#include "refs.h"
5
6static int notes_cache_match_validity(const char *ref, const char *validity)
7{
569aa376 8 struct object_id oid;
a941d5e3
JK
9 struct commit *commit;
10 struct pretty_print_context pretty_ctx;
11 struct strbuf msg = STRBUF_INIT;
12 int ret;
13
34c290a6 14 if (read_ref(ref, &oid) < 0)
a941d5e3
JK
15 return 0;
16
bc83266a 17 commit = lookup_commit_reference_gently(&oid, 1);
a941d5e3
JK
18 if (!commit)
19 return 0;
20
21 memset(&pretty_ctx, 0, sizeof(pretty_ctx));
22 format_commit_message(commit, "%s", &msg, &pretty_ctx);
23 strbuf_trim(&msg);
24
25 ret = !strcmp(msg.buf, validity);
26 strbuf_release(&msg);
27
28 return ret;
29}
30
31void notes_cache_init(struct notes_cache *c, const char *name,
32 const char *validity)
33{
34 struct strbuf ref = STRBUF_INIT;
ee76f92f 35 int flags = NOTES_INIT_WRITABLE;
a941d5e3
JK
36
37 memset(c, 0, sizeof(*c));
38 c->validity = xstrdup(validity);
39
40 strbuf_addf(&ref, "refs/notes/%s", name);
41 if (!notes_cache_match_validity(ref.buf, validity))
ee76f92f 42 flags |= NOTES_INIT_EMPTY;
a941d5e3
JK
43 init_notes(&c->tree, ref.buf, combine_notes_overwrite, flags);
44 strbuf_release(&ref);
45}
46
47int notes_cache_write(struct notes_cache *c)
48{
569aa376 49 struct object_id tree_oid, commit_oid;
a941d5e3 50
ee76f92f
MH
51 if (!c || !c->tree.initialized || !c->tree.update_ref ||
52 !*c->tree.update_ref)
a941d5e3
JK
53 return -1;
54 if (!c->tree.dirty)
55 return 0;
56
bbca96d5 57 if (write_notes_tree(&c->tree, &tree_oid))
a941d5e3 58 return -1;
5078f344
PO
59 if (commit_tree(c->validity, strlen(c->validity), &tree_oid, NULL,
60 &commit_oid, NULL, NULL) < 0)
a941d5e3 61 return -1;
ae077771 62 if (update_ref("update notes cache", c->tree.update_ref, &commit_oid,
ee76f92f 63 NULL, 0, UPDATE_REFS_QUIET_ON_ERR) < 0)
a941d5e3
JK
64 return -1;
65
66 return 0;
67}
68
569aa376 69char *notes_cache_get(struct notes_cache *c, struct object_id *key_oid,
a941d5e3
JK
70 size_t *outsize)
71{
9ef72230 72 const struct object_id *value_oid;
a941d5e3
JK
73 enum object_type type;
74 char *value;
75 unsigned long size;
76
5ee8a954 77 value_oid = get_note(&c->tree, key_oid);
9ef72230 78 if (!value_oid)
a941d5e3 79 return NULL;
9ef72230 80 value = read_sha1_file(value_oid->hash, &type, &size);
a941d5e3
JK
81
82 *outsize = size;
83 return value;
84}
85
569aa376 86int notes_cache_put(struct notes_cache *c, struct object_id *key_oid,
a941d5e3
JK
87 const char *data, size_t size)
88{
569aa376 89 struct object_id value_oid;
a941d5e3 90
569aa376 91 if (write_sha1_file(data, size, "blob", value_oid.hash) < 0)
a941d5e3 92 return -1;
5ee8a954 93 return add_note(&c->tree, key_oid, &value_oid, NULL);
a941d5e3 94}