]> git.proxmox.com Git - libgit2.git/blob - src/tree.c
Merge pull request #3794 from libgit2/cmn/tree-update-basename
[libgit2.git] / src / tree.c
1 /*
2 * Copyright (C) the libgit2 contributors. All rights reserved.
3 *
4 * This file is part of libgit2, distributed under the GNU GPL v2 with
5 * a Linking Exception. For full terms see the included COPYING file.
6 */
7
8 #include "common.h"
9 #include "commit.h"
10 #include "tree.h"
11 #include "git2/repository.h"
12 #include "git2/object.h"
13 #include "fileops.h"
14 #include "tree-cache.h"
15 #include "index.h"
16
17 #define DEFAULT_TREE_SIZE 16
18 #define MAX_FILEMODE_BYTES 6
19
20 #define TREE_ENTRY_CHECK_NAMELEN(n) \
21 if (n > UINT16_MAX) { giterr_set(GITERR_INVALID, "tree entry path too long"); }
22
23 GIT__USE_STRMAP
24
25 static bool valid_filemode(const int filemode)
26 {
27 return (filemode == GIT_FILEMODE_TREE
28 || filemode == GIT_FILEMODE_BLOB
29 || filemode == GIT_FILEMODE_BLOB_EXECUTABLE
30 || filemode == GIT_FILEMODE_LINK
31 || filemode == GIT_FILEMODE_COMMIT);
32 }
33
34 GIT_INLINE(git_filemode_t) normalize_filemode(git_filemode_t filemode)
35 {
36 /* Tree bits set, but it's not a commit */
37 if (GIT_MODE_TYPE(filemode) == GIT_FILEMODE_TREE)
38 return GIT_FILEMODE_TREE;
39
40 /* If any of the x bits are set */
41 if (GIT_PERMS_IS_EXEC(filemode))
42 return GIT_FILEMODE_BLOB_EXECUTABLE;
43
44 /* 16XXXX means commit */
45 if (GIT_MODE_TYPE(filemode) == GIT_FILEMODE_COMMIT)
46 return GIT_FILEMODE_COMMIT;
47
48 /* 12XXXX means commit */
49 if (GIT_MODE_TYPE(filemode) == GIT_FILEMODE_LINK)
50 return GIT_FILEMODE_LINK;
51
52 /* Otherwise, return a blob */
53 return GIT_FILEMODE_BLOB;
54 }
55
56 static int valid_entry_name(git_repository *repo, const char *filename)
57 {
58 return *filename != '\0' &&
59 git_path_isvalid(repo, filename,
60 GIT_PATH_REJECT_TRAVERSAL | GIT_PATH_REJECT_DOT_GIT | GIT_PATH_REJECT_SLASH);
61 }
62
63 static int entry_sort_cmp(const void *a, const void *b)
64 {
65 const git_tree_entry *e1 = (const git_tree_entry *)a;
66 const git_tree_entry *e2 = (const git_tree_entry *)b;
67
68 return git_path_cmp(
69 e1->filename, e1->filename_len, git_tree_entry__is_tree(e1),
70 e2->filename, e2->filename_len, git_tree_entry__is_tree(e2),
71 git__strncmp);
72 }
73
74 int git_tree_entry_cmp(const git_tree_entry *e1, const git_tree_entry *e2)
75 {
76 return entry_sort_cmp(e1, e2);
77 }
78
79 int git_tree_entry_icmp(const git_tree_entry *e1, const git_tree_entry *e2)
80 {
81 return git_path_cmp(
82 e1->filename, e1->filename_len, git_tree_entry__is_tree(e1),
83 e2->filename, e2->filename_len, git_tree_entry__is_tree(e2),
84 git__strncasecmp);
85 }
86
87 /**
88 * Allocate a new self-contained entry, with enough space after it to
89 * store the filename and the id.
90 */
91 static git_tree_entry *alloc_entry(const char *filename, size_t filename_len, const git_oid *id)
92 {
93 git_tree_entry *entry = NULL;
94 size_t tree_len;
95
96 TREE_ENTRY_CHECK_NAMELEN(filename_len);
97
98 if (GIT_ADD_SIZET_OVERFLOW(&tree_len, sizeof(git_tree_entry), filename_len) ||
99 GIT_ADD_SIZET_OVERFLOW(&tree_len, tree_len, 1) ||
100 GIT_ADD_SIZET_OVERFLOW(&tree_len, tree_len, GIT_OID_RAWSZ))
101 return NULL;
102
103 entry = git__calloc(1, tree_len);
104 if (!entry)
105 return NULL;
106
107 {
108 char *filename_ptr;
109 void *id_ptr;
110
111 filename_ptr = ((char *) entry) + sizeof(git_tree_entry);
112 memcpy(filename_ptr, filename, filename_len);
113 entry->filename = filename_ptr;
114
115 id_ptr = filename_ptr + filename_len + 1;
116 git_oid_cpy(id_ptr, id);
117 entry->oid = id_ptr;
118 }
119
120 entry->filename_len = (uint16_t)filename_len;
121
122 return entry;
123 }
124
125 struct tree_key_search {
126 const char *filename;
127 uint16_t filename_len;
128 };
129
130 static int homing_search_cmp(const void *key, const void *array_member)
131 {
132 const struct tree_key_search *ksearch = key;
133 const git_tree_entry *entry = array_member;
134
135 const uint16_t len1 = ksearch->filename_len;
136 const uint16_t len2 = entry->filename_len;
137
138 return memcmp(
139 ksearch->filename,
140 entry->filename,
141 len1 < len2 ? len1 : len2
142 );
143 }
144
145 /*
146 * Search for an entry in a given tree.
147 *
148 * Note that this search is performed in two steps because
149 * of the way tree entries are sorted internally in git:
150 *
151 * Entries in a tree are not sorted alphabetically; two entries
152 * with the same root prefix will have different positions
153 * depending on whether they are folders (subtrees) or normal files.
154 *
155 * Consequently, it is not possible to find an entry on the tree
156 * with a binary search if you don't know whether the filename
157 * you're looking for is a folder or a normal file.
158 *
159 * To work around this, we first perform a homing binary search
160 * on the tree, using the minimal length root prefix of our filename.
161 * Once the comparisons for this homing search start becoming
162 * ambiguous because of folder vs file sorting, we look linearly
163 * around the area for our target file.
164 */
165 static int tree_key_search(
166 size_t *at_pos,
167 const git_tree *tree,
168 const char *filename,
169 size_t filename_len)
170 {
171 struct tree_key_search ksearch;
172 const git_tree_entry *entry;
173 size_t homing, i;
174
175 TREE_ENTRY_CHECK_NAMELEN(filename_len);
176
177 ksearch.filename = filename;
178 ksearch.filename_len = (uint16_t)filename_len;
179
180 /* Initial homing search; find an entry on the tree with
181 * the same prefix as the filename we're looking for */
182
183 if (git_array_search(&homing,
184 tree->entries, &homing_search_cmp, &ksearch) < 0)
185 return GIT_ENOTFOUND; /* just a signal error; not passed back to user */
186
187 /* We found a common prefix. Look forward as long as
188 * there are entries that share the common prefix */
189 for (i = homing; i < tree->entries.size; ++i) {
190 entry = git_array_get(tree->entries, i);
191
192 if (homing_search_cmp(&ksearch, entry) < 0)
193 break;
194
195 if (entry->filename_len == filename_len &&
196 memcmp(filename, entry->filename, filename_len) == 0) {
197 if (at_pos)
198 *at_pos = i;
199
200 return 0;
201 }
202 }
203
204 /* If we haven't found our filename yet, look backwards
205 * too as long as we have entries with the same prefix */
206 if (homing > 0) {
207 i = homing - 1;
208
209 do {
210 entry = git_array_get(tree->entries, i);
211
212 if (homing_search_cmp(&ksearch, entry) > 0)
213 break;
214
215 if (entry->filename_len == filename_len &&
216 memcmp(filename, entry->filename, filename_len) == 0) {
217 if (at_pos)
218 *at_pos = i;
219
220 return 0;
221 }
222 } while (i-- > 0);
223 }
224
225 /* The filename doesn't exist at all */
226 return GIT_ENOTFOUND;
227 }
228
229 void git_tree_entry_free(git_tree_entry *entry)
230 {
231 if (entry == NULL)
232 return;
233
234 git__free(entry);
235 }
236
237 int git_tree_entry_dup(git_tree_entry **dest, const git_tree_entry *source)
238 {
239 git_tree_entry *cpy;
240
241 assert(source);
242
243 cpy = alloc_entry(source->filename, source->filename_len, source->oid);
244 if (cpy == NULL)
245 return -1;
246
247 cpy->attr = source->attr;
248
249 *dest = cpy;
250 return 0;
251 }
252
253 void git_tree__free(void *_tree)
254 {
255 git_tree *tree = _tree;
256
257 git_odb_object_free(tree->odb_obj);
258 git_array_clear(tree->entries);
259 git__free(tree);
260 }
261
262 git_filemode_t git_tree_entry_filemode(const git_tree_entry *entry)
263 {
264 return normalize_filemode(entry->attr);
265 }
266
267 git_filemode_t git_tree_entry_filemode_raw(const git_tree_entry *entry)
268 {
269 return entry->attr;
270 }
271
272 const char *git_tree_entry_name(const git_tree_entry *entry)
273 {
274 assert(entry);
275 return entry->filename;
276 }
277
278 const git_oid *git_tree_entry_id(const git_tree_entry *entry)
279 {
280 assert(entry);
281 return entry->oid;
282 }
283
284 git_otype git_tree_entry_type(const git_tree_entry *entry)
285 {
286 assert(entry);
287
288 if (S_ISGITLINK(entry->attr))
289 return GIT_OBJ_COMMIT;
290 else if (S_ISDIR(entry->attr))
291 return GIT_OBJ_TREE;
292 else
293 return GIT_OBJ_BLOB;
294 }
295
296 int git_tree_entry_to_object(
297 git_object **object_out,
298 git_repository *repo,
299 const git_tree_entry *entry)
300 {
301 assert(entry && object_out);
302 return git_object_lookup(object_out, repo, entry->oid, GIT_OBJ_ANY);
303 }
304
305 static const git_tree_entry *entry_fromname(
306 const git_tree *tree, const char *name, size_t name_len)
307 {
308 size_t idx;
309
310 if (tree_key_search(&idx, tree, name, name_len) < 0)
311 return NULL;
312
313 return git_array_get(tree->entries, idx);
314 }
315
316 const git_tree_entry *git_tree_entry_byname(
317 const git_tree *tree, const char *filename)
318 {
319 assert(tree && filename);
320
321 return entry_fromname(tree, filename, strlen(filename));
322 }
323
324 const git_tree_entry *git_tree_entry_byindex(
325 const git_tree *tree, size_t idx)
326 {
327 assert(tree);
328 return git_array_get(tree->entries, idx);
329 }
330
331 const git_tree_entry *git_tree_entry_byid(
332 const git_tree *tree, const git_oid *id)
333 {
334 size_t i;
335 const git_tree_entry *e;
336
337 assert(tree);
338
339 git_array_foreach(tree->entries, i, e) {
340 if (memcmp(&e->oid->id, &id->id, sizeof(id->id)) == 0)
341 return e;
342 }
343
344 return NULL;
345 }
346
347 int git_tree__prefix_position(const git_tree *tree, const char *path)
348 {
349 struct tree_key_search ksearch;
350 size_t at_pos, path_len;
351
352 if (!path)
353 return 0;
354
355 path_len = strlen(path);
356 TREE_ENTRY_CHECK_NAMELEN(path_len);
357
358 ksearch.filename = path;
359 ksearch.filename_len = (uint16_t)path_len;
360
361 /* Find tree entry with appropriate prefix */
362 git_array_search(
363 &at_pos, tree->entries, &homing_search_cmp, &ksearch);
364
365 for (; at_pos < tree->entries.size; ++at_pos) {
366 const git_tree_entry *entry = git_array_get(tree->entries, at_pos);
367 if (homing_search_cmp(&ksearch, entry) < 0)
368 break;
369 }
370
371 for (; at_pos > 0; --at_pos) {
372 const git_tree_entry *entry =
373 git_array_get(tree->entries, at_pos - 1);
374
375 if (homing_search_cmp(&ksearch, entry) > 0)
376 break;
377 }
378
379 return (int)at_pos;
380 }
381
382 size_t git_tree_entrycount(const git_tree *tree)
383 {
384 assert(tree);
385 return tree->entries.size;
386 }
387
388 unsigned int git_treebuilder_entrycount(git_treebuilder *bld)
389 {
390 assert(bld);
391
392 return git_strmap_num_entries(bld->map);
393 }
394
395 static int tree_error(const char *str, const char *path)
396 {
397 if (path)
398 giterr_set(GITERR_TREE, "%s - %s", str, path);
399 else
400 giterr_set(GITERR_TREE, "%s", str);
401 return -1;
402 }
403
404 static int parse_mode(unsigned int *modep, const char *buffer, const char **buffer_out)
405 {
406 unsigned char c;
407 unsigned int mode = 0;
408
409 if (*buffer == ' ')
410 return -1;
411
412 while ((c = *buffer++) != ' ') {
413 if (c < '0' || c > '7')
414 return -1;
415 mode = (mode << 3) + (c - '0');
416 }
417 *modep = mode;
418 *buffer_out = buffer;
419
420 return 0;
421 }
422
423 int git_tree__parse(void *_tree, git_odb_object *odb_obj)
424 {
425 git_tree *tree = _tree;
426 const char *buffer;
427 const char *buffer_end;
428
429 if (git_odb_object_dup(&tree->odb_obj, odb_obj) < 0)
430 return -1;
431
432 buffer = git_odb_object_data(tree->odb_obj);
433 buffer_end = buffer + git_odb_object_size(tree->odb_obj);
434
435 git_array_init_to_size(tree->entries, DEFAULT_TREE_SIZE);
436 GITERR_CHECK_ARRAY(tree->entries);
437
438 while (buffer < buffer_end) {
439 git_tree_entry *entry;
440 size_t filename_len;
441 const char *nul;
442 unsigned int attr;
443
444 if (parse_mode(&attr, buffer, &buffer) < 0 || !buffer)
445 return tree_error("Failed to parse tree. Can't parse filemode", NULL);
446
447 if ((nul = memchr(buffer, 0, buffer_end - buffer)) == NULL)
448 return tree_error("Failed to parse tree. Object is corrupted", NULL);
449
450 filename_len = nul - buffer;
451 /* Allocate the entry */
452 {
453 entry = git_array_alloc(tree->entries);
454 GITERR_CHECK_ALLOC(entry);
455
456 entry->attr = attr;
457 entry->filename_len = filename_len;
458 entry->filename = buffer;
459 entry->oid = (git_oid *) ((char *) buffer + filename_len + 1);
460 }
461
462 buffer += filename_len + 1;
463 buffer += GIT_OID_RAWSZ;
464 }
465
466 return 0;
467 }
468
469 static size_t find_next_dir(const char *dirname, git_index *index, size_t start)
470 {
471 size_t dirlen, i, entries = git_index_entrycount(index);
472
473 dirlen = strlen(dirname);
474 for (i = start; i < entries; ++i) {
475 const git_index_entry *entry = git_index_get_byindex(index, i);
476 if (strlen(entry->path) < dirlen ||
477 memcmp(entry->path, dirname, dirlen) ||
478 (dirlen > 0 && entry->path[dirlen] != '/')) {
479 break;
480 }
481 }
482
483 return i;
484 }
485
486 static int append_entry(
487 git_treebuilder *bld,
488 const char *filename,
489 const git_oid *id,
490 git_filemode_t filemode)
491 {
492 git_tree_entry *entry;
493 int error = 0;
494
495 if (!valid_entry_name(bld->repo, filename))
496 return tree_error("Failed to insert entry. Invalid name for a tree entry", filename);
497
498 entry = alloc_entry(filename, strlen(filename), id);
499 GITERR_CHECK_ALLOC(entry);
500
501 entry->attr = (uint16_t)filemode;
502
503 git_strmap_insert(bld->map, entry->filename, entry, error);
504 if (error < 0) {
505 git_tree_entry_free(entry);
506 giterr_set(GITERR_TREE, "failed to append entry %s to the tree builder", filename);
507 return -1;
508 }
509
510 return 0;
511 }
512
513 static int write_tree(
514 git_oid *oid,
515 git_repository *repo,
516 git_index *index,
517 const char *dirname,
518 size_t start)
519 {
520 git_treebuilder *bld = NULL;
521 size_t i, entries = git_index_entrycount(index);
522 int error;
523 size_t dirname_len = strlen(dirname);
524 const git_tree_cache *cache;
525
526 cache = git_tree_cache_get(index->tree, dirname);
527 if (cache != NULL && cache->entry_count >= 0){
528 git_oid_cpy(oid, &cache->oid);
529 return (int)find_next_dir(dirname, index, start);
530 }
531
532 if ((error = git_treebuilder_new(&bld, repo, NULL)) < 0 || bld == NULL)
533 return -1;
534
535 /*
536 * This loop is unfortunate, but necessary. The index doesn't have
537 * any directores, so we need to handle that manually, and we
538 * need to keep track of the current position.
539 */
540 for (i = start; i < entries; ++i) {
541 const git_index_entry *entry = git_index_get_byindex(index, i);
542 const char *filename, *next_slash;
543
544 /*
545 * If we've left our (sub)tree, exit the loop and return. The
546 * first check is an early out (and security for the
547 * third). The second check is a simple prefix comparison. The
548 * third check catches situations where there is a directory
549 * win32/sys and a file win32mmap.c. Without it, the following
550 * code believes there is a file win32/mmap.c
551 */
552 if (strlen(entry->path) < dirname_len ||
553 memcmp(entry->path, dirname, dirname_len) ||
554 (dirname_len > 0 && entry->path[dirname_len] != '/')) {
555 break;
556 }
557
558 filename = entry->path + dirname_len;
559 if (*filename == '/')
560 filename++;
561 next_slash = strchr(filename, '/');
562 if (next_slash) {
563 git_oid sub_oid;
564 int written;
565 char *subdir, *last_comp;
566
567 subdir = git__strndup(entry->path, next_slash - entry->path);
568 GITERR_CHECK_ALLOC(subdir);
569
570 /* Write out the subtree */
571 written = write_tree(&sub_oid, repo, index, subdir, i);
572 if (written < 0) {
573 git__free(subdir);
574 goto on_error;
575 } else {
576 i = written - 1; /* -1 because of the loop increment */
577 }
578
579 /*
580 * We need to figure out what we want toinsert
581 * into this tree. If we're traversing
582 * deps/zlib/, then we only want to write
583 * 'zlib' into the tree.
584 */
585 last_comp = strrchr(subdir, '/');
586 if (last_comp) {
587 last_comp++; /* Get rid of the '/' */
588 } else {
589 last_comp = subdir;
590 }
591
592 error = append_entry(bld, last_comp, &sub_oid, S_IFDIR);
593 git__free(subdir);
594 if (error < 0)
595 goto on_error;
596 } else {
597 error = append_entry(bld, filename, &entry->id, entry->mode);
598 if (error < 0)
599 goto on_error;
600 }
601 }
602
603 if (git_treebuilder_write(oid, bld) < 0)
604 goto on_error;
605
606 git_treebuilder_free(bld);
607 return (int)i;
608
609 on_error:
610 git_treebuilder_free(bld);
611 return -1;
612 }
613
614 int git_tree__write_index(
615 git_oid *oid, git_index *index, git_repository *repo)
616 {
617 int ret;
618 git_tree *tree;
619 bool old_ignore_case = false;
620
621 assert(oid && index && repo);
622
623 if (git_index_has_conflicts(index)) {
624 giterr_set(GITERR_INDEX,
625 "Cannot create a tree from a not fully merged index.");
626 return GIT_EUNMERGED;
627 }
628
629 if (index->tree != NULL && index->tree->entry_count >= 0) {
630 git_oid_cpy(oid, &index->tree->oid);
631 return 0;
632 }
633
634 /* The tree cache didn't help us; we'll have to write
635 * out a tree. If the index is ignore_case, we must
636 * make it case-sensitive for the duration of the tree-write
637 * operation. */
638
639 if (index->ignore_case) {
640 old_ignore_case = true;
641 git_index__set_ignore_case(index, false);
642 }
643
644 ret = write_tree(oid, repo, index, "", 0);
645
646 if (old_ignore_case)
647 git_index__set_ignore_case(index, true);
648
649 index->tree = NULL;
650
651 if (ret < 0)
652 return ret;
653
654 git_pool_clear(&index->tree_pool);
655
656 if ((ret = git_tree_lookup(&tree, repo, oid)) < 0)
657 return ret;
658
659 /* Read the tree cache into the index */
660 ret = git_tree_cache_read_tree(&index->tree, tree, &index->tree_pool);
661 git_tree_free(tree);
662
663 return ret;
664 }
665
666 int git_treebuilder_new(
667 git_treebuilder **builder_p,
668 git_repository *repo,
669 const git_tree *source)
670 {
671 git_treebuilder *bld;
672 size_t i;
673
674 assert(builder_p && repo);
675
676 bld = git__calloc(1, sizeof(git_treebuilder));
677 GITERR_CHECK_ALLOC(bld);
678
679 bld->repo = repo;
680
681 if (git_strmap_alloc(&bld->map) < 0) {
682 git__free(bld);
683 return -1;
684 }
685
686 if (source != NULL) {
687 git_tree_entry *entry_src;
688
689 git_array_foreach(source->entries, i, entry_src) {
690 if (append_entry(
691 bld, entry_src->filename,
692 entry_src->oid,
693 entry_src->attr) < 0)
694 goto on_error;
695 }
696 }
697
698 *builder_p = bld;
699 return 0;
700
701 on_error:
702 git_treebuilder_free(bld);
703 return -1;
704 }
705
706 static git_otype otype_from_mode(git_filemode_t filemode)
707 {
708 switch (filemode) {
709 case GIT_FILEMODE_TREE:
710 return GIT_OBJ_TREE;
711 case GIT_FILEMODE_COMMIT:
712 return GIT_OBJ_COMMIT;
713 default:
714 return GIT_OBJ_BLOB;
715 }
716 }
717
718 int git_treebuilder_insert(
719 const git_tree_entry **entry_out,
720 git_treebuilder *bld,
721 const char *filename,
722 const git_oid *id,
723 git_filemode_t filemode)
724 {
725 git_tree_entry *entry;
726 int error;
727 git_strmap_iter pos;
728
729 assert(bld && id && filename);
730
731 if (!valid_filemode(filemode))
732 return tree_error("Failed to insert entry. Invalid filemode for file", filename);
733
734 if (!valid_entry_name(bld->repo, filename))
735 return tree_error("Failed to insert entry. Invalid name for a tree entry", filename);
736
737 if (filemode != GIT_FILEMODE_COMMIT &&
738 !git_object__is_valid(bld->repo, id, otype_from_mode(filemode)))
739 return tree_error("Failed to insert entry; invalid object specified", filename);
740
741 pos = git_strmap_lookup_index(bld->map, filename);
742 if (git_strmap_valid_index(bld->map, pos)) {
743 entry = git_strmap_value_at(bld->map, pos);
744 git_oid_cpy((git_oid *) entry->oid, id);
745 } else {
746 entry = alloc_entry(filename, strlen(filename), id);
747 GITERR_CHECK_ALLOC(entry);
748
749 git_strmap_insert(bld->map, entry->filename, entry, error);
750
751 if (error < 0) {
752 git_tree_entry_free(entry);
753 giterr_set(GITERR_TREE, "failed to insert %s", filename);
754 return -1;
755 }
756 }
757
758 entry->attr = filemode;
759
760 if (entry_out)
761 *entry_out = entry;
762
763 return 0;
764 }
765
766 static git_tree_entry *treebuilder_get(git_treebuilder *bld, const char *filename)
767 {
768 git_tree_entry *entry = NULL;
769 git_strmap_iter pos;
770
771 assert(bld && filename);
772
773 pos = git_strmap_lookup_index(bld->map, filename);
774 if (git_strmap_valid_index(bld->map, pos))
775 entry = git_strmap_value_at(bld->map, pos);
776
777 return entry;
778 }
779
780 const git_tree_entry *git_treebuilder_get(git_treebuilder *bld, const char *filename)
781 {
782 return treebuilder_get(bld, filename);
783 }
784
785 int git_treebuilder_remove(git_treebuilder *bld, const char *filename)
786 {
787 git_tree_entry *entry = treebuilder_get(bld, filename);
788
789 if (entry == NULL)
790 return tree_error("Failed to remove entry. File isn't in the tree", filename);
791
792 git_strmap_delete(bld->map, filename);
793 git_tree_entry_free(entry);
794
795 return 0;
796 }
797
798 int git_treebuilder_write(git_oid *oid, git_treebuilder *bld)
799 {
800 int error = 0;
801 size_t i, entrycount;
802 git_buf tree = GIT_BUF_INIT;
803 git_odb *odb;
804 git_tree_entry *entry;
805 git_vector entries;
806
807 assert(bld);
808
809 entrycount = git_strmap_num_entries(bld->map);
810 if (git_vector_init(&entries, entrycount, entry_sort_cmp) < 0)
811 return -1;
812
813 git_strmap_foreach_value(bld->map, entry, {
814 if (git_vector_insert(&entries, entry) < 0)
815 return -1;
816 });
817
818 git_vector_sort(&entries);
819
820 /* Grow the buffer beforehand to an estimated size */
821 error = git_buf_grow(&tree, entrycount * 72);
822
823 for (i = 0; i < entries.length && !error; ++i) {
824 git_tree_entry *entry = git_vector_get(&entries, i);
825
826 git_buf_printf(&tree, "%o ", entry->attr);
827 git_buf_put(&tree, entry->filename, entry->filename_len + 1);
828 git_buf_put(&tree, (char *)entry->oid->id, GIT_OID_RAWSZ);
829
830 if (git_buf_oom(&tree))
831 error = -1;
832 }
833
834
835 if (!error &&
836 !(error = git_repository_odb__weakptr(&odb, bld->repo)))
837 error = git_odb_write(oid, odb, tree.ptr, tree.size, GIT_OBJ_TREE);
838
839 git_buf_free(&tree);
840 git_vector_free(&entries);
841
842 return error;
843 }
844
845 void git_treebuilder_filter(
846 git_treebuilder *bld,
847 git_treebuilder_filter_cb filter,
848 void *payload)
849 {
850 const char *filename;
851 git_tree_entry *entry;
852
853 assert(bld && filter);
854
855 git_strmap_foreach(bld->map, filename, entry, {
856 if (filter(entry, payload)) {
857 git_strmap_delete(bld->map, filename);
858 git_tree_entry_free(entry);
859 }
860 });
861 }
862
863 void git_treebuilder_clear(git_treebuilder *bld)
864 {
865 git_tree_entry *e;
866
867 assert(bld);
868
869 git_strmap_foreach_value(bld->map, e, git_tree_entry_free(e));
870 git_strmap_clear(bld->map);
871 }
872
873 void git_treebuilder_free(git_treebuilder *bld)
874 {
875 if (bld == NULL)
876 return;
877
878 git_treebuilder_clear(bld);
879 git_strmap_free(bld->map);
880 git__free(bld);
881 }
882
883 static size_t subpath_len(const char *path)
884 {
885 const char *slash_pos = strchr(path, '/');
886 if (slash_pos == NULL)
887 return strlen(path);
888
889 return slash_pos - path;
890 }
891
892 int git_tree_entry_bypath(
893 git_tree_entry **entry_out,
894 const git_tree *root,
895 const char *path)
896 {
897 int error = 0;
898 git_tree *subtree;
899 const git_tree_entry *entry;
900 size_t filename_len;
901
902 /* Find how long is the current path component (i.e.
903 * the filename between two slashes */
904 filename_len = subpath_len(path);
905
906 if (filename_len == 0) {
907 giterr_set(GITERR_TREE, "Invalid tree path given");
908 return GIT_ENOTFOUND;
909 }
910
911 entry = entry_fromname(root, path, filename_len);
912
913 if (entry == NULL) {
914 giterr_set(GITERR_TREE,
915 "the path '%.*s' does not exist in the given tree", filename_len, path);
916 return GIT_ENOTFOUND;
917 }
918
919 switch (path[filename_len]) {
920 case '/':
921 /* If there are more components in the path...
922 * then this entry *must* be a tree */
923 if (!git_tree_entry__is_tree(entry)) {
924 giterr_set(GITERR_TREE,
925 "the path '%.*s' exists but is not a tree", filename_len, path);
926 return GIT_ENOTFOUND;
927 }
928
929 /* If there's only a slash left in the path, we
930 * return the current entry; otherwise, we keep
931 * walking down the path */
932 if (path[filename_len + 1] != '\0')
933 break;
934
935 case '\0':
936 /* If there are no more components in the path, return
937 * this entry */
938 return git_tree_entry_dup(entry_out, entry);
939 }
940
941 if (git_tree_lookup(&subtree, root->object.repo, entry->oid) < 0)
942 return -1;
943
944 error = git_tree_entry_bypath(
945 entry_out,
946 subtree,
947 path + filename_len + 1
948 );
949
950 git_tree_free(subtree);
951 return error;
952 }
953
954 static int tree_walk(
955 const git_tree *tree,
956 git_treewalk_cb callback,
957 git_buf *path,
958 void *payload,
959 bool preorder)
960 {
961 int error = 0;
962 size_t i;
963 const git_tree_entry *entry;
964
965 git_array_foreach(tree->entries, i, entry) {
966 if (preorder) {
967 error = callback(path->ptr, entry, payload);
968 if (error < 0) { /* negative value stops iteration */
969 giterr_set_after_callback_function(error, "git_tree_walk");
970 break;
971 }
972 if (error > 0) { /* positive value skips this entry */
973 error = 0;
974 continue;
975 }
976 }
977
978 if (git_tree_entry__is_tree(entry)) {
979 git_tree *subtree;
980 size_t path_len = git_buf_len(path);
981
982 error = git_tree_lookup(&subtree, tree->object.repo, entry->oid);
983 if (error < 0)
984 break;
985
986 /* append the next entry to the path */
987 git_buf_puts(path, entry->filename);
988 git_buf_putc(path, '/');
989
990 if (git_buf_oom(path))
991 error = -1;
992 else
993 error = tree_walk(subtree, callback, path, payload, preorder);
994
995 git_tree_free(subtree);
996 if (error != 0)
997 break;
998
999 git_buf_truncate(path, path_len);
1000 }
1001
1002 if (!preorder) {
1003 error = callback(path->ptr, entry, payload);
1004 if (error < 0) { /* negative value stops iteration */
1005 giterr_set_after_callback_function(error, "git_tree_walk");
1006 break;
1007 }
1008 error = 0;
1009 }
1010 }
1011
1012 return error;
1013 }
1014
1015 int git_tree_walk(
1016 const git_tree *tree,
1017 git_treewalk_mode mode,
1018 git_treewalk_cb callback,
1019 void *payload)
1020 {
1021 int error = 0;
1022 git_buf root_path = GIT_BUF_INIT;
1023
1024 if (mode != GIT_TREEWALK_POST && mode != GIT_TREEWALK_PRE) {
1025 giterr_set(GITERR_INVALID, "Invalid walking mode for tree walk");
1026 return -1;
1027 }
1028
1029 error = tree_walk(
1030 tree, callback, &root_path, payload, (mode == GIT_TREEWALK_PRE));
1031
1032 git_buf_free(&root_path);
1033
1034 return error;
1035 }
1036
1037 static int compare_entries(const void *_a, const void *_b)
1038 {
1039 const git_tree_update *a = (git_tree_update *) _a;
1040 const git_tree_update *b = (git_tree_update *) _b;
1041
1042 return strcmp(a->path, b->path);
1043 }
1044
1045 static int on_dup_entry(void **old, void *new)
1046 {
1047 GIT_UNUSED(old); GIT_UNUSED(new);
1048
1049 giterr_set(GITERR_TREE, "duplicate entries given for update");
1050 return -1;
1051 }
1052
1053 /*
1054 * We keep the previous tree and the new one at each level of the
1055 * stack. When we leave a level we're done with that tree and we can
1056 * write it out to the odb.
1057 */
1058 typedef struct {
1059 git_treebuilder *bld;
1060 git_tree *tree;
1061 char *name;
1062 } tree_stack_entry;
1063
1064 /** Count how many slashes (i.e. path components) there are in this string */
1065 GIT_INLINE(size_t) count_slashes(const char *path)
1066 {
1067 size_t count = 0;
1068 const char *slash;
1069
1070 while ((slash = strchr(path, '/')) != NULL) {
1071 count++;
1072 path = slash + 1;
1073 }
1074
1075 return count;
1076 }
1077
1078 static bool next_component(git_buf *out, const char *in)
1079 {
1080 const char *slash = strchr(in, '/');
1081
1082 git_buf_clear(out);
1083
1084 if (slash)
1085 git_buf_put(out, in, slash - in);
1086
1087 return !!slash;
1088 }
1089
1090 static int create_popped_tree(tree_stack_entry *current, tree_stack_entry *popped, git_buf *component)
1091 {
1092 int error;
1093 git_oid new_tree;
1094
1095 git_tree_free(popped->tree);
1096 error = git_treebuilder_write(&new_tree, popped->bld);
1097 git_treebuilder_free(popped->bld);
1098
1099 if (error < 0) {
1100 git__free(popped->name);
1101 return error;
1102 }
1103
1104 /* We've written out the tree, now we have to put the new value into its parent */
1105 git_buf_clear(component);
1106 git_buf_puts(component, popped->name);
1107 git__free(popped->name);
1108
1109 GITERR_CHECK_ALLOC(component->ptr);
1110
1111 /* Error out if this would create a D/F conflict in this update */
1112 if (current->tree) {
1113 const git_tree_entry *to_replace;
1114 to_replace = git_tree_entry_byname(current->tree, component->ptr);
1115 if (to_replace && git_tree_entry_type(to_replace) != GIT_OBJ_TREE) {
1116 giterr_set(GITERR_TREE, "D/F conflict when updating tree");
1117 return -1;
1118 }
1119 }
1120
1121 return git_treebuilder_insert(NULL, current->bld, component->ptr, &new_tree, GIT_FILEMODE_TREE);
1122 }
1123
1124 int git_tree_create_updated(git_oid *out, git_repository *repo, git_tree *baseline, size_t nupdates, const git_tree_update *updates)
1125 {
1126 git_array_t(tree_stack_entry) stack = GIT_ARRAY_INIT;
1127 tree_stack_entry *root_elem;
1128 git_vector entries;
1129 int error;
1130 size_t i;
1131 git_buf component = GIT_BUF_INIT;
1132
1133 if ((error = git_vector_init(&entries, nupdates, compare_entries)) < 0)
1134 return error;
1135
1136 /* Sort the entries for treversal */
1137 for (i = 0 ; i < nupdates; i++) {
1138 if ((error = git_vector_insert_sorted(&entries, (void *) &updates[i], on_dup_entry)) < 0)
1139 goto cleanup;
1140 }
1141
1142 root_elem = git_array_alloc(stack);
1143 GITERR_CHECK_ALLOC(root_elem);
1144 memset(root_elem, 0, sizeof(*root_elem));
1145
1146 if (baseline && (error = git_tree_dup(&root_elem->tree, baseline)) < 0)
1147 goto cleanup;
1148
1149 if ((error = git_treebuilder_new(&root_elem->bld, repo, root_elem->tree)) < 0)
1150 goto cleanup;
1151
1152 for (i = 0; i < nupdates; i++) {
1153 const git_tree_update *last_update = i == 0 ? NULL : &updates[i-1];
1154 const git_tree_update *update = &updates[i];
1155 size_t common_prefix = 0, steps_up, j;
1156 const char *path;
1157
1158 /* Figure out how much we need to change from the previous tree */
1159 if (last_update)
1160 common_prefix = git_path_common_dirlen(last_update->path, update->path);
1161
1162 /*
1163 * The entries are sorted, so when we find we're no
1164 * longer in the same directory, we need to abandon
1165 * the old tree (steps up) and dive down to the next
1166 * one.
1167 */
1168 steps_up = last_update == NULL ? 0 : count_slashes(&last_update->path[common_prefix]);
1169
1170 for (j = 0; j < steps_up; j++) {
1171 tree_stack_entry *current, *popped = git_array_pop(stack);
1172 assert(popped);
1173
1174 current = git_array_last(stack);
1175 assert(current);
1176
1177 if ((error = create_popped_tree(current, popped, &component)) < 0)
1178 goto cleanup;
1179 }
1180
1181 /* Now that we've created the trees we popped from the stack, let's go back down */
1182 path = &update->path[common_prefix];
1183 while (next_component(&component, path)) {
1184 tree_stack_entry *last, *new_entry;
1185 const git_tree_entry *entry;
1186
1187 last = git_array_last(stack);
1188 entry = last->tree ? git_tree_entry_byname(last->tree, component.ptr) : NULL;
1189 if (entry && git_tree_entry_type(entry) != GIT_OBJ_TREE) {
1190 giterr_set(GITERR_TREE, "D/F conflict when updating tree");
1191 error = -1;
1192 goto cleanup;
1193 }
1194
1195 new_entry = git_array_alloc(stack);
1196 GITERR_CHECK_ALLOC(new_entry);
1197 memset(new_entry, 0, sizeof(*new_entry));
1198
1199 new_entry->tree = NULL;
1200 if (entry && (error = git_tree_lookup(&new_entry->tree, repo, git_tree_entry_id(entry))) < 0)
1201 goto cleanup;
1202
1203 if ((error = git_treebuilder_new(&new_entry->bld, repo, new_entry->tree)) < 0)
1204 goto cleanup;
1205
1206 new_entry->name = git__strdup(component.ptr);
1207 GITERR_CHECK_ALLOC(new_entry->name);
1208
1209 /* Get to the start of the next component */
1210 path += component.size + 1;
1211 }
1212
1213 /* After all that, we're finally at the place where we want to perform the update */
1214 switch (update->action) {
1215 case GIT_TREE_UPDATE_UPSERT:
1216 {
1217 /* Make sure we're replacing something of the same type */
1218 tree_stack_entry *last = git_array_last(stack);
1219 char *basename = git_path_basename(update->path);
1220 const git_tree_entry *e = git_treebuilder_get(last->bld, basename);
1221 if (e && git_tree_entry_type(e) != git_object__type_from_filemode(update->filemode)) {
1222 git__free(basename);
1223 giterr_set(GITERR_TREE, "Cannot replace '%s' with '%s' at '%s'",
1224 git_object_type2string(git_tree_entry_type(e)),
1225 git_object_type2string(git_object__type_from_filemode(update->filemode)),
1226 update->path);
1227 error = -1;
1228 goto cleanup;
1229 }
1230
1231 error = git_treebuilder_insert(NULL, last->bld, basename, &update->id, update->filemode);
1232 git__free(basename);
1233 break;
1234 }
1235 case GIT_TREE_UPDATE_REMOVE:
1236 {
1237 char *basename = git_path_basename(update->path);
1238 error = git_treebuilder_remove(git_array_last(stack)->bld, basename);
1239 git__free(basename);
1240 break;
1241 }
1242 default:
1243 giterr_set(GITERR_TREE, "unkown action for update");
1244 error = -1;
1245 goto cleanup;
1246 }
1247
1248 if (error < 0)
1249 goto cleanup;
1250 }
1251
1252 /* We're done, go up the stack again and write out the tree */
1253 {
1254 tree_stack_entry *current = NULL, *popped = NULL;
1255 while ((popped = git_array_pop(stack)) != NULL) {
1256 current = git_array_last(stack);
1257 /* We've reached the top, current is the root tree */
1258 if (!current)
1259 break;
1260
1261 if ((error = create_popped_tree(current, popped, &component)) < 0)
1262 goto cleanup;
1263 }
1264
1265 /* Write out the root tree */
1266 git__free(popped->name);
1267 git_tree_free(popped->tree);
1268
1269 error = git_treebuilder_write(out, popped->bld);
1270 git_treebuilder_free(popped->bld);
1271 if (error < 0)
1272 goto cleanup;
1273 }
1274
1275 cleanup:
1276 {
1277 tree_stack_entry *e;
1278 while ((e = git_array_pop(stack)) != NULL) {
1279 git_treebuilder_free(e->bld);
1280 git_tree_free(e->tree);
1281 git__free(e->name);
1282 }
1283 }
1284
1285 git_buf_free(&component);
1286 git_array_clear(stack);
1287 git_vector_free(&entries);
1288 return error;
1289 }