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