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