t2400: drop no-op `--sq` from rev-parse call
[git.git] / notes-cache.c
blobfbcdfd0dfe551211353c5c677ca97ff935341921
1 #include "git-compat-util.h"
2 #include "notes-cache.h"
3 #include "object-store.h"
4 #include "repository.h"
5 #include "commit.h"
6 #include "refs.h"
8 static int notes_cache_match_validity(struct repository *r,
9 const char *ref,
10 const char *validity)
12 struct object_id oid;
13 struct commit *commit;
14 struct pretty_print_context pretty_ctx;
15 struct strbuf msg = STRBUF_INIT;
16 int ret;
18 if (read_ref(ref, &oid) < 0)
19 return 0;
21 commit = lookup_commit_reference_gently(r, &oid, 1);
22 if (!commit)
23 return 0;
25 memset(&pretty_ctx, 0, sizeof(pretty_ctx));
26 repo_format_commit_message(r, commit, "%s", &msg,
27 &pretty_ctx);
28 strbuf_trim(&msg);
30 ret = !strcmp(msg.buf, validity);
31 strbuf_release(&msg);
33 return ret;
36 void notes_cache_init(struct repository *r, struct notes_cache *c,
37 const char *name, const char *validity)
39 struct strbuf ref = STRBUF_INIT;
40 int flags = NOTES_INIT_WRITABLE;
42 memset(c, 0, sizeof(*c));
43 c->validity = xstrdup(validity);
45 strbuf_addf(&ref, "refs/notes/%s", name);
46 if (!notes_cache_match_validity(r, ref.buf, validity))
47 flags |= NOTES_INIT_EMPTY;
48 init_notes(&c->tree, ref.buf, combine_notes_overwrite, flags);
49 strbuf_release(&ref);
52 int notes_cache_write(struct notes_cache *c)
54 struct object_id tree_oid, commit_oid;
56 if (!c || !c->tree.initialized || !c->tree.update_ref ||
57 !*c->tree.update_ref)
58 return -1;
59 if (!c->tree.dirty)
60 return 0;
62 if (write_notes_tree(&c->tree, &tree_oid))
63 return -1;
64 if (commit_tree(c->validity, strlen(c->validity), &tree_oid, NULL,
65 &commit_oid, NULL, NULL) < 0)
66 return -1;
67 if (update_ref("update notes cache", c->tree.update_ref, &commit_oid,
68 NULL, 0, UPDATE_REFS_QUIET_ON_ERR) < 0)
69 return -1;
71 return 0;
74 char *notes_cache_get(struct notes_cache *c, struct object_id *key_oid,
75 size_t *outsize)
77 const struct object_id *value_oid;
78 enum object_type type;
79 char *value;
80 unsigned long size;
82 value_oid = get_note(&c->tree, key_oid);
83 if (!value_oid)
84 return NULL;
85 value = repo_read_object_file(the_repository, value_oid, &type, &size);
87 *outsize = size;
88 return value;
91 int notes_cache_put(struct notes_cache *c, struct object_id *key_oid,
92 const char *data, size_t size)
94 struct object_id value_oid;
96 if (write_object_file(data, size, OBJ_BLOB, &value_oid) < 0)
97 return -1;
98 return add_note(&c->tree, key_oid, &value_oid, NULL);