notes.con commit Notes API: write_notes_tree(): Store the notes tree in the database (61a7cca)
   1#include "cache.h"
   2#include "notes.h"
   3#include "tree.h"
   4#include "utf8.h"
   5#include "strbuf.h"
   6#include "tree-walk.h"
   7
   8/*
   9 * Use a non-balancing simple 16-tree structure with struct int_node as
  10 * internal nodes, and struct leaf_node as leaf nodes. Each int_node has a
  11 * 16-array of pointers to its children.
  12 * The bottom 2 bits of each pointer is used to identify the pointer type
  13 * - ptr & 3 == 0 - NULL pointer, assert(ptr == NULL)
  14 * - ptr & 3 == 1 - pointer to next internal node - cast to struct int_node *
  15 * - ptr & 3 == 2 - pointer to note entry - cast to struct leaf_node *
  16 * - ptr & 3 == 3 - pointer to subtree entry - cast to struct leaf_node *
  17 *
  18 * The root node is a statically allocated struct int_node.
  19 */
  20struct int_node {
  21        void *a[16];
  22};
  23
  24/*
  25 * Leaf nodes come in two variants, note entries and subtree entries,
  26 * distinguished by the LSb of the leaf node pointer (see above).
  27 * As a note entry, the key is the SHA1 of the referenced object, and the
  28 * value is the SHA1 of the note object.
  29 * As a subtree entry, the key is the prefix SHA1 (w/trailing NULs) of the
  30 * referenced object, using the last byte of the key to store the length of
  31 * the prefix. The value is the SHA1 of the tree object containing the notes
  32 * subtree.
  33 */
  34struct leaf_node {
  35        unsigned char key_sha1[20];
  36        unsigned char val_sha1[20];
  37};
  38
  39#define PTR_TYPE_NULL     0
  40#define PTR_TYPE_INTERNAL 1
  41#define PTR_TYPE_NOTE     2
  42#define PTR_TYPE_SUBTREE  3
  43
  44#define GET_PTR_TYPE(ptr)       ((uintptr_t) (ptr) & 3)
  45#define CLR_PTR_TYPE(ptr)       ((void *) ((uintptr_t) (ptr) & ~3))
  46#define SET_PTR_TYPE(ptr, type) ((void *) ((uintptr_t) (ptr) | (type)))
  47
  48#define GET_NIBBLE(n, sha1) (((sha1[(n) >> 1]) >> ((~(n) & 0x01) << 2)) & 0x0f)
  49
  50#define SUBTREE_SHA1_PREFIXCMP(key_sha1, subtree_sha1) \
  51        (memcmp(key_sha1, subtree_sha1, subtree_sha1[19]))
  52
  53static struct int_node root_node;
  54
  55static int initialized;
  56
  57static void load_subtree(struct leaf_node *subtree, struct int_node *node,
  58                unsigned int n);
  59
  60/*
  61 * Search the tree until the appropriate location for the given key is found:
  62 * 1. Start at the root node, with n = 0
  63 * 2. If a[0] at the current level is a matching subtree entry, unpack that
  64 *    subtree entry and remove it; restart search at the current level.
  65 * 3. Use the nth nibble of the key as an index into a:
  66 *    - If a[n] is an int_node, recurse from #2 into that node and increment n
  67 *    - If a matching subtree entry, unpack that subtree entry (and remove it);
  68 *      restart search at the current level.
  69 *    - Otherwise, we have found one of the following:
  70 *      - a subtree entry which does not match the key
  71 *      - a note entry which may or may not match the key
  72 *      - an unused leaf node (NULL)
  73 *      In any case, set *tree and *n, and return pointer to the tree location.
  74 */
  75static void **note_tree_search(struct int_node **tree,
  76                unsigned char *n, const unsigned char *key_sha1)
  77{
  78        struct leaf_node *l;
  79        unsigned char i;
  80        void *p = (*tree)->a[0];
  81
  82        if (GET_PTR_TYPE(p) == PTR_TYPE_SUBTREE) {
  83                l = (struct leaf_node *) CLR_PTR_TYPE(p);
  84                if (!SUBTREE_SHA1_PREFIXCMP(key_sha1, l->key_sha1)) {
  85                        /* unpack tree and resume search */
  86                        (*tree)->a[0] = NULL;
  87                        load_subtree(l, *tree, *n);
  88                        free(l);
  89                        return note_tree_search(tree, n, key_sha1);
  90                }
  91        }
  92
  93        i = GET_NIBBLE(*n, key_sha1);
  94        p = (*tree)->a[i];
  95        switch (GET_PTR_TYPE(p)) {
  96        case PTR_TYPE_INTERNAL:
  97                *tree = CLR_PTR_TYPE(p);
  98                (*n)++;
  99                return note_tree_search(tree, n, key_sha1);
 100        case PTR_TYPE_SUBTREE:
 101                l = (struct leaf_node *) CLR_PTR_TYPE(p);
 102                if (!SUBTREE_SHA1_PREFIXCMP(key_sha1, l->key_sha1)) {
 103                        /* unpack tree and resume search */
 104                        (*tree)->a[i] = NULL;
 105                        load_subtree(l, *tree, *n);
 106                        free(l);
 107                        return note_tree_search(tree, n, key_sha1);
 108                }
 109                /* fall through */
 110        default:
 111                return &((*tree)->a[i]);
 112        }
 113}
 114
 115/*
 116 * To find a leaf_node:
 117 * Search to the tree location appropriate for the given key:
 118 * If a note entry with matching key, return the note entry, else return NULL.
 119 */
 120static struct leaf_node *note_tree_find(struct int_node *tree, unsigned char n,
 121                const unsigned char *key_sha1)
 122{
 123        void **p = note_tree_search(&tree, &n, key_sha1);
 124        if (GET_PTR_TYPE(*p) == PTR_TYPE_NOTE) {
 125                struct leaf_node *l = (struct leaf_node *) CLR_PTR_TYPE(*p);
 126                if (!hashcmp(key_sha1, l->key_sha1))
 127                        return l;
 128        }
 129        return NULL;
 130}
 131
 132/* Create a new blob object by concatenating the two given blob objects */
 133static int concatenate_notes(unsigned char *cur_sha1,
 134                const unsigned char *new_sha1)
 135{
 136        char *cur_msg, *new_msg, *buf;
 137        unsigned long cur_len, new_len, buf_len;
 138        enum object_type cur_type, new_type;
 139        int ret;
 140
 141        /* read in both note blob objects */
 142        new_msg = read_sha1_file(new_sha1, &new_type, &new_len);
 143        if (!new_msg || !new_len || new_type != OBJ_BLOB) {
 144                free(new_msg);
 145                return 0;
 146        }
 147        cur_msg = read_sha1_file(cur_sha1, &cur_type, &cur_len);
 148        if (!cur_msg || !cur_len || cur_type != OBJ_BLOB) {
 149                free(cur_msg);
 150                free(new_msg);
 151                hashcpy(cur_sha1, new_sha1);
 152                return 0;
 153        }
 154
 155        /* we will separate the notes by a newline anyway */
 156        if (cur_msg[cur_len - 1] == '\n')
 157                cur_len--;
 158
 159        /* concatenate cur_msg and new_msg into buf */
 160        buf_len = cur_len + 1 + new_len;
 161        buf = (char *) xmalloc(buf_len);
 162        memcpy(buf, cur_msg, cur_len);
 163        buf[cur_len] = '\n';
 164        memcpy(buf + cur_len + 1, new_msg, new_len);
 165
 166        free(cur_msg);
 167        free(new_msg);
 168
 169        /* create a new blob object from buf */
 170        ret = write_sha1_file(buf, buf_len, "blob", cur_sha1);
 171        free(buf);
 172        return ret;
 173}
 174
 175/*
 176 * To insert a leaf_node:
 177 * Search to the tree location appropriate for the given leaf_node's key:
 178 * - If location is unused (NULL), store the tweaked pointer directly there
 179 * - If location holds a note entry that matches the note-to-be-inserted, then
 180 *   concatenate the two notes.
 181 * - If location holds a note entry that matches the subtree-to-be-inserted,
 182 *   then unpack the subtree-to-be-inserted into the location.
 183 * - If location holds a matching subtree entry, unpack the subtree at that
 184 *   location, and restart the insert operation from that level.
 185 * - Else, create a new int_node, holding both the node-at-location and the
 186 *   node-to-be-inserted, and store the new int_node into the location.
 187 */
 188static void note_tree_insert(struct int_node *tree, unsigned char n,
 189                struct leaf_node *entry, unsigned char type)
 190{
 191        struct int_node *new_node;
 192        struct leaf_node *l;
 193        void **p = note_tree_search(&tree, &n, entry->key_sha1);
 194
 195        assert(GET_PTR_TYPE(entry) == 0); /* no type bits set */
 196        l = (struct leaf_node *) CLR_PTR_TYPE(*p);
 197        switch (GET_PTR_TYPE(*p)) {
 198        case PTR_TYPE_NULL:
 199                assert(!*p);
 200                *p = SET_PTR_TYPE(entry, type);
 201                return;
 202        case PTR_TYPE_NOTE:
 203                switch (type) {
 204                case PTR_TYPE_NOTE:
 205                        if (!hashcmp(l->key_sha1, entry->key_sha1)) {
 206                                /* skip concatenation if l == entry */
 207                                if (!hashcmp(l->val_sha1, entry->val_sha1))
 208                                        return;
 209
 210                                if (concatenate_notes(l->val_sha1,
 211                                                entry->val_sha1))
 212                                        die("failed to concatenate note %s "
 213                                            "into note %s for object %s",
 214                                            sha1_to_hex(entry->val_sha1),
 215                                            sha1_to_hex(l->val_sha1),
 216                                            sha1_to_hex(l->key_sha1));
 217                                free(entry);
 218                                return;
 219                        }
 220                        break;
 221                case PTR_TYPE_SUBTREE:
 222                        if (!SUBTREE_SHA1_PREFIXCMP(l->key_sha1,
 223                                                    entry->key_sha1)) {
 224                                /* unpack 'entry' */
 225                                load_subtree(entry, tree, n);
 226                                free(entry);
 227                                return;
 228                        }
 229                        break;
 230                }
 231                break;
 232        case PTR_TYPE_SUBTREE:
 233                if (!SUBTREE_SHA1_PREFIXCMP(entry->key_sha1, l->key_sha1)) {
 234                        /* unpack 'l' and restart insert */
 235                        *p = NULL;
 236                        load_subtree(l, tree, n);
 237                        free(l);
 238                        note_tree_insert(tree, n, entry, type);
 239                        return;
 240                }
 241                break;
 242        }
 243
 244        /* non-matching leaf_node */
 245        assert(GET_PTR_TYPE(*p) == PTR_TYPE_NOTE ||
 246               GET_PTR_TYPE(*p) == PTR_TYPE_SUBTREE);
 247        new_node = (struct int_node *) xcalloc(sizeof(struct int_node), 1);
 248        note_tree_insert(new_node, n + 1, l, GET_PTR_TYPE(*p));
 249        *p = SET_PTR_TYPE(new_node, PTR_TYPE_INTERNAL);
 250        note_tree_insert(new_node, n + 1, entry, type);
 251}
 252
 253/*
 254 * How to consolidate an int_node:
 255 * If there are > 1 non-NULL entries, give up and return non-zero.
 256 * Otherwise replace the int_node at the given index in the given parent node
 257 * with the only entry (or a NULL entry if no entries) from the given tree,
 258 * and return 0.
 259 */
 260static int note_tree_consolidate(struct int_node *tree,
 261        struct int_node *parent, unsigned char index)
 262{
 263        unsigned int i;
 264        void *p = NULL;
 265
 266        assert(tree && parent);
 267        assert(CLR_PTR_TYPE(parent->a[index]) == tree);
 268
 269        for (i = 0; i < 16; i++) {
 270                if (GET_PTR_TYPE(tree->a[i]) != PTR_TYPE_NULL) {
 271                        if (p) /* more than one entry */
 272                                return -2;
 273                        p = tree->a[i];
 274                }
 275        }
 276
 277        /* replace tree with p in parent[index] */
 278        parent->a[index] = p;
 279        free(tree);
 280        return 0;
 281}
 282
 283/*
 284 * To remove a leaf_node:
 285 * Search to the tree location appropriate for the given leaf_node's key:
 286 * - If location does not hold a matching entry, abort and do nothing.
 287 * - Replace the matching leaf_node with a NULL entry (and free the leaf_node).
 288 * - Consolidate int_nodes repeatedly, while walking up the tree towards root.
 289 */
 290static void note_tree_remove(struct int_node *tree, unsigned char n,
 291                struct leaf_node *entry)
 292{
 293        struct leaf_node *l;
 294        struct int_node *parent_stack[20];
 295        unsigned char i, j;
 296        void **p = note_tree_search(&tree, &n, entry->key_sha1);
 297
 298        assert(GET_PTR_TYPE(entry) == 0); /* no type bits set */
 299        if (GET_PTR_TYPE(*p) != PTR_TYPE_NOTE)
 300                return; /* type mismatch, nothing to remove */
 301        l = (struct leaf_node *) CLR_PTR_TYPE(*p);
 302        if (hashcmp(l->key_sha1, entry->key_sha1))
 303                return; /* key mismatch, nothing to remove */
 304
 305        /* we have found a matching entry */
 306        free(l);
 307        *p = SET_PTR_TYPE(NULL, PTR_TYPE_NULL);
 308
 309        /* consolidate this tree level, and parent levels, if possible */
 310        if (!n)
 311                return; /* cannot consolidate top level */
 312        /* first, build stack of ancestors between root and current node */
 313        parent_stack[0] = &root_node;
 314        for (i = 0; i < n; i++) {
 315                j = GET_NIBBLE(i, entry->key_sha1);
 316                parent_stack[i + 1] = CLR_PTR_TYPE(parent_stack[i]->a[j]);
 317        }
 318        assert(i == n && parent_stack[i] == tree);
 319        /* next, unwind stack until note_tree_consolidate() is done */
 320        while (i > 0 &&
 321               !note_tree_consolidate(parent_stack[i], parent_stack[i - 1],
 322                                      GET_NIBBLE(i - 1, entry->key_sha1)))
 323                i--;
 324}
 325
 326/* Free the entire notes data contained in the given tree */
 327static void note_tree_free(struct int_node *tree)
 328{
 329        unsigned int i;
 330        for (i = 0; i < 16; i++) {
 331                void *p = tree->a[i];
 332                switch (GET_PTR_TYPE(p)) {
 333                case PTR_TYPE_INTERNAL:
 334                        note_tree_free(CLR_PTR_TYPE(p));
 335                        /* fall through */
 336                case PTR_TYPE_NOTE:
 337                case PTR_TYPE_SUBTREE:
 338                        free(CLR_PTR_TYPE(p));
 339                }
 340        }
 341}
 342
 343/*
 344 * Convert a partial SHA1 hex string to the corresponding partial SHA1 value.
 345 * - hex      - Partial SHA1 segment in ASCII hex format
 346 * - hex_len  - Length of above segment. Must be multiple of 2 between 0 and 40
 347 * - sha1     - Partial SHA1 value is written here
 348 * - sha1_len - Max #bytes to store in sha1, Must be >= hex_len / 2, and < 20
 349 * Returns -1 on error (invalid arguments or invalid SHA1 (not in hex format)).
 350 * Otherwise, returns number of bytes written to sha1 (i.e. hex_len / 2).
 351 * Pads sha1 with NULs up to sha1_len (not included in returned length).
 352 */
 353static int get_sha1_hex_segment(const char *hex, unsigned int hex_len,
 354                unsigned char *sha1, unsigned int sha1_len)
 355{
 356        unsigned int i, len = hex_len >> 1;
 357        if (hex_len % 2 != 0 || len > sha1_len)
 358                return -1;
 359        for (i = 0; i < len; i++) {
 360                unsigned int val = (hexval(hex[0]) << 4) | hexval(hex[1]);
 361                if (val & ~0xff)
 362                        return -1;
 363                *sha1++ = val;
 364                hex += 2;
 365        }
 366        for (; i < sha1_len; i++)
 367                *sha1++ = 0;
 368        return len;
 369}
 370
 371static void load_subtree(struct leaf_node *subtree, struct int_node *node,
 372                unsigned int n)
 373{
 374        unsigned char object_sha1[20];
 375        unsigned int prefix_len;
 376        void *buf;
 377        struct tree_desc desc;
 378        struct name_entry entry;
 379
 380        buf = fill_tree_descriptor(&desc, subtree->val_sha1);
 381        if (!buf)
 382                die("Could not read %s for notes-index",
 383                     sha1_to_hex(subtree->val_sha1));
 384
 385        prefix_len = subtree->key_sha1[19];
 386        assert(prefix_len * 2 >= n);
 387        memcpy(object_sha1, subtree->key_sha1, prefix_len);
 388        while (tree_entry(&desc, &entry)) {
 389                int len = get_sha1_hex_segment(entry.path, strlen(entry.path),
 390                                object_sha1 + prefix_len, 20 - prefix_len);
 391                if (len < 0)
 392                        continue; /* entry.path is not a SHA1 sum. Skip */
 393                len += prefix_len;
 394
 395                /*
 396                 * If object SHA1 is complete (len == 20), assume note object
 397                 * If object SHA1 is incomplete (len < 20), assume note subtree
 398                 */
 399                if (len <= 20) {
 400                        unsigned char type = PTR_TYPE_NOTE;
 401                        struct leaf_node *l = (struct leaf_node *)
 402                                xcalloc(sizeof(struct leaf_node), 1);
 403                        hashcpy(l->key_sha1, object_sha1);
 404                        hashcpy(l->val_sha1, entry.sha1);
 405                        if (len < 20) {
 406                                if (!S_ISDIR(entry.mode))
 407                                        continue; /* entry cannot be subtree */
 408                                l->key_sha1[19] = (unsigned char) len;
 409                                type = PTR_TYPE_SUBTREE;
 410                        }
 411                        note_tree_insert(node, n, l, type);
 412                }
 413        }
 414        free(buf);
 415}
 416
 417/*
 418 * Determine optimal on-disk fanout for this part of the notes tree
 419 *
 420 * Given a (sub)tree and the level in the internal tree structure, determine
 421 * whether or not the given existing fanout should be expanded for this
 422 * (sub)tree.
 423 *
 424 * Values of the 'fanout' variable:
 425 * - 0: No fanout (all notes are stored directly in the root notes tree)
 426 * - 1: 2/38 fanout
 427 * - 2: 2/2/36 fanout
 428 * - 3: 2/2/2/34 fanout
 429 * etc.
 430 */
 431static unsigned char determine_fanout(struct int_node *tree, unsigned char n,
 432                unsigned char fanout)
 433{
 434        /*
 435         * The following is a simple heuristic that works well in practice:
 436         * For each even-numbered 16-tree level (remember that each on-disk
 437         * fanout level corresponds to _two_ 16-tree levels), peek at all 16
 438         * entries at that tree level. If all of them are either int_nodes or
 439         * subtree entries, then there are likely plenty of notes below this
 440         * level, so we return an incremented fanout.
 441         */
 442        unsigned int i;
 443        if ((n % 2) || (n > 2 * fanout))
 444                return fanout;
 445        for (i = 0; i < 16; i++) {
 446                switch (GET_PTR_TYPE(tree->a[i])) {
 447                case PTR_TYPE_SUBTREE:
 448                case PTR_TYPE_INTERNAL:
 449                        continue;
 450                default:
 451                        return fanout;
 452                }
 453        }
 454        return fanout + 1;
 455}
 456
 457static void construct_path_with_fanout(const unsigned char *sha1,
 458                unsigned char fanout, char *path)
 459{
 460        unsigned int i = 0, j = 0;
 461        const char *hex_sha1 = sha1_to_hex(sha1);
 462        assert(fanout < 20);
 463        while (fanout) {
 464                path[i++] = hex_sha1[j++];
 465                path[i++] = hex_sha1[j++];
 466                path[i++] = '/';
 467                fanout--;
 468        }
 469        strcpy(path + i, hex_sha1 + j);
 470}
 471
 472static int for_each_note_helper(struct int_node *tree, unsigned char n,
 473                unsigned char fanout, int flags, each_note_fn fn,
 474                void *cb_data)
 475{
 476        unsigned int i;
 477        void *p;
 478        int ret = 0;
 479        struct leaf_node *l;
 480        static char path[40 + 19 + 1];  /* hex SHA1 + 19 * '/' + NUL */
 481
 482        fanout = determine_fanout(tree, n, fanout);
 483        for (i = 0; i < 16; i++) {
 484redo:
 485                p = tree->a[i];
 486                switch (GET_PTR_TYPE(p)) {
 487                case PTR_TYPE_INTERNAL:
 488                        /* recurse into int_node */
 489                        ret = for_each_note_helper(CLR_PTR_TYPE(p), n + 1,
 490                                fanout, flags, fn, cb_data);
 491                        break;
 492                case PTR_TYPE_SUBTREE:
 493                        l = (struct leaf_node *) CLR_PTR_TYPE(p);
 494                        /*
 495                         * Subtree entries in the note tree represent parts of
 496                         * the note tree that have not yet been explored. There
 497                         * is a direct relationship between subtree entries at
 498                         * level 'n' in the tree, and the 'fanout' variable:
 499                         * Subtree entries at level 'n <= 2 * fanout' should be
 500                         * preserved, since they correspond exactly to a fanout
 501                         * directory in the on-disk structure. However, subtree
 502                         * entries at level 'n > 2 * fanout' should NOT be
 503                         * preserved, but rather consolidated into the above
 504                         * notes tree level. We achieve this by unconditionally
 505                         * unpacking subtree entries that exist below the
 506                         * threshold level at 'n = 2 * fanout'.
 507                         */
 508                        if (n <= 2 * fanout &&
 509                            flags & FOR_EACH_NOTE_YIELD_SUBTREES) {
 510                                /* invoke callback with subtree */
 511                                unsigned int path_len =
 512                                        l->key_sha1[19] * 2 + fanout;
 513                                assert(path_len < 40 + 19);
 514                                construct_path_with_fanout(l->key_sha1, fanout,
 515                                                           path);
 516                                /* Create trailing slash, if needed */
 517                                if (path[path_len - 1] != '/')
 518                                        path[path_len++] = '/';
 519                                path[path_len] = '\0';
 520                                ret = fn(l->key_sha1, l->val_sha1, path,
 521                                         cb_data);
 522                        }
 523                        if (n > fanout * 2 ||
 524                            !(flags & FOR_EACH_NOTE_DONT_UNPACK_SUBTREES)) {
 525                                /* unpack subtree and resume traversal */
 526                                tree->a[i] = NULL;
 527                                load_subtree(l, tree, n);
 528                                free(l);
 529                                goto redo;
 530                        }
 531                        break;
 532                case PTR_TYPE_NOTE:
 533                        l = (struct leaf_node *) CLR_PTR_TYPE(p);
 534                        construct_path_with_fanout(l->key_sha1, fanout, path);
 535                        ret = fn(l->key_sha1, l->val_sha1, path, cb_data);
 536                        break;
 537                }
 538                if (ret)
 539                        return ret;
 540        }
 541        return 0;
 542}
 543
 544struct tree_write_stack {
 545        struct tree_write_stack *next;
 546        struct strbuf buf;
 547        char path[2]; /* path to subtree in next, if any */
 548};
 549
 550static inline int matches_tree_write_stack(struct tree_write_stack *tws,
 551                const char *full_path)
 552{
 553        return  full_path[0] == tws->path[0] &&
 554                full_path[1] == tws->path[1] &&
 555                full_path[2] == '/';
 556}
 557
 558static void write_tree_entry(struct strbuf *buf, unsigned int mode,
 559                const char *path, unsigned int path_len, const
 560                unsigned char *sha1)
 561{
 562                strbuf_addf(buf, "%06o %.*s%c", mode, path_len, path, '\0');
 563                strbuf_add(buf, sha1, 20);
 564}
 565
 566static void tree_write_stack_init_subtree(struct tree_write_stack *tws,
 567                const char *path)
 568{
 569        struct tree_write_stack *n;
 570        assert(!tws->next);
 571        assert(tws->path[0] == '\0' && tws->path[1] == '\0');
 572        n = (struct tree_write_stack *)
 573                xmalloc(sizeof(struct tree_write_stack));
 574        n->next = NULL;
 575        strbuf_init(&n->buf, 256 * (32 + 40)); /* assume 256 entries per tree */
 576        n->path[0] = n->path[1] = '\0';
 577        tws->next = n;
 578        tws->path[0] = path[0];
 579        tws->path[1] = path[1];
 580}
 581
 582static int tree_write_stack_finish_subtree(struct tree_write_stack *tws)
 583{
 584        int ret;
 585        struct tree_write_stack *n = tws->next;
 586        unsigned char s[20];
 587        if (n) {
 588                ret = tree_write_stack_finish_subtree(n);
 589                if (ret)
 590                        return ret;
 591                ret = write_sha1_file(n->buf.buf, n->buf.len, tree_type, s);
 592                if (ret)
 593                        return ret;
 594                strbuf_release(&n->buf);
 595                free(n);
 596                tws->next = NULL;
 597                write_tree_entry(&tws->buf, 040000, tws->path, 2, s);
 598                tws->path[0] = tws->path[1] = '\0';
 599        }
 600        return 0;
 601}
 602
 603static int write_each_note_helper(struct tree_write_stack *tws,
 604                const char *path, unsigned int mode,
 605                const unsigned char *sha1)
 606{
 607        size_t path_len = strlen(path);
 608        unsigned int n = 0;
 609        int ret;
 610
 611        /* Determine common part of tree write stack */
 612        while (tws && 3 * n < path_len &&
 613               matches_tree_write_stack(tws, path + 3 * n)) {
 614                n++;
 615                tws = tws->next;
 616        }
 617
 618        /* tws point to last matching tree_write_stack entry */
 619        ret = tree_write_stack_finish_subtree(tws);
 620        if (ret)
 621                return ret;
 622
 623        /* Start subtrees needed to satisfy path */
 624        while (3 * n + 2 < path_len && path[3 * n + 2] == '/') {
 625                tree_write_stack_init_subtree(tws, path + 3 * n);
 626                n++;
 627                tws = tws->next;
 628        }
 629
 630        /* There should be no more directory components in the given path */
 631        assert(memchr(path + 3 * n, '/', path_len - (3 * n)) == NULL);
 632
 633        /* Finally add given entry to the current tree object */
 634        write_tree_entry(&tws->buf, mode, path + 3 * n, path_len - (3 * n),
 635                         sha1);
 636
 637        return 0;
 638}
 639
 640struct write_each_note_data {
 641        struct tree_write_stack *root;
 642};
 643
 644static int write_each_note(const unsigned char *object_sha1,
 645                const unsigned char *note_sha1, char *note_path,
 646                void *cb_data)
 647{
 648        struct write_each_note_data *d =
 649                (struct write_each_note_data *) cb_data;
 650        size_t note_path_len = strlen(note_path);
 651        unsigned int mode = 0100644;
 652
 653        if (note_path[note_path_len - 1] == '/') {
 654                /* subtree entry */
 655                note_path_len--;
 656                note_path[note_path_len] = '\0';
 657                mode = 040000;
 658        }
 659        assert(note_path_len <= 40 + 19);
 660
 661        return write_each_note_helper(d->root, note_path, mode, note_sha1);
 662}
 663
 664void init_notes(const char *notes_ref, int flags)
 665{
 666        unsigned char sha1[20], object_sha1[20];
 667        unsigned mode;
 668        struct leaf_node root_tree;
 669
 670        assert(!initialized);
 671        initialized = 1;
 672
 673        if (!notes_ref)
 674                notes_ref = getenv(GIT_NOTES_REF_ENVIRONMENT);
 675        if (!notes_ref)
 676                notes_ref = notes_ref_name; /* value of core.notesRef config */
 677        if (!notes_ref)
 678                notes_ref = GIT_NOTES_DEFAULT_REF;
 679
 680        if (flags & NOTES_INIT_EMPTY || !notes_ref ||
 681            read_ref(notes_ref, object_sha1))
 682                return;
 683        if (get_tree_entry(object_sha1, "", sha1, &mode))
 684                die("Failed to read notes tree referenced by %s (%s)",
 685                    notes_ref, object_sha1);
 686
 687        hashclr(root_tree.key_sha1);
 688        hashcpy(root_tree.val_sha1, sha1);
 689        load_subtree(&root_tree, &root_node, 0);
 690}
 691
 692void add_note(const unsigned char *object_sha1, const unsigned char *note_sha1)
 693{
 694        struct leaf_node *l;
 695
 696        assert(initialized);
 697        l = (struct leaf_node *) xmalloc(sizeof(struct leaf_node));
 698        hashcpy(l->key_sha1, object_sha1);
 699        hashcpy(l->val_sha1, note_sha1);
 700        note_tree_insert(&root_node, 0, l, PTR_TYPE_NOTE);
 701}
 702
 703void remove_note(const unsigned char *object_sha1)
 704{
 705        struct leaf_node l;
 706
 707        assert(initialized);
 708        hashcpy(l.key_sha1, object_sha1);
 709        hashclr(l.val_sha1);
 710        return note_tree_remove(&root_node, 0, &l);
 711}
 712
 713const unsigned char *get_note(const unsigned char *object_sha1)
 714{
 715        struct leaf_node *found;
 716
 717        assert(initialized);
 718        found = note_tree_find(&root_node, 0, object_sha1);
 719        return found ? found->val_sha1 : NULL;
 720}
 721
 722int for_each_note(int flags, each_note_fn fn, void *cb_data)
 723{
 724        assert(initialized);
 725        return for_each_note_helper(&root_node, 0, 0, flags, fn, cb_data);
 726}
 727
 728int write_notes_tree(unsigned char *result)
 729{
 730        struct tree_write_stack root;
 731        struct write_each_note_data cb_data;
 732        int ret;
 733
 734        assert(initialized);
 735
 736        /* Prepare for traversal of current notes tree */
 737        root.next = NULL; /* last forward entry in list is grounded */
 738        strbuf_init(&root.buf, 256 * (32 + 40)); /* assume 256 entries */
 739        root.path[0] = root.path[1] = '\0';
 740        cb_data.root = &root;
 741
 742        /* Write tree objects representing current notes tree */
 743        ret = for_each_note(FOR_EACH_NOTE_DONT_UNPACK_SUBTREES |
 744                                FOR_EACH_NOTE_YIELD_SUBTREES,
 745                        write_each_note, &cb_data) ||
 746                tree_write_stack_finish_subtree(&root) ||
 747                write_sha1_file(root.buf.buf, root.buf.len, tree_type, result);
 748        strbuf_release(&root.buf);
 749        return ret;
 750}
 751
 752void free_notes(void)
 753{
 754        note_tree_free(&root_node);
 755        memset(&root_node, 0, sizeof(struct int_node));
 756        initialized = 0;
 757}
 758
 759void format_note(const unsigned char *object_sha1, struct strbuf *sb,
 760                const char *output_encoding, int flags)
 761{
 762        static const char utf8[] = "utf-8";
 763        const unsigned char *sha1;
 764        char *msg, *msg_p;
 765        unsigned long linelen, msglen;
 766        enum object_type type;
 767
 768        if (!initialized)
 769                init_notes(NULL, 0);
 770
 771        sha1 = get_note(object_sha1);
 772        if (!sha1)
 773                return;
 774
 775        if (!(msg = read_sha1_file(sha1, &type, &msglen)) || !msglen ||
 776                        type != OBJ_BLOB) {
 777                free(msg);
 778                return;
 779        }
 780
 781        if (output_encoding && *output_encoding &&
 782                        strcmp(utf8, output_encoding)) {
 783                char *reencoded = reencode_string(msg, output_encoding, utf8);
 784                if (reencoded) {
 785                        free(msg);
 786                        msg = reencoded;
 787                        msglen = strlen(msg);
 788                }
 789        }
 790
 791        /* we will end the annotation by a newline anyway */
 792        if (msglen && msg[msglen - 1] == '\n')
 793                msglen--;
 794
 795        if (flags & NOTES_SHOW_HEADER)
 796                strbuf_addstr(sb, "\nNotes:\n");
 797
 798        for (msg_p = msg; msg_p < msg + msglen; msg_p += linelen + 1) {
 799                linelen = strchrnul(msg_p, '\n') - msg_p;
 800
 801                if (flags & NOTES_INDENT)
 802                        strbuf_addstr(sb, "    ");
 803                strbuf_add(sb, msg_p, linelen);
 804                strbuf_addch(sb, '\n');
 805        }
 806
 807        free(msg);
 808}