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"78static int notes_cache_match_validity(const char *ref, const char *validity)9{10struct object_id oid;11struct commit *commit;12struct pretty_print_context pretty_ctx;13struct strbuf msg = STRBUF_INIT;14int ret;1516if (read_ref(ref, &oid) < 0)17return 0;1819commit = lookup_commit_reference_gently(the_repository, &oid, 1);20if (!commit)21return 0;2223memset(&pretty_ctx, 0, sizeof(pretty_ctx));24format_commit_message(commit, "%s", &msg, &pretty_ctx);25strbuf_trim(&msg);2627ret = !strcmp(msg.buf, validity);28strbuf_release(&msg);2930return ret;31}3233void notes_cache_init(struct notes_cache *c, const char *name,34const char *validity)35{36struct strbuf ref = STRBUF_INIT;37int flags = NOTES_INIT_WRITABLE;3839memset(c, 0, sizeof(*c));40c->validity = xstrdup(validity);4142strbuf_addf(&ref, "refs/notes/%s", name);43if (!notes_cache_match_validity(ref.buf, validity))44flags |= NOTES_INIT_EMPTY;45init_notes(&c->tree, ref.buf, combine_notes_overwrite, flags);46strbuf_release(&ref);47}4849int notes_cache_write(struct notes_cache *c)50{51struct object_id tree_oid, commit_oid;5253if (!c || !c->tree.initialized || !c->tree.update_ref ||54!*c->tree.update_ref)55return -1;56if (!c->tree.dirty)57return 0;5859if (write_notes_tree(&c->tree, &tree_oid))60return -1;61if (commit_tree(c->validity, strlen(c->validity), &tree_oid, NULL,62&commit_oid, NULL, NULL) < 0)63return -1;64if (update_ref("update notes cache", c->tree.update_ref, &commit_oid,65NULL, 0, UPDATE_REFS_QUIET_ON_ERR) < 0)66return -1;6768return 0;69}7071char *notes_cache_get(struct notes_cache *c, struct object_id *key_oid,72size_t *outsize)73{74const struct object_id *value_oid;75enum object_type type;76char *value;77unsigned long size;7879value_oid = get_note(&c->tree, key_oid);80if (!value_oid)81return NULL;82value = read_object_file(value_oid, &type, &size);8384*outsize = size;85return value;86}8788int notes_cache_put(struct notes_cache *c, struct object_id *key_oid,89const char *data, size_t size)90{91struct object_id value_oid;9293if (write_object_file(data, size, "blob", &value_oid) < 0)94return -1;95return add_note(&c->tree, key_oid, &value_oid, NULL);96}