e83f5e81363a9eadef850a89ada36551ad29b797
1#include "cache.h"
2#include "config.h"
3#include "notes.h"
4#include "blob.h"
5#include "tree.h"
6#include "utf8.h"
7#include "strbuf.h"
8#include "tree-walk.h"
9#include "string-list.h"
10#include "refs.h"
11
12/*
13 * Use a non-balancing simple 16-tree structure with struct int_node as
14 * internal nodes, and struct leaf_node as leaf nodes. Each int_node has a
15 * 16-array of pointers to its children.
16 * The bottom 2 bits of each pointer is used to identify the pointer type
17 * - ptr & 3 == 0 - NULL pointer, assert(ptr == NULL)
18 * - ptr & 3 == 1 - pointer to next internal node - cast to struct int_node *
19 * - ptr & 3 == 2 - pointer to note entry - cast to struct leaf_node *
20 * - ptr & 3 == 3 - pointer to subtree entry - cast to struct leaf_node *
21 *
22 * The root node is a statically allocated struct int_node.
23 */
24struct int_node {
25 void *a[16];
26};
27
28/*
29 * Leaf nodes come in two variants, note entries and subtree entries,
30 * distinguished by the LSb of the leaf node pointer (see above).
31 * As a note entry, the key is the SHA1 of the referenced object, and the
32 * value is the SHA1 of the note object.
33 * As a subtree entry, the key is the prefix SHA1 (w/trailing NULs) of the
34 * referenced object, using the last byte of the key to store the length of
35 * the prefix. The value is the SHA1 of the tree object containing the notes
36 * subtree.
37 */
38struct leaf_node {
39 struct object_id key_oid;
40 struct object_id val_oid;
41};
42
43/*
44 * A notes tree may contain entries that are not notes, and that do not follow
45 * the naming conventions of notes. There are typically none/few of these, but
46 * we still need to keep track of them. Keep a simple linked list sorted alpha-
47 * betically on the non-note path. The list is populated when parsing tree
48 * objects in load_subtree(), and the non-notes are correctly written back into
49 * the tree objects produced by write_notes_tree().
50 */
51struct non_note {
52 struct non_note *next; /* grounded (last->next == NULL) */
53 char *path;
54 unsigned int mode;
55 struct object_id oid;
56};
57
58#define PTR_TYPE_NULL 0
59#define PTR_TYPE_INTERNAL 1
60#define PTR_TYPE_NOTE 2
61#define PTR_TYPE_SUBTREE 3
62
63#define GET_PTR_TYPE(ptr) ((uintptr_t) (ptr) & 3)
64#define CLR_PTR_TYPE(ptr) ((void *) ((uintptr_t) (ptr) & ~3))
65#define SET_PTR_TYPE(ptr, type) ((void *) ((uintptr_t) (ptr) | (type)))
66
67#define GET_NIBBLE(n, sha1) ((((sha1)[(n) >> 1]) >> ((~(n) & 0x01) << 2)) & 0x0f)
68
69#define KEY_INDEX (GIT_SHA1_RAWSZ - 1)
70#define FANOUT_PATH_SEPARATORS ((GIT_SHA1_HEXSZ / 2) - 1)
71#define SUBTREE_SHA1_PREFIXCMP(key_sha1, subtree_sha1) \
72 (memcmp(key_sha1, subtree_sha1, subtree_sha1[KEY_INDEX]))
73
74struct notes_tree default_notes_tree;
75
76static struct string_list display_notes_refs = STRING_LIST_INIT_NODUP;
77static struct notes_tree **display_notes_trees;
78
79static void load_subtree(struct notes_tree *t, struct leaf_node *subtree,
80 struct int_node *node, unsigned int n);
81
82/*
83 * Search the tree until the appropriate location for the given key is found:
84 * 1. Start at the root node, with n = 0
85 * 2. If a[0] at the current level is a matching subtree entry, unpack that
86 * subtree entry and remove it; restart search at the current level.
87 * 3. Use the nth nibble of the key as an index into a:
88 * - If a[n] is an int_node, recurse from #2 into that node and increment n
89 * - If a matching subtree entry, unpack that subtree entry (and remove it);
90 * restart search at the current level.
91 * - Otherwise, we have found one of the following:
92 * - a subtree entry which does not match the key
93 * - a note entry which may or may not match the key
94 * - an unused leaf node (NULL)
95 * In any case, set *tree and *n, and return pointer to the tree location.
96 */
97static void **note_tree_search(struct notes_tree *t, struct int_node **tree,
98 unsigned char *n, const unsigned char *key_sha1)
99{
100 struct leaf_node *l;
101 unsigned char i;
102 void *p = (*tree)->a[0];
103
104 if (GET_PTR_TYPE(p) == PTR_TYPE_SUBTREE) {
105 l = (struct leaf_node *) CLR_PTR_TYPE(p);
106 if (!SUBTREE_SHA1_PREFIXCMP(key_sha1, l->key_oid.hash)) {
107 /* unpack tree and resume search */
108 (*tree)->a[0] = NULL;
109 load_subtree(t, l, *tree, *n);
110 free(l);
111 return note_tree_search(t, tree, n, key_sha1);
112 }
113 }
114
115 i = GET_NIBBLE(*n, key_sha1);
116 p = (*tree)->a[i];
117 switch (GET_PTR_TYPE(p)) {
118 case PTR_TYPE_INTERNAL:
119 *tree = CLR_PTR_TYPE(p);
120 (*n)++;
121 return note_tree_search(t, tree, n, key_sha1);
122 case PTR_TYPE_SUBTREE:
123 l = (struct leaf_node *) CLR_PTR_TYPE(p);
124 if (!SUBTREE_SHA1_PREFIXCMP(key_sha1, l->key_oid.hash)) {
125 /* unpack tree and resume search */
126 (*tree)->a[i] = NULL;
127 load_subtree(t, l, *tree, *n);
128 free(l);
129 return note_tree_search(t, tree, n, key_sha1);
130 }
131 /* fall through */
132 default:
133 return &((*tree)->a[i]);
134 }
135}
136
137/*
138 * To find a leaf_node:
139 * Search to the tree location appropriate for the given key:
140 * If a note entry with matching key, return the note entry, else return NULL.
141 */
142static struct leaf_node *note_tree_find(struct notes_tree *t,
143 struct int_node *tree, unsigned char n,
144 const unsigned char *key_sha1)
145{
146 void **p = note_tree_search(t, &tree, &n, key_sha1);
147 if (GET_PTR_TYPE(*p) == PTR_TYPE_NOTE) {
148 struct leaf_node *l = (struct leaf_node *) CLR_PTR_TYPE(*p);
149 if (!hashcmp(key_sha1, l->key_oid.hash))
150 return l;
151 }
152 return NULL;
153}
154
155/*
156 * How to consolidate an int_node:
157 * If there are > 1 non-NULL entries, give up and return non-zero.
158 * Otherwise replace the int_node at the given index in the given parent node
159 * with the only NOTE entry (or a NULL entry if no entries) from the given
160 * tree, and return 0.
161 */
162static int note_tree_consolidate(struct int_node *tree,
163 struct int_node *parent, unsigned char index)
164{
165 unsigned int i;
166 void *p = NULL;
167
168 assert(tree && parent);
169 assert(CLR_PTR_TYPE(parent->a[index]) == tree);
170
171 for (i = 0; i < 16; i++) {
172 if (GET_PTR_TYPE(tree->a[i]) != PTR_TYPE_NULL) {
173 if (p) /* more than one entry */
174 return -2;
175 p = tree->a[i];
176 }
177 }
178
179 if (p && (GET_PTR_TYPE(p) != PTR_TYPE_NOTE))
180 return -2;
181 /* replace tree with p in parent[index] */
182 parent->a[index] = p;
183 free(tree);
184 return 0;
185}
186
187/*
188 * To remove a leaf_node:
189 * Search to the tree location appropriate for the given leaf_node's key:
190 * - If location does not hold a matching entry, abort and do nothing.
191 * - Copy the matching entry's value into the given entry.
192 * - Replace the matching leaf_node with a NULL entry (and free the leaf_node).
193 * - Consolidate int_nodes repeatedly, while walking up the tree towards root.
194 */
195static void note_tree_remove(struct notes_tree *t,
196 struct int_node *tree, unsigned char n,
197 struct leaf_node *entry)
198{
199 struct leaf_node *l;
200 struct int_node *parent_stack[GIT_SHA1_RAWSZ];
201 unsigned char i, j;
202 void **p = note_tree_search(t, &tree, &n, entry->key_oid.hash);
203
204 assert(GET_PTR_TYPE(entry) == 0); /* no type bits set */
205 if (GET_PTR_TYPE(*p) != PTR_TYPE_NOTE)
206 return; /* type mismatch, nothing to remove */
207 l = (struct leaf_node *) CLR_PTR_TYPE(*p);
208 if (oidcmp(&l->key_oid, &entry->key_oid))
209 return; /* key mismatch, nothing to remove */
210
211 /* we have found a matching entry */
212 oidcpy(&entry->val_oid, &l->val_oid);
213 free(l);
214 *p = SET_PTR_TYPE(NULL, PTR_TYPE_NULL);
215
216 /* consolidate this tree level, and parent levels, if possible */
217 if (!n)
218 return; /* cannot consolidate top level */
219 /* first, build stack of ancestors between root and current node */
220 parent_stack[0] = t->root;
221 for (i = 0; i < n; i++) {
222 j = GET_NIBBLE(i, entry->key_oid.hash);
223 parent_stack[i + 1] = CLR_PTR_TYPE(parent_stack[i]->a[j]);
224 }
225 assert(i == n && parent_stack[i] == tree);
226 /* next, unwind stack until note_tree_consolidate() is done */
227 while (i > 0 &&
228 !note_tree_consolidate(parent_stack[i], parent_stack[i - 1],
229 GET_NIBBLE(i - 1, entry->key_oid.hash)))
230 i--;
231}
232
233/*
234 * To insert a leaf_node:
235 * Search to the tree location appropriate for the given leaf_node's key:
236 * - If location is unused (NULL), store the tweaked pointer directly there
237 * - If location holds a note entry that matches the note-to-be-inserted, then
238 * combine the two notes (by calling the given combine_notes function).
239 * - If location holds a note entry that matches the subtree-to-be-inserted,
240 * then unpack the subtree-to-be-inserted into the location.
241 * - If location holds a matching subtree entry, unpack the subtree at that
242 * location, and restart the insert operation from that level.
243 * - Else, create a new int_node, holding both the node-at-location and the
244 * node-to-be-inserted, and store the new int_node into the location.
245 */
246static int note_tree_insert(struct notes_tree *t, struct int_node *tree,
247 unsigned char n, struct leaf_node *entry, unsigned char type,
248 combine_notes_fn combine_notes)
249{
250 struct int_node *new_node;
251 struct leaf_node *l;
252 void **p = note_tree_search(t, &tree, &n, entry->key_oid.hash);
253 int ret = 0;
254
255 assert(GET_PTR_TYPE(entry) == 0); /* no type bits set */
256 l = (struct leaf_node *) CLR_PTR_TYPE(*p);
257 switch (GET_PTR_TYPE(*p)) {
258 case PTR_TYPE_NULL:
259 assert(!*p);
260 if (is_null_oid(&entry->val_oid))
261 free(entry);
262 else
263 *p = SET_PTR_TYPE(entry, type);
264 return 0;
265 case PTR_TYPE_NOTE:
266 switch (type) {
267 case PTR_TYPE_NOTE:
268 if (!oidcmp(&l->key_oid, &entry->key_oid)) {
269 /* skip concatenation if l == entry */
270 if (!oidcmp(&l->val_oid, &entry->val_oid))
271 return 0;
272
273 ret = combine_notes(l->val_oid.hash,
274 entry->val_oid.hash);
275 if (!ret && is_null_oid(&l->val_oid))
276 note_tree_remove(t, tree, n, entry);
277 free(entry);
278 return ret;
279 }
280 break;
281 case PTR_TYPE_SUBTREE:
282 if (!SUBTREE_SHA1_PREFIXCMP(l->key_oid.hash,
283 entry->key_oid.hash)) {
284 /* unpack 'entry' */
285 load_subtree(t, entry, tree, n);
286 free(entry);
287 return 0;
288 }
289 break;
290 }
291 break;
292 case PTR_TYPE_SUBTREE:
293 if (!SUBTREE_SHA1_PREFIXCMP(entry->key_oid.hash, l->key_oid.hash)) {
294 /* unpack 'l' and restart insert */
295 *p = NULL;
296 load_subtree(t, l, tree, n);
297 free(l);
298 return note_tree_insert(t, tree, n, entry, type,
299 combine_notes);
300 }
301 break;
302 }
303
304 /* non-matching leaf_node */
305 assert(GET_PTR_TYPE(*p) == PTR_TYPE_NOTE ||
306 GET_PTR_TYPE(*p) == PTR_TYPE_SUBTREE);
307 if (is_null_oid(&entry->val_oid)) { /* skip insertion of empty note */
308 free(entry);
309 return 0;
310 }
311 new_node = (struct int_node *) xcalloc(1, sizeof(struct int_node));
312 ret = note_tree_insert(t, new_node, n + 1, l, GET_PTR_TYPE(*p),
313 combine_notes);
314 if (ret)
315 return ret;
316 *p = SET_PTR_TYPE(new_node, PTR_TYPE_INTERNAL);
317 return note_tree_insert(t, new_node, n + 1, entry, type, combine_notes);
318}
319
320/* Free the entire notes data contained in the given tree */
321static void note_tree_free(struct int_node *tree)
322{
323 unsigned int i;
324 for (i = 0; i < 16; i++) {
325 void *p = tree->a[i];
326 switch (GET_PTR_TYPE(p)) {
327 case PTR_TYPE_INTERNAL:
328 note_tree_free(CLR_PTR_TYPE(p));
329 /* fall through */
330 case PTR_TYPE_NOTE:
331 case PTR_TYPE_SUBTREE:
332 free(CLR_PTR_TYPE(p));
333 }
334 }
335}
336
337/*
338 * Convert a partial SHA1 hex string to the corresponding partial SHA1 value.
339 * - hex - Partial SHA1 segment in ASCII hex format
340 * - hex_len - Length of above segment. Must be multiple of 2 between 0 and 40
341 * - oid - Partial SHA1 value is written here
342 * Return 0 on success or -1 on error (invalid arguments or input not
343 * in hex format).
344 */
345static int get_oid_hex_segment(const char *hex, unsigned int hex_len,
346 unsigned char *oid)
347{
348 unsigned int i, len = hex_len >> 1;
349 if (hex_len % 2 != 0)
350 return -1;
351 for (i = 0; i < len; i++) {
352 unsigned int val = (hexval(hex[0]) << 4) | hexval(hex[1]);
353 if (val & ~0xff)
354 return -1;
355 *oid++ = val;
356 hex += 2;
357 }
358 return 0;
359}
360
361static int non_note_cmp(const struct non_note *a, const struct non_note *b)
362{
363 return strcmp(a->path, b->path);
364}
365
366/* note: takes ownership of path string */
367static void add_non_note(struct notes_tree *t, char *path,
368 unsigned int mode, const unsigned char *sha1)
369{
370 struct non_note *p = t->prev_non_note, *n;
371 n = (struct non_note *) xmalloc(sizeof(struct non_note));
372 n->next = NULL;
373 n->path = path;
374 n->mode = mode;
375 hashcpy(n->oid.hash, sha1);
376 t->prev_non_note = n;
377
378 if (!t->first_non_note) {
379 t->first_non_note = n;
380 return;
381 }
382
383 if (non_note_cmp(p, n) < 0)
384 ; /* do nothing */
385 else if (non_note_cmp(t->first_non_note, n) <= 0)
386 p = t->first_non_note;
387 else {
388 /* n sorts before t->first_non_note */
389 n->next = t->first_non_note;
390 t->first_non_note = n;
391 return;
392 }
393
394 /* n sorts equal or after p */
395 while (p->next && non_note_cmp(p->next, n) <= 0)
396 p = p->next;
397
398 if (non_note_cmp(p, n) == 0) { /* n ~= p; overwrite p with n */
399 assert(strcmp(p->path, n->path) == 0);
400 p->mode = n->mode;
401 oidcpy(&p->oid, &n->oid);
402 free(n);
403 t->prev_non_note = p;
404 return;
405 }
406
407 /* n sorts between p and p->next */
408 n->next = p->next;
409 p->next = n;
410}
411
412static void load_subtree(struct notes_tree *t, struct leaf_node *subtree,
413 struct int_node *node, unsigned int n)
414{
415 struct object_id object_oid;
416 unsigned int prefix_len;
417 void *buf;
418 struct tree_desc desc;
419 struct name_entry entry;
420
421 buf = fill_tree_descriptor(&desc, subtree->val_oid.hash);
422 if (!buf)
423 die("Could not read %s for notes-index",
424 oid_to_hex(&subtree->val_oid));
425
426 prefix_len = subtree->key_oid.hash[KEY_INDEX];
427 assert(prefix_len * 2 >= n);
428 memcpy(object_oid.hash, subtree->key_oid.hash, prefix_len);
429 while (tree_entry(&desc, &entry)) {
430 unsigned char type;
431 struct leaf_node *l;
432 int path_len = strlen(entry.path);
433
434 if (path_len == 2 * (GIT_SHA1_RAWSZ - prefix_len)) {
435 /* This is potentially the remainder of the SHA-1 */
436
437 if (!S_ISREG(entry.mode))
438 /* notes must be blobs */
439 goto handle_non_note;
440
441 if (get_oid_hex_segment(entry.path, path_len,
442 object_oid.hash + prefix_len))
443 goto handle_non_note; /* entry.path is not a SHA1 */
444
445 type = PTR_TYPE_NOTE;
446 } else if (path_len == 2) {
447 /* This is potentially an internal node */
448 size_t len = prefix_len;
449
450 if (!S_ISDIR(entry.mode))
451 /* internal nodes must be trees */
452 goto handle_non_note;
453
454 if (get_oid_hex_segment(entry.path, 2,
455 object_oid.hash + len++))
456 goto handle_non_note; /* entry.path is not a SHA1 */
457
458 /*
459 * Pad the rest of the SHA-1 with zeros,
460 * except for the last byte, where we write
461 * the length:
462 */
463 memset(object_oid.hash + len, 0, GIT_SHA1_RAWSZ - len - 1);
464 object_oid.hash[KEY_INDEX] = (unsigned char)len;
465
466 type = PTR_TYPE_SUBTREE;
467 } else {
468 /* This can't be part of a note */
469 goto handle_non_note;
470 }
471
472 l = xcalloc(1, sizeof(*l));
473 oidcpy(&l->key_oid, &object_oid);
474 oidcpy(&l->val_oid, entry.oid);
475 if (note_tree_insert(t, node, n, l, type,
476 combine_notes_concatenate))
477 die("Failed to load %s %s into notes tree "
478 "from %s",
479 type == PTR_TYPE_NOTE ? "note" : "subtree",
480 oid_to_hex(&l->key_oid), t->ref);
481
482 continue;
483
484handle_non_note:
485 /*
486 * Determine full path for this non-note entry. The
487 * filename is already found in entry.path, but the
488 * directory part of the path must be deduced from the
489 * subtree containing this entry based on our
490 * knowledge that the overall notes tree follows a
491 * strict byte-based progressive fanout structure
492 * (i.e. using 2/38, 2/2/36, etc. fanouts).
493 */
494 {
495 struct strbuf non_note_path = STRBUF_INIT;
496 const char *q = oid_to_hex(&subtree->key_oid);
497 int i;
498 for (i = 0; i < prefix_len; i++) {
499 strbuf_addch(&non_note_path, *q++);
500 strbuf_addch(&non_note_path, *q++);
501 strbuf_addch(&non_note_path, '/');
502 }
503 strbuf_addstr(&non_note_path, entry.path);
504 add_non_note(t, strbuf_detach(&non_note_path, NULL),
505 entry.mode, entry.oid->hash);
506 }
507 }
508 free(buf);
509}
510
511/*
512 * Determine optimal on-disk fanout for this part of the notes tree
513 *
514 * Given a (sub)tree and the level in the internal tree structure, determine
515 * whether or not the given existing fanout should be expanded for this
516 * (sub)tree.
517 *
518 * Values of the 'fanout' variable:
519 * - 0: No fanout (all notes are stored directly in the root notes tree)
520 * - 1: 2/38 fanout
521 * - 2: 2/2/36 fanout
522 * - 3: 2/2/2/34 fanout
523 * etc.
524 */
525static unsigned char determine_fanout(struct int_node *tree, unsigned char n,
526 unsigned char fanout)
527{
528 /*
529 * The following is a simple heuristic that works well in practice:
530 * For each even-numbered 16-tree level (remember that each on-disk
531 * fanout level corresponds to _two_ 16-tree levels), peek at all 16
532 * entries at that tree level. If all of them are either int_nodes or
533 * subtree entries, then there are likely plenty of notes below this
534 * level, so we return an incremented fanout.
535 */
536 unsigned int i;
537 if ((n % 2) || (n > 2 * fanout))
538 return fanout;
539 for (i = 0; i < 16; i++) {
540 switch (GET_PTR_TYPE(tree->a[i])) {
541 case PTR_TYPE_SUBTREE:
542 case PTR_TYPE_INTERNAL:
543 continue;
544 default:
545 return fanout;
546 }
547 }
548 return fanout + 1;
549}
550
551/* hex SHA1 + 19 * '/' + NUL */
552#define FANOUT_PATH_MAX GIT_SHA1_HEXSZ + FANOUT_PATH_SEPARATORS + 1
553
554static void construct_path_with_fanout(const unsigned char *sha1,
555 unsigned char fanout, char *path)
556{
557 unsigned int i = 0, j = 0;
558 const char *hex_sha1 = sha1_to_hex(sha1);
559 assert(fanout < GIT_SHA1_RAWSZ);
560 while (fanout) {
561 path[i++] = hex_sha1[j++];
562 path[i++] = hex_sha1[j++];
563 path[i++] = '/';
564 fanout--;
565 }
566 xsnprintf(path + i, FANOUT_PATH_MAX - i, "%s", hex_sha1 + j);
567}
568
569static int for_each_note_helper(struct notes_tree *t, struct int_node *tree,
570 unsigned char n, unsigned char fanout, int flags,
571 each_note_fn fn, void *cb_data)
572{
573 unsigned int i;
574 void *p;
575 int ret = 0;
576 struct leaf_node *l;
577 static char path[FANOUT_PATH_MAX];
578
579 fanout = determine_fanout(tree, n, fanout);
580 for (i = 0; i < 16; i++) {
581redo:
582 p = tree->a[i];
583 switch (GET_PTR_TYPE(p)) {
584 case PTR_TYPE_INTERNAL:
585 /* recurse into int_node */
586 ret = for_each_note_helper(t, CLR_PTR_TYPE(p), n + 1,
587 fanout, flags, fn, cb_data);
588 break;
589 case PTR_TYPE_SUBTREE:
590 l = (struct leaf_node *) CLR_PTR_TYPE(p);
591 /*
592 * Subtree entries in the note tree represent parts of
593 * the note tree that have not yet been explored. There
594 * is a direct relationship between subtree entries at
595 * level 'n' in the tree, and the 'fanout' variable:
596 * Subtree entries at level 'n <= 2 * fanout' should be
597 * preserved, since they correspond exactly to a fanout
598 * directory in the on-disk structure. However, subtree
599 * entries at level 'n > 2 * fanout' should NOT be
600 * preserved, but rather consolidated into the above
601 * notes tree level. We achieve this by unconditionally
602 * unpacking subtree entries that exist below the
603 * threshold level at 'n = 2 * fanout'.
604 */
605 if (n <= 2 * fanout &&
606 flags & FOR_EACH_NOTE_YIELD_SUBTREES) {
607 /* invoke callback with subtree */
608 unsigned int path_len =
609 l->key_oid.hash[KEY_INDEX] * 2 + fanout;
610 assert(path_len < FANOUT_PATH_MAX - 1);
611 construct_path_with_fanout(l->key_oid.hash,
612 fanout,
613 path);
614 /* Create trailing slash, if needed */
615 if (path[path_len - 1] != '/')
616 path[path_len++] = '/';
617 path[path_len] = '\0';
618 ret = fn(&l->key_oid, &l->val_oid,
619 path,
620 cb_data);
621 }
622 if (n > fanout * 2 ||
623 !(flags & FOR_EACH_NOTE_DONT_UNPACK_SUBTREES)) {
624 /* unpack subtree and resume traversal */
625 tree->a[i] = NULL;
626 load_subtree(t, l, tree, n);
627 free(l);
628 goto redo;
629 }
630 break;
631 case PTR_TYPE_NOTE:
632 l = (struct leaf_node *) CLR_PTR_TYPE(p);
633 construct_path_with_fanout(l->key_oid.hash, fanout,
634 path);
635 ret = fn(&l->key_oid, &l->val_oid, path,
636 cb_data);
637 break;
638 }
639 if (ret)
640 return ret;
641 }
642 return 0;
643}
644
645struct tree_write_stack {
646 struct tree_write_stack *next;
647 struct strbuf buf;
648 char path[2]; /* path to subtree in next, if any */
649};
650
651static inline int matches_tree_write_stack(struct tree_write_stack *tws,
652 const char *full_path)
653{
654 return full_path[0] == tws->path[0] &&
655 full_path[1] == tws->path[1] &&
656 full_path[2] == '/';
657}
658
659static void write_tree_entry(struct strbuf *buf, unsigned int mode,
660 const char *path, unsigned int path_len, const
661 unsigned char *sha1)
662{
663 strbuf_addf(buf, "%o %.*s%c", mode, path_len, path, '\0');
664 strbuf_add(buf, sha1, GIT_SHA1_RAWSZ);
665}
666
667static void tree_write_stack_init_subtree(struct tree_write_stack *tws,
668 const char *path)
669{
670 struct tree_write_stack *n;
671 assert(!tws->next);
672 assert(tws->path[0] == '\0' && tws->path[1] == '\0');
673 n = (struct tree_write_stack *)
674 xmalloc(sizeof(struct tree_write_stack));
675 n->next = NULL;
676 strbuf_init(&n->buf, 256 * (32 + GIT_SHA1_HEXSZ)); /* assume 256 entries per tree */
677 n->path[0] = n->path[1] = '\0';
678 tws->next = n;
679 tws->path[0] = path[0];
680 tws->path[1] = path[1];
681}
682
683static int tree_write_stack_finish_subtree(struct tree_write_stack *tws)
684{
685 int ret;
686 struct tree_write_stack *n = tws->next;
687 struct object_id s;
688 if (n) {
689 ret = tree_write_stack_finish_subtree(n);
690 if (ret)
691 return ret;
692 ret = write_sha1_file(n->buf.buf, n->buf.len, tree_type, s.hash);
693 if (ret)
694 return ret;
695 strbuf_release(&n->buf);
696 free(n);
697 tws->next = NULL;
698 write_tree_entry(&tws->buf, 040000, tws->path, 2, s.hash);
699 tws->path[0] = tws->path[1] = '\0';
700 }
701 return 0;
702}
703
704static int write_each_note_helper(struct tree_write_stack *tws,
705 const char *path, unsigned int mode,
706 const struct object_id *oid)
707{
708 size_t path_len = strlen(path);
709 unsigned int n = 0;
710 int ret;
711
712 /* Determine common part of tree write stack */
713 while (tws && 3 * n < path_len &&
714 matches_tree_write_stack(tws, path + 3 * n)) {
715 n++;
716 tws = tws->next;
717 }
718
719 /* tws point to last matching tree_write_stack entry */
720 ret = tree_write_stack_finish_subtree(tws);
721 if (ret)
722 return ret;
723
724 /* Start subtrees needed to satisfy path */
725 while (3 * n + 2 < path_len && path[3 * n + 2] == '/') {
726 tree_write_stack_init_subtree(tws, path + 3 * n);
727 n++;
728 tws = tws->next;
729 }
730
731 /* There should be no more directory components in the given path */
732 assert(memchr(path + 3 * n, '/', path_len - (3 * n)) == NULL);
733
734 /* Finally add given entry to the current tree object */
735 write_tree_entry(&tws->buf, mode, path + 3 * n, path_len - (3 * n),
736 oid->hash);
737
738 return 0;
739}
740
741struct write_each_note_data {
742 struct tree_write_stack *root;
743 struct non_note *next_non_note;
744};
745
746static int write_each_non_note_until(const char *note_path,
747 struct write_each_note_data *d)
748{
749 struct non_note *n = d->next_non_note;
750 int cmp = 0, ret;
751 while (n && (!note_path || (cmp = strcmp(n->path, note_path)) <= 0)) {
752 if (note_path && cmp == 0)
753 ; /* do nothing, prefer note to non-note */
754 else {
755 ret = write_each_note_helper(d->root, n->path, n->mode,
756 &n->oid);
757 if (ret)
758 return ret;
759 }
760 n = n->next;
761 }
762 d->next_non_note = n;
763 return 0;
764}
765
766static int write_each_note(const struct object_id *object_oid,
767 const struct object_id *note_oid, char *note_path,
768 void *cb_data)
769{
770 struct write_each_note_data *d =
771 (struct write_each_note_data *) cb_data;
772 size_t note_path_len = strlen(note_path);
773 unsigned int mode = 0100644;
774
775 if (note_path[note_path_len - 1] == '/') {
776 /* subtree entry */
777 note_path_len--;
778 note_path[note_path_len] = '\0';
779 mode = 040000;
780 }
781 assert(note_path_len <= GIT_SHA1_HEXSZ + FANOUT_PATH_SEPARATORS);
782
783 /* Weave non-note entries into note entries */
784 return write_each_non_note_until(note_path, d) ||
785 write_each_note_helper(d->root, note_path, mode, note_oid);
786}
787
788struct note_delete_list {
789 struct note_delete_list *next;
790 const unsigned char *sha1;
791};
792
793static int prune_notes_helper(const struct object_id *object_oid,
794 const struct object_id *note_oid, char *note_path,
795 void *cb_data)
796{
797 struct note_delete_list **l = (struct note_delete_list **) cb_data;
798 struct note_delete_list *n;
799
800 if (has_object_file(object_oid))
801 return 0; /* nothing to do for this note */
802
803 /* failed to find object => prune this note */
804 n = (struct note_delete_list *) xmalloc(sizeof(*n));
805 n->next = *l;
806 n->sha1 = object_oid->hash;
807 *l = n;
808 return 0;
809}
810
811int combine_notes_concatenate(unsigned char *cur_sha1,
812 const unsigned char *new_sha1)
813{
814 char *cur_msg = NULL, *new_msg = NULL, *buf;
815 unsigned long cur_len, new_len, buf_len;
816 enum object_type cur_type, new_type;
817 int ret;
818
819 /* read in both note blob objects */
820 if (!is_null_sha1(new_sha1))
821 new_msg = read_sha1_file(new_sha1, &new_type, &new_len);
822 if (!new_msg || !new_len || new_type != OBJ_BLOB) {
823 free(new_msg);
824 return 0;
825 }
826 if (!is_null_sha1(cur_sha1))
827 cur_msg = read_sha1_file(cur_sha1, &cur_type, &cur_len);
828 if (!cur_msg || !cur_len || cur_type != OBJ_BLOB) {
829 free(cur_msg);
830 free(new_msg);
831 hashcpy(cur_sha1, new_sha1);
832 return 0;
833 }
834
835 /* we will separate the notes by two newlines anyway */
836 if (cur_msg[cur_len - 1] == '\n')
837 cur_len--;
838
839 /* concatenate cur_msg and new_msg into buf */
840 buf_len = cur_len + 2 + new_len;
841 buf = (char *) xmalloc(buf_len);
842 memcpy(buf, cur_msg, cur_len);
843 buf[cur_len] = '\n';
844 buf[cur_len + 1] = '\n';
845 memcpy(buf + cur_len + 2, new_msg, new_len);
846 free(cur_msg);
847 free(new_msg);
848
849 /* create a new blob object from buf */
850 ret = write_sha1_file(buf, buf_len, blob_type, cur_sha1);
851 free(buf);
852 return ret;
853}
854
855int combine_notes_overwrite(unsigned char *cur_sha1,
856 const unsigned char *new_sha1)
857{
858 hashcpy(cur_sha1, new_sha1);
859 return 0;
860}
861
862int combine_notes_ignore(unsigned char *cur_sha1,
863 const unsigned char *new_sha1)
864{
865 return 0;
866}
867
868/*
869 * Add the lines from the named object to list, with trailing
870 * newlines removed.
871 */
872static int string_list_add_note_lines(struct string_list *list,
873 const unsigned char *sha1)
874{
875 char *data;
876 unsigned long len;
877 enum object_type t;
878
879 if (is_null_sha1(sha1))
880 return 0;
881
882 /* read_sha1_file NUL-terminates */
883 data = read_sha1_file(sha1, &t, &len);
884 if (t != OBJ_BLOB || !data || !len) {
885 free(data);
886 return t != OBJ_BLOB || !data;
887 }
888
889 /*
890 * If the last line of the file is EOL-terminated, this will
891 * add an empty string to the list. But it will be removed
892 * later, along with any empty strings that came from empty
893 * lines within the file.
894 */
895 string_list_split(list, data, '\n', -1);
896 free(data);
897 return 0;
898}
899
900static int string_list_join_lines_helper(struct string_list_item *item,
901 void *cb_data)
902{
903 struct strbuf *buf = cb_data;
904 strbuf_addstr(buf, item->string);
905 strbuf_addch(buf, '\n');
906 return 0;
907}
908
909int combine_notes_cat_sort_uniq(unsigned char *cur_sha1,
910 const unsigned char *new_sha1)
911{
912 struct string_list sort_uniq_list = STRING_LIST_INIT_DUP;
913 struct strbuf buf = STRBUF_INIT;
914 int ret = 1;
915
916 /* read both note blob objects into unique_lines */
917 if (string_list_add_note_lines(&sort_uniq_list, cur_sha1))
918 goto out;
919 if (string_list_add_note_lines(&sort_uniq_list, new_sha1))
920 goto out;
921 string_list_remove_empty_items(&sort_uniq_list, 0);
922 string_list_sort(&sort_uniq_list);
923 string_list_remove_duplicates(&sort_uniq_list, 0);
924
925 /* create a new blob object from sort_uniq_list */
926 if (for_each_string_list(&sort_uniq_list,
927 string_list_join_lines_helper, &buf))
928 goto out;
929
930 ret = write_sha1_file(buf.buf, buf.len, blob_type, cur_sha1);
931
932out:
933 strbuf_release(&buf);
934 string_list_clear(&sort_uniq_list, 0);
935 return ret;
936}
937
938static int string_list_add_one_ref(const char *refname, const struct object_id *oid,
939 int flag, void *cb)
940{
941 struct string_list *refs = cb;
942 if (!unsorted_string_list_has_string(refs, refname))
943 string_list_append(refs, refname);
944 return 0;
945}
946
947/*
948 * The list argument must have strdup_strings set on it.
949 */
950void string_list_add_refs_by_glob(struct string_list *list, const char *glob)
951{
952 assert(list->strdup_strings);
953 if (has_glob_specials(glob)) {
954 for_each_glob_ref(string_list_add_one_ref, glob, list);
955 } else {
956 struct object_id oid;
957 if (get_oid(glob, &oid))
958 warning("notes ref %s is invalid", glob);
959 if (!unsorted_string_list_has_string(list, glob))
960 string_list_append(list, glob);
961 }
962}
963
964void string_list_add_refs_from_colon_sep(struct string_list *list,
965 const char *globs)
966{
967 struct string_list split = STRING_LIST_INIT_NODUP;
968 char *globs_copy = xstrdup(globs);
969 int i;
970
971 string_list_split_in_place(&split, globs_copy, ':', -1);
972 string_list_remove_empty_items(&split, 0);
973
974 for (i = 0; i < split.nr; i++)
975 string_list_add_refs_by_glob(list, split.items[i].string);
976
977 string_list_clear(&split, 0);
978 free(globs_copy);
979}
980
981static int notes_display_config(const char *k, const char *v, void *cb)
982{
983 int *load_refs = cb;
984
985 if (*load_refs && !strcmp(k, "notes.displayref")) {
986 if (!v)
987 config_error_nonbool(k);
988 string_list_add_refs_by_glob(&display_notes_refs, v);
989 }
990
991 return 0;
992}
993
994const char *default_notes_ref(void)
995{
996 const char *notes_ref = NULL;
997 if (!notes_ref)
998 notes_ref = getenv(GIT_NOTES_REF_ENVIRONMENT);
999 if (!notes_ref)
1000 notes_ref = notes_ref_name; /* value of core.notesRef config */
1001 if (!notes_ref)
1002 notes_ref = GIT_NOTES_DEFAULT_REF;
1003 return notes_ref;
1004}
1005
1006void init_notes(struct notes_tree *t, const char *notes_ref,
1007 combine_notes_fn combine_notes, int flags)
1008{
1009 struct object_id oid, object_oid;
1010 unsigned mode;
1011 struct leaf_node root_tree;
1012
1013 if (!t)
1014 t = &default_notes_tree;
1015 assert(!t->initialized);
1016
1017 if (!notes_ref)
1018 notes_ref = default_notes_ref();
1019
1020 if (!combine_notes)
1021 combine_notes = combine_notes_concatenate;
1022
1023 t->root = (struct int_node *) xcalloc(1, sizeof(struct int_node));
1024 t->first_non_note = NULL;
1025 t->prev_non_note = NULL;
1026 t->ref = xstrdup_or_null(notes_ref);
1027 t->update_ref = (flags & NOTES_INIT_WRITABLE) ? t->ref : NULL;
1028 t->combine_notes = combine_notes;
1029 t->initialized = 1;
1030 t->dirty = 0;
1031
1032 if (flags & NOTES_INIT_EMPTY || !notes_ref ||
1033 get_sha1_treeish(notes_ref, object_oid.hash))
1034 return;
1035 if (flags & NOTES_INIT_WRITABLE && read_ref(notes_ref, object_oid.hash))
1036 die("Cannot use notes ref %s", notes_ref);
1037 if (get_tree_entry(object_oid.hash, "", oid.hash, &mode))
1038 die("Failed to read notes tree referenced by %s (%s)",
1039 notes_ref, oid_to_hex(&object_oid));
1040
1041 oidclr(&root_tree.key_oid);
1042 oidcpy(&root_tree.val_oid, &oid);
1043 load_subtree(t, &root_tree, t->root, 0);
1044}
1045
1046struct notes_tree **load_notes_trees(struct string_list *refs, int flags)
1047{
1048 struct string_list_item *item;
1049 int counter = 0;
1050 struct notes_tree **trees;
1051 ALLOC_ARRAY(trees, refs->nr + 1);
1052 for_each_string_list_item(item, refs) {
1053 struct notes_tree *t = xcalloc(1, sizeof(struct notes_tree));
1054 init_notes(t, item->string, combine_notes_ignore, flags);
1055 trees[counter++] = t;
1056 }
1057 trees[counter] = NULL;
1058 return trees;
1059}
1060
1061void init_display_notes(struct display_notes_opt *opt)
1062{
1063 char *display_ref_env;
1064 int load_config_refs = 0;
1065 display_notes_refs.strdup_strings = 1;
1066
1067 assert(!display_notes_trees);
1068
1069 if (!opt || opt->use_default_notes > 0 ||
1070 (opt->use_default_notes == -1 && !opt->extra_notes_refs.nr)) {
1071 string_list_append(&display_notes_refs, default_notes_ref());
1072 display_ref_env = getenv(GIT_NOTES_DISPLAY_REF_ENVIRONMENT);
1073 if (display_ref_env) {
1074 string_list_add_refs_from_colon_sep(&display_notes_refs,
1075 display_ref_env);
1076 load_config_refs = 0;
1077 } else
1078 load_config_refs = 1;
1079 }
1080
1081 git_config(notes_display_config, &load_config_refs);
1082
1083 if (opt) {
1084 struct string_list_item *item;
1085 for_each_string_list_item(item, &opt->extra_notes_refs)
1086 string_list_add_refs_by_glob(&display_notes_refs,
1087 item->string);
1088 }
1089
1090 display_notes_trees = load_notes_trees(&display_notes_refs, 0);
1091 string_list_clear(&display_notes_refs, 0);
1092}
1093
1094int add_note(struct notes_tree *t, const struct object_id *object_oid,
1095 const struct object_id *note_oid, combine_notes_fn combine_notes)
1096{
1097 struct leaf_node *l;
1098
1099 if (!t)
1100 t = &default_notes_tree;
1101 assert(t->initialized);
1102 t->dirty = 1;
1103 if (!combine_notes)
1104 combine_notes = t->combine_notes;
1105 l = (struct leaf_node *) xmalloc(sizeof(struct leaf_node));
1106 oidcpy(&l->key_oid, object_oid);
1107 oidcpy(&l->val_oid, note_oid);
1108 return note_tree_insert(t, t->root, 0, l, PTR_TYPE_NOTE, combine_notes);
1109}
1110
1111int remove_note(struct notes_tree *t, const unsigned char *object_sha1)
1112{
1113 struct leaf_node l;
1114
1115 if (!t)
1116 t = &default_notes_tree;
1117 assert(t->initialized);
1118 hashcpy(l.key_oid.hash, object_sha1);
1119 oidclr(&l.val_oid);
1120 note_tree_remove(t, t->root, 0, &l);
1121 if (is_null_oid(&l.val_oid)) /* no note was removed */
1122 return 1;
1123 t->dirty = 1;
1124 return 0;
1125}
1126
1127const struct object_id *get_note(struct notes_tree *t,
1128 const struct object_id *oid)
1129{
1130 struct leaf_node *found;
1131
1132 if (!t)
1133 t = &default_notes_tree;
1134 assert(t->initialized);
1135 found = note_tree_find(t, t->root, 0, oid->hash);
1136 return found ? &found->val_oid : NULL;
1137}
1138
1139int for_each_note(struct notes_tree *t, int flags, each_note_fn fn,
1140 void *cb_data)
1141{
1142 if (!t)
1143 t = &default_notes_tree;
1144 assert(t->initialized);
1145 return for_each_note_helper(t, t->root, 0, 0, flags, fn, cb_data);
1146}
1147
1148int write_notes_tree(struct notes_tree *t, unsigned char *result)
1149{
1150 struct tree_write_stack root;
1151 struct write_each_note_data cb_data;
1152 int ret;
1153
1154 if (!t)
1155 t = &default_notes_tree;
1156 assert(t->initialized);
1157
1158 /* Prepare for traversal of current notes tree */
1159 root.next = NULL; /* last forward entry in list is grounded */
1160 strbuf_init(&root.buf, 256 * (32 + GIT_SHA1_HEXSZ)); /* assume 256 entries */
1161 root.path[0] = root.path[1] = '\0';
1162 cb_data.root = &root;
1163 cb_data.next_non_note = t->first_non_note;
1164
1165 /* Write tree objects representing current notes tree */
1166 ret = for_each_note(t, FOR_EACH_NOTE_DONT_UNPACK_SUBTREES |
1167 FOR_EACH_NOTE_YIELD_SUBTREES,
1168 write_each_note, &cb_data) ||
1169 write_each_non_note_until(NULL, &cb_data) ||
1170 tree_write_stack_finish_subtree(&root) ||
1171 write_sha1_file(root.buf.buf, root.buf.len, tree_type, result);
1172 strbuf_release(&root.buf);
1173 return ret;
1174}
1175
1176void prune_notes(struct notes_tree *t, int flags)
1177{
1178 struct note_delete_list *l = NULL;
1179
1180 if (!t)
1181 t = &default_notes_tree;
1182 assert(t->initialized);
1183
1184 for_each_note(t, 0, prune_notes_helper, &l);
1185
1186 while (l) {
1187 if (flags & NOTES_PRUNE_VERBOSE)
1188 printf("%s\n", sha1_to_hex(l->sha1));
1189 if (!(flags & NOTES_PRUNE_DRYRUN))
1190 remove_note(t, l->sha1);
1191 l = l->next;
1192 }
1193}
1194
1195void free_notes(struct notes_tree *t)
1196{
1197 if (!t)
1198 t = &default_notes_tree;
1199 if (t->root)
1200 note_tree_free(t->root);
1201 free(t->root);
1202 while (t->first_non_note) {
1203 t->prev_non_note = t->first_non_note->next;
1204 free(t->first_non_note->path);
1205 free(t->first_non_note);
1206 t->first_non_note = t->prev_non_note;
1207 }
1208 free(t->ref);
1209 memset(t, 0, sizeof(struct notes_tree));
1210}
1211
1212/*
1213 * Fill the given strbuf with the notes associated with the given object.
1214 *
1215 * If the given notes_tree structure is not initialized, it will be auto-
1216 * initialized to the default value (see documentation for init_notes() above).
1217 * If the given notes_tree is NULL, the internal/default notes_tree will be
1218 * used instead.
1219 *
1220 * (raw != 0) gives the %N userformat; otherwise, the note message is given
1221 * for human consumption.
1222 */
1223static void format_note(struct notes_tree *t, const struct object_id *object_oid,
1224 struct strbuf *sb, const char *output_encoding, int raw)
1225{
1226 static const char utf8[] = "utf-8";
1227 const struct object_id *oid;
1228 char *msg, *msg_p;
1229 unsigned long linelen, msglen;
1230 enum object_type type;
1231
1232 if (!t)
1233 t = &default_notes_tree;
1234 if (!t->initialized)
1235 init_notes(t, NULL, NULL, 0);
1236
1237 oid = get_note(t, object_oid);
1238 if (!oid)
1239 return;
1240
1241 if (!(msg = read_sha1_file(oid->hash, &type, &msglen)) || type != OBJ_BLOB) {
1242 free(msg);
1243 return;
1244 }
1245
1246 if (output_encoding && *output_encoding &&
1247 !is_encoding_utf8(output_encoding)) {
1248 char *reencoded = reencode_string(msg, output_encoding, utf8);
1249 if (reencoded) {
1250 free(msg);
1251 msg = reencoded;
1252 msglen = strlen(msg);
1253 }
1254 }
1255
1256 /* we will end the annotation by a newline anyway */
1257 if (msglen && msg[msglen - 1] == '\n')
1258 msglen--;
1259
1260 if (!raw) {
1261 const char *ref = t->ref;
1262 if (!ref || !strcmp(ref, GIT_NOTES_DEFAULT_REF)) {
1263 strbuf_addstr(sb, "\nNotes:\n");
1264 } else {
1265 if (starts_with(ref, "refs/"))
1266 ref += 5;
1267 if (starts_with(ref, "notes/"))
1268 ref += 6;
1269 strbuf_addf(sb, "\nNotes (%s):\n", ref);
1270 }
1271 }
1272
1273 for (msg_p = msg; msg_p < msg + msglen; msg_p += linelen + 1) {
1274 linelen = strchrnul(msg_p, '\n') - msg_p;
1275
1276 if (!raw)
1277 strbuf_addstr(sb, " ");
1278 strbuf_add(sb, msg_p, linelen);
1279 strbuf_addch(sb, '\n');
1280 }
1281
1282 free(msg);
1283}
1284
1285void format_display_notes(const struct object_id *object_oid,
1286 struct strbuf *sb, const char *output_encoding, int raw)
1287{
1288 int i;
1289 assert(display_notes_trees);
1290 for (i = 0; display_notes_trees[i]; i++)
1291 format_note(display_notes_trees[i], object_oid, sb,
1292 output_encoding, raw);
1293}
1294
1295int copy_note(struct notes_tree *t,
1296 const struct object_id *from_obj, const struct object_id *to_obj,
1297 int force, combine_notes_fn combine_notes)
1298{
1299 const struct object_id *note = get_note(t, from_obj);
1300 const struct object_id *existing_note = get_note(t, to_obj);
1301
1302 if (!force && existing_note)
1303 return 1;
1304
1305 if (note)
1306 return add_note(t, to_obj, note, combine_notes);
1307 else if (existing_note)
1308 return add_note(t, to_obj, &null_oid, combine_notes);
1309
1310 return 0;
1311}
1312
1313void expand_notes_ref(struct strbuf *sb)
1314{
1315 if (starts_with(sb->buf, "refs/notes/"))
1316 return; /* we're happy */
1317 else if (starts_with(sb->buf, "notes/"))
1318 strbuf_insert(sb, 0, "refs/", 5);
1319 else
1320 strbuf_insert(sb, 0, "refs/notes/", 11);
1321}
1322
1323void expand_loose_notes_ref(struct strbuf *sb)
1324{
1325 struct object_id object;
1326
1327 if (get_oid(sb->buf, &object)) {
1328 /* fallback to expand_notes_ref */
1329 expand_notes_ref(sb);
1330 }
1331}