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