1#include "cache.h"
2#include "notes-cache.h"
3#include "object-store.h"
4#include "repository.h"
5#include "commit.h"
6#include "refs.h"
78
static int notes_cache_match_validity(struct repository *r,
9const char *ref,
10const char *validity)
11{
12struct object_id oid;
13struct commit *commit;
14struct pretty_print_context pretty_ctx;
15struct strbuf msg = STRBUF_INIT;
16int ret;
1718
if (read_ref(ref, &oid) < 0)
19return 0;
2021
commit = lookup_commit_reference_gently(r, &oid, 1);
22if (!commit)
23return 0;
2425
memset(&pretty_ctx, 0, sizeof(pretty_ctx));
26format_commit_message(commit, "%s", &msg, &pretty_ctx);
27strbuf_trim(&msg);
2829
ret = !strcmp(msg.buf, validity);
30strbuf_release(&msg);
3132
return ret;
33}
3435
void notes_cache_init(struct repository *r, struct notes_cache *c,
36const char *name, const char *validity)
37{
38struct strbuf ref = STRBUF_INIT;
39int flags = NOTES_INIT_WRITABLE;
4041
memset(c, 0, sizeof(*c));
42c->validity = xstrdup(validity);
4344
strbuf_addf(&ref, "refs/notes/%s", name);
45if (!notes_cache_match_validity(r, ref.buf, validity))
46flags |= NOTES_INIT_EMPTY;
47init_notes(&c->tree, ref.buf, combine_notes_overwrite, flags);
48strbuf_release(&ref);
49}
5051
int notes_cache_write(struct notes_cache *c)
52{
53struct object_id tree_oid, commit_oid;
5455
if (!c || !c->tree.initialized || !c->tree.update_ref ||
56!*c->tree.update_ref)
57return -1;
58if (!c->tree.dirty)
59return 0;
6061
if (write_notes_tree(&c->tree, &tree_oid))
62return -1;
63if (commit_tree(c->validity, strlen(c->validity), &tree_oid, NULL,
64&commit_oid, NULL, NULL) < 0)
65return -1;
66if (update_ref("update notes cache", c->tree.update_ref, &commit_oid,
67NULL, 0, UPDATE_REFS_QUIET_ON_ERR) < 0)
68return -1;
6970
return 0;
71}
7273
char *notes_cache_get(struct notes_cache *c, struct object_id *key_oid,
74size_t *outsize)
75{
76const struct object_id *value_oid;
77enum object_type type;
78char *value;
79unsigned long size;
8081
value_oid = get_note(&c->tree, key_oid);
82if (!value_oid)
83return NULL;
84value = read_object_file(value_oid, &type, &size);
8586
*outsize = size;
87return value;
88}
8990
int notes_cache_put(struct notes_cache *c, struct object_id *key_oid,
91const char *data, size_t size)
92{
93struct object_id value_oid;
9495
if (write_object_file(data, size, "blob", &value_oid) < 0)
96return -1;
97return add_note(&c->tree, key_oid, &value_oid, NULL);
98}