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