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