]> git.proxmox.com Git - libgit2.git/blob - src/refs.c
branch: deploy git_branch_is_head()
[libgit2.git] / src / refs.c
1 /*
2 * Copyright (C) 2009-2012 the libgit2 contributors
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 "refs.h"
9 #include "hash.h"
10 #include "repository.h"
11 #include "fileops.h"
12 #include "pack.h"
13 #include "reflog.h"
14
15 #include <git2/tag.h>
16 #include <git2/object.h>
17 #include <git2/oid.h>
18 #include <git2/branch.h>
19
20 GIT__USE_STRMAP;
21
22 #define DEFAULT_NESTING_LEVEL 5
23 #define MAX_NESTING_LEVEL 10
24
25 enum {
26 GIT_PACKREF_HAS_PEEL = 1,
27 GIT_PACKREF_WAS_LOOSE = 2
28 };
29
30 struct packref {
31 git_oid oid;
32 git_oid peel;
33 char flags;
34 char name[GIT_FLEX_ARRAY];
35 };
36
37 static int reference_read(
38 git_buf *file_content,
39 time_t *mtime,
40 const char *repo_path,
41 const char *ref_name,
42 int *updated);
43
44 /* loose refs */
45 static int loose_parse_symbolic(git_reference *ref, git_buf *file_content);
46 static int loose_parse_oid(git_oid *ref, git_buf *file_content);
47 static int loose_lookup(git_reference *ref);
48 static int loose_lookup_to_packfile(struct packref **ref_out,
49 git_repository *repo, const char *name);
50 static int loose_write(git_reference *ref);
51
52 /* packed refs */
53 static int packed_parse_peel(struct packref *tag_ref,
54 const char **buffer_out, const char *buffer_end);
55 static int packed_parse_oid(struct packref **ref_out,
56 const char **buffer_out, const char *buffer_end);
57 static int packed_load(git_repository *repo);
58 static int packed_loadloose(git_repository *repository);
59 static int packed_write_ref(struct packref *ref, git_filebuf *file);
60 static int packed_find_peel(git_repository *repo, struct packref *ref);
61 static int packed_remove_loose(git_repository *repo, git_vector *packing_list);
62 static int packed_sort(const void *a, const void *b);
63 static int packed_lookup(git_reference *ref);
64 static int packed_write(git_repository *repo);
65
66 /* internal helpers */
67 static int reference_path_available(git_repository *repo,
68 const char *ref, const char *old_ref);
69 static int reference_delete(git_reference *ref);
70 static int reference_lookup(git_reference *ref);
71
72 void git_reference_free(git_reference *reference)
73 {
74 if (reference == NULL)
75 return;
76
77 git__free(reference->name);
78 reference->name = NULL;
79
80 if (reference->flags & GIT_REF_SYMBOLIC) {
81 git__free(reference->target.symbolic);
82 reference->target.symbolic = NULL;
83 }
84
85 git__free(reference);
86 }
87
88 static int reference_alloc(
89 git_reference **ref_out,
90 git_repository *repo,
91 const char *name)
92 {
93 git_reference *reference = NULL;
94
95 assert(ref_out && repo && name);
96
97 reference = git__malloc(sizeof(git_reference));
98 GITERR_CHECK_ALLOC(reference);
99
100 memset(reference, 0x0, sizeof(git_reference));
101 reference->owner = repo;
102
103 reference->name = git__strdup(name);
104 GITERR_CHECK_ALLOC(reference->name);
105
106 *ref_out = reference;
107 return 0;
108 }
109
110 static int reference_read(
111 git_buf *file_content,
112 time_t *mtime,
113 const char *repo_path,
114 const char *ref_name,
115 int *updated)
116 {
117 git_buf path = GIT_BUF_INIT;
118 int result;
119
120 assert(file_content && repo_path && ref_name);
121
122 /* Determine the full path of the file */
123 if (git_buf_joinpath(&path, repo_path, ref_name) < 0)
124 return -1;
125
126 result = git_futils_readbuffer_updated(file_content, path.ptr, mtime, updated);
127 git_buf_free(&path);
128
129 return result;
130 }
131
132 static int loose_parse_symbolic(git_reference *ref, git_buf *file_content)
133 {
134 const unsigned int header_len = (unsigned int)strlen(GIT_SYMREF);
135 const char *refname_start;
136
137 refname_start = (const char *)file_content->ptr;
138
139 if (git_buf_len(file_content) < header_len + 1) {
140 giterr_set(GITERR_REFERENCE, "Corrupted loose reference file");
141 return -1;
142 }
143
144 /*
145 * Assume we have already checked for the header
146 * before calling this function
147 */
148 refname_start += header_len;
149
150 ref->target.symbolic = git__strdup(refname_start);
151 GITERR_CHECK_ALLOC(ref->target.symbolic);
152
153 return 0;
154 }
155
156 static int loose_parse_oid(git_oid *oid, git_buf *file_content)
157 {
158 /* File format: 40 chars (OID) */
159 if (git_buf_len(file_content) == GIT_OID_HEXSZ &&
160 git_oid_fromstr(oid, git_buf_cstr(file_content)) == 0)
161 return 0;
162
163 giterr_set(GITERR_REFERENCE, "Corrupted loose reference file");
164 return -1;
165 }
166
167 static git_ref_t loose_guess_rtype(const git_buf *full_path)
168 {
169 git_buf ref_file = GIT_BUF_INIT;
170 git_ref_t type;
171
172 type = GIT_REF_INVALID;
173
174 if (git_futils_readbuffer(&ref_file, full_path->ptr) == 0) {
175 if (git__prefixcmp((const char *)(ref_file.ptr), GIT_SYMREF) == 0)
176 type = GIT_REF_SYMBOLIC;
177 else
178 type = GIT_REF_OID;
179 }
180
181 git_buf_free(&ref_file);
182 return type;
183 }
184
185 static int loose_lookup(git_reference *ref)
186 {
187 int result, updated;
188 git_buf ref_file = GIT_BUF_INIT;
189
190 result = reference_read(&ref_file, &ref->mtime,
191 ref->owner->path_repository, ref->name, &updated);
192
193 if (result < 0)
194 return result;
195
196 if (!updated)
197 return 0;
198
199 git_buf_rtrim(&ref_file);
200
201 if (ref->flags & GIT_REF_SYMBOLIC) {
202 git__free(ref->target.symbolic);
203 ref->target.symbolic = NULL;
204 }
205
206 ref->flags = 0;
207
208 if (git__prefixcmp((const char *)(ref_file.ptr), GIT_SYMREF) == 0) {
209 ref->flags |= GIT_REF_SYMBOLIC;
210 result = loose_parse_symbolic(ref, &ref_file);
211 } else {
212 ref->flags |= GIT_REF_OID;
213 result = loose_parse_oid(&ref->target.oid, &ref_file);
214 }
215
216 git_buf_free(&ref_file);
217 return result;
218 }
219
220 static int loose_lookup_to_packfile(
221 struct packref **ref_out,
222 git_repository *repo,
223 const char *name)
224 {
225 git_buf ref_file = GIT_BUF_INIT;
226 struct packref *ref = NULL;
227 size_t name_len;
228
229 *ref_out = NULL;
230
231 if (reference_read(&ref_file, NULL, repo->path_repository, name, NULL) < 0)
232 return -1;
233
234 git_buf_rtrim(&ref_file);
235
236 name_len = strlen(name);
237 ref = git__malloc(sizeof(struct packref) + name_len + 1);
238 GITERR_CHECK_ALLOC(ref);
239
240 memcpy(ref->name, name, name_len);
241 ref->name[name_len] = 0;
242
243 if (loose_parse_oid(&ref->oid, &ref_file) < 0) {
244 git_buf_free(&ref_file);
245 git__free(ref);
246 return -1;
247 }
248
249 ref->flags = GIT_PACKREF_WAS_LOOSE;
250
251 *ref_out = ref;
252 git_buf_free(&ref_file);
253 return 0;
254 }
255
256 static int loose_write(git_reference *ref)
257 {
258 git_filebuf file = GIT_FILEBUF_INIT;
259 git_buf ref_path = GIT_BUF_INIT;
260 struct stat st;
261
262 if (git_buf_joinpath(&ref_path, ref->owner->path_repository, ref->name) < 0)
263 return -1;
264
265 /* Remove a possibly existing empty directory hierarchy
266 * which name would collide with the reference name
267 */
268 if (git_path_isdir(git_buf_cstr(&ref_path)) &&
269 (git_futils_rmdir_r(git_buf_cstr(&ref_path), GIT_DIRREMOVAL_ONLY_EMPTY_DIRS) < 0)) {
270 git_buf_free(&ref_path);
271 return -1;
272 }
273
274 if (git_filebuf_open(&file, ref_path.ptr, GIT_FILEBUF_FORCE) < 0) {
275 git_buf_free(&ref_path);
276 return -1;
277 }
278
279 git_buf_free(&ref_path);
280
281 if (ref->flags & GIT_REF_OID) {
282 char oid[GIT_OID_HEXSZ + 1];
283
284 git_oid_fmt(oid, &ref->target.oid);
285 oid[GIT_OID_HEXSZ] = '\0';
286
287 git_filebuf_printf(&file, "%s\n", oid);
288
289 } else if (ref->flags & GIT_REF_SYMBOLIC) {
290 git_filebuf_printf(&file, GIT_SYMREF "%s\n", ref->target.symbolic);
291 } else {
292 assert(0); /* don't let this happen */
293 }
294
295 if (p_stat(ref_path.ptr, &st) == 0)
296 ref->mtime = st.st_mtime;
297
298 return git_filebuf_commit(&file, GIT_REFS_FILE_MODE);
299 }
300
301 static int packed_parse_peel(
302 struct packref *tag_ref,
303 const char **buffer_out,
304 const char *buffer_end)
305 {
306 const char *buffer = *buffer_out + 1;
307
308 assert(buffer[-1] == '^');
309
310 /* Ensure it's not the first entry of the file */
311 if (tag_ref == NULL)
312 goto corrupt;
313
314 /* Ensure reference is a tag */
315 if (git__prefixcmp(tag_ref->name, GIT_REFS_TAGS_DIR) != 0)
316 goto corrupt;
317
318 if (buffer + GIT_OID_HEXSZ >= buffer_end)
319 goto corrupt;
320
321 /* Is this a valid object id? */
322 if (git_oid_fromstr(&tag_ref->peel, buffer) < 0)
323 goto corrupt;
324
325 buffer = buffer + GIT_OID_HEXSZ;
326 if (*buffer == '\r')
327 buffer++;
328
329 if (*buffer != '\n')
330 goto corrupt;
331
332 *buffer_out = buffer + 1;
333 return 0;
334
335 corrupt:
336 giterr_set(GITERR_REFERENCE, "The packed references file is corrupted");
337 return -1;
338 }
339
340 static int packed_parse_oid(
341 struct packref **ref_out,
342 const char **buffer_out,
343 const char *buffer_end)
344 {
345 struct packref *ref = NULL;
346
347 const char *buffer = *buffer_out;
348 const char *refname_begin, *refname_end;
349
350 size_t refname_len;
351 git_oid id;
352
353 refname_begin = (buffer + GIT_OID_HEXSZ + 1);
354 if (refname_begin >= buffer_end || refname_begin[-1] != ' ')
355 goto corrupt;
356
357 /* Is this a valid object id? */
358 if (git_oid_fromstr(&id, buffer) < 0)
359 goto corrupt;
360
361 refname_end = memchr(refname_begin, '\n', buffer_end - refname_begin);
362 if (refname_end == NULL)
363 goto corrupt;
364
365 if (refname_end[-1] == '\r')
366 refname_end--;
367
368 refname_len = refname_end - refname_begin;
369
370 ref = git__malloc(sizeof(struct packref) + refname_len + 1);
371 GITERR_CHECK_ALLOC(ref);
372
373 memcpy(ref->name, refname_begin, refname_len);
374 ref->name[refname_len] = 0;
375
376 git_oid_cpy(&ref->oid, &id);
377
378 ref->flags = 0;
379
380 *ref_out = ref;
381 *buffer_out = refname_end + 1;
382
383 return 0;
384
385 corrupt:
386 git__free(ref);
387 giterr_set(GITERR_REFERENCE, "The packed references file is corrupted");
388 return -1;
389 }
390
391 static int packed_load(git_repository *repo)
392 {
393 int result, updated;
394 git_buf packfile = GIT_BUF_INIT;
395 const char *buffer_start, *buffer_end;
396 git_refcache *ref_cache = &repo->references;
397
398 /* First we make sure we have allocated the hash table */
399 if (ref_cache->packfile == NULL) {
400 ref_cache->packfile = git_strmap_alloc();
401 GITERR_CHECK_ALLOC(ref_cache->packfile);
402 }
403
404 result = reference_read(&packfile, &ref_cache->packfile_time,
405 repo->path_repository, GIT_PACKEDREFS_FILE, &updated);
406
407 /*
408 * If we couldn't find the file, we need to clear the table and
409 * return. On any other error, we return that error. If everything
410 * went fine and the file wasn't updated, then there's nothing new
411 * for us here, so just return. Anything else means we need to
412 * refresh the packed refs.
413 */
414 if (result == GIT_ENOTFOUND) {
415 git_strmap_clear(ref_cache->packfile);
416 return 0;
417 }
418
419 if (result < 0)
420 return -1;
421
422 if (!updated)
423 return 0;
424
425 /*
426 * At this point, we want to refresh the packed refs. We already
427 * have the contents in our buffer.
428 */
429 git_strmap_clear(ref_cache->packfile);
430
431 buffer_start = (const char *)packfile.ptr;
432 buffer_end = (const char *)(buffer_start) + packfile.size;
433
434 while (buffer_start < buffer_end && buffer_start[0] == '#') {
435 buffer_start = strchr(buffer_start, '\n');
436 if (buffer_start == NULL)
437 goto parse_failed;
438
439 buffer_start++;
440 }
441
442 while (buffer_start < buffer_end) {
443 int err;
444 struct packref *ref = NULL;
445
446 if (packed_parse_oid(&ref, &buffer_start, buffer_end) < 0)
447 goto parse_failed;
448
449 if (buffer_start[0] == '^') {
450 if (packed_parse_peel(ref, &buffer_start, buffer_end) < 0)
451 goto parse_failed;
452 }
453
454 git_strmap_insert(ref_cache->packfile, ref->name, ref, err);
455 if (err < 0)
456 goto parse_failed;
457 }
458
459 git_buf_free(&packfile);
460 return 0;
461
462 parse_failed:
463 git_strmap_free(ref_cache->packfile);
464 ref_cache->packfile = NULL;
465 git_buf_free(&packfile);
466 return -1;
467 }
468
469
470 struct dirent_list_data {
471 git_repository *repo;
472 size_t repo_path_len;
473 unsigned int list_flags;
474
475 int (*callback)(const char *, void *);
476 void *callback_payload;
477 int callback_error;
478 };
479
480 static int _dirent_loose_listall(void *_data, git_buf *full_path)
481 {
482 struct dirent_list_data *data = (struct dirent_list_data *)_data;
483 const char *file_path = full_path->ptr + data->repo_path_len;
484
485 if (git_path_isdir(full_path->ptr) == true)
486 return git_path_direach(full_path, _dirent_loose_listall, _data);
487
488 /* do not add twice a reference that exists already in the packfile */
489 if ((data->list_flags & GIT_REF_PACKED) != 0 &&
490 git_strmap_exists(data->repo->references.packfile, file_path))
491 return 0;
492
493 if (data->list_flags != GIT_REF_LISTALL) {
494 if ((data->list_flags & loose_guess_rtype(full_path)) == 0)
495 return 0; /* we are filtering out this reference */
496 }
497
498 /* Locked references aren't returned */
499 if (!git__suffixcmp(file_path, GIT_FILELOCK_EXTENSION))
500 return 0;
501
502 if (data->callback(file_path, data->callback_payload))
503 data->callback_error = GIT_EUSER;
504
505 return data->callback_error;
506 }
507
508 static int _dirent_loose_load(void *data, git_buf *full_path)
509 {
510 git_repository *repository = (git_repository *)data;
511 void *old_ref = NULL;
512 struct packref *ref;
513 const char *file_path;
514 int err;
515
516 if (git_path_isdir(full_path->ptr) == true)
517 return git_path_direach(full_path, _dirent_loose_load, repository);
518
519 file_path = full_path->ptr + strlen(repository->path_repository);
520
521 if (loose_lookup_to_packfile(&ref, repository, file_path) < 0)
522 return -1;
523
524 git_strmap_insert2(
525 repository->references.packfile, ref->name, ref, old_ref, err);
526 if (err < 0) {
527 git__free(ref);
528 return -1;
529 }
530
531 git__free(old_ref);
532 return 0;
533 }
534
535 /*
536 * Load all the loose references from the repository
537 * into the in-memory Packfile, and build a vector with
538 * all the references so it can be written back to
539 * disk.
540 */
541 static int packed_loadloose(git_repository *repository)
542 {
543 git_buf refs_path = GIT_BUF_INIT;
544 int result;
545
546 /* the packfile must have been previously loaded! */
547 assert(repository->references.packfile);
548
549 if (git_buf_joinpath(&refs_path, repository->path_repository, GIT_REFS_DIR) < 0)
550 return -1;
551
552 /*
553 * Load all the loose files from disk into the Packfile table.
554 * This will overwrite any old packed entries with their
555 * updated loose versions
556 */
557 result = git_path_direach(&refs_path, _dirent_loose_load, repository);
558 git_buf_free(&refs_path);
559
560 return result;
561 }
562
563 /*
564 * Write a single reference into a packfile
565 */
566 static int packed_write_ref(struct packref *ref, git_filebuf *file)
567 {
568 char oid[GIT_OID_HEXSZ + 1];
569
570 git_oid_fmt(oid, &ref->oid);
571 oid[GIT_OID_HEXSZ] = 0;
572
573 /*
574 * For references that peel to an object in the repo, we must
575 * write the resulting peel on a separate line, e.g.
576 *
577 * 6fa8a902cc1d18527e1355773c86721945475d37 refs/tags/libgit2-0.4
578 * ^2ec0cb7959b0bf965d54f95453f5b4b34e8d3100
579 *
580 * This obviously only applies to tags.
581 * The required peels have already been loaded into `ref->peel_target`.
582 */
583 if (ref->flags & GIT_PACKREF_HAS_PEEL) {
584 char peel[GIT_OID_HEXSZ + 1];
585 git_oid_fmt(peel, &ref->peel);
586 peel[GIT_OID_HEXSZ] = 0;
587
588 if (git_filebuf_printf(file, "%s %s\n^%s\n", oid, ref->name, peel) < 0)
589 return -1;
590 } else {
591 if (git_filebuf_printf(file, "%s %s\n", oid, ref->name) < 0)
592 return -1;
593 }
594
595 return 0;
596 }
597
598 /*
599 * Find out what object this reference resolves to.
600 *
601 * For references that point to a 'big' tag (e.g. an
602 * actual tag object on the repository), we need to
603 * cache on the packfile the OID of the object to
604 * which that 'big tag' is pointing to.
605 */
606 static int packed_find_peel(git_repository *repo, struct packref *ref)
607 {
608 git_object *object;
609
610 if (ref->flags & GIT_PACKREF_HAS_PEEL)
611 return 0;
612
613 /*
614 * Only applies to tags, i.e. references
615 * in the /refs/tags folder
616 */
617 if (git__prefixcmp(ref->name, GIT_REFS_TAGS_DIR) != 0)
618 return 0;
619
620 /*
621 * Find the tagged object in the repository
622 */
623 if (git_object_lookup(&object, repo, &ref->oid, GIT_OBJ_ANY) < 0)
624 return -1;
625
626 /*
627 * If the tagged object is a Tag object, we need to resolve it;
628 * if the ref is actually a 'weak' ref, we don't need to resolve
629 * anything.
630 */
631 if (git_object_type(object) == GIT_OBJ_TAG) {
632 git_tag *tag = (git_tag *)object;
633
634 /*
635 * Find the object pointed at by this tag
636 */
637 git_oid_cpy(&ref->peel, git_tag_target_oid(tag));
638 ref->flags |= GIT_PACKREF_HAS_PEEL;
639
640 /*
641 * The reference has now cached the resolved OID, and is
642 * marked at such. When written to the packfile, it'll be
643 * accompanied by this resolved oid
644 */
645 }
646
647 git_object_free(object);
648 return 0;
649 }
650
651 /*
652 * Remove all loose references
653 *
654 * Once we have successfully written a packfile,
655 * all the loose references that were packed must be
656 * removed from disk.
657 *
658 * This is a dangerous method; make sure the packfile
659 * is well-written, because we are destructing references
660 * here otherwise.
661 */
662 static int packed_remove_loose(git_repository *repo, git_vector *packing_list)
663 {
664 unsigned int i;
665 git_buf full_path = GIT_BUF_INIT;
666 int failed = 0;
667
668 for (i = 0; i < packing_list->length; ++i) {
669 struct packref *ref = git_vector_get(packing_list, i);
670
671 if ((ref->flags & GIT_PACKREF_WAS_LOOSE) == 0)
672 continue;
673
674 if (git_buf_joinpath(&full_path, repo->path_repository, ref->name) < 0)
675 return -1; /* critical; do not try to recover on oom */
676
677 if (git_path_exists(full_path.ptr) == true && p_unlink(full_path.ptr) < 0) {
678 if (failed)
679 continue;
680
681 giterr_set(GITERR_REFERENCE,
682 "Failed to remove loose reference '%s' after packing: %s",
683 full_path.ptr, strerror(errno));
684
685 failed = 1;
686 }
687
688 /*
689 * if we fail to remove a single file, this is *not* good,
690 * but we should keep going and remove as many as possible.
691 * After we've removed as many files as possible, we return
692 * the error code anyway.
693 */
694 }
695
696 git_buf_free(&full_path);
697 return failed ? -1 : 0;
698 }
699
700 static int packed_sort(const void *a, const void *b)
701 {
702 const struct packref *ref_a = (const struct packref *)a;
703 const struct packref *ref_b = (const struct packref *)b;
704
705 return strcmp(ref_a->name, ref_b->name);
706 }
707
708 /*
709 * Write all the contents in the in-memory packfile to disk.
710 */
711 static int packed_write(git_repository *repo)
712 {
713 git_filebuf pack_file = GIT_FILEBUF_INIT;
714 unsigned int i;
715 git_buf pack_file_path = GIT_BUF_INIT;
716 git_vector packing_list;
717 unsigned int total_refs;
718
719 assert(repo && repo->references.packfile);
720
721 total_refs =
722 (unsigned int)git_strmap_num_entries(repo->references.packfile);
723
724 if (git_vector_init(&packing_list, total_refs, packed_sort) < 0)
725 return -1;
726
727 /* Load all the packfile into a vector */
728 {
729 struct packref *reference;
730
731 /* cannot fail: vector already has the right size */
732 git_strmap_foreach_value(repo->references.packfile, reference, {
733 git_vector_insert(&packing_list, reference);
734 });
735 }
736
737 /* sort the vector so the entries appear sorted on the packfile */
738 git_vector_sort(&packing_list);
739
740 /* Now we can open the file! */
741 if (git_buf_joinpath(&pack_file_path, repo->path_repository, GIT_PACKEDREFS_FILE) < 0)
742 goto cleanup_memory;
743
744 if (git_filebuf_open(&pack_file, pack_file_path.ptr, 0) < 0)
745 goto cleanup_packfile;
746
747 /* Packfiles have a header... apparently
748 * This is in fact not required, but we might as well print it
749 * just for kicks */
750 if (git_filebuf_printf(&pack_file, "%s\n", GIT_PACKEDREFS_HEADER) < 0)
751 goto cleanup_packfile;
752
753 for (i = 0; i < packing_list.length; ++i) {
754 struct packref *ref = (struct packref *)git_vector_get(&packing_list, i);
755
756 if (packed_find_peel(repo, ref) < 0)
757 goto cleanup_packfile;
758
759 if (packed_write_ref(ref, &pack_file) < 0)
760 goto cleanup_packfile;
761 }
762
763 /* if we've written all the references properly, we can commit
764 * the packfile to make the changes effective */
765 if (git_filebuf_commit(&pack_file, GIT_PACKEDREFS_FILE_MODE) < 0)
766 goto cleanup_memory;
767
768 /* when and only when the packfile has been properly written,
769 * we can go ahead and remove the loose refs */
770 if (packed_remove_loose(repo, &packing_list) < 0)
771 goto cleanup_memory;
772
773 {
774 struct stat st;
775 if (p_stat(pack_file_path.ptr, &st) == 0)
776 repo->references.packfile_time = st.st_mtime;
777 }
778
779 git_vector_free(&packing_list);
780 git_buf_free(&pack_file_path);
781
782 /* we're good now */
783 return 0;
784
785 cleanup_packfile:
786 git_filebuf_cleanup(&pack_file);
787
788 cleanup_memory:
789 git_vector_free(&packing_list);
790 git_buf_free(&pack_file_path);
791
792 return -1;
793 }
794
795 struct reference_available_t {
796 const char *new_ref;
797 const char *old_ref;
798 int available;
799 };
800
801 static int _reference_available_cb(const char *ref, void *data)
802 {
803 struct reference_available_t *d;
804
805 assert(ref && data);
806 d = (struct reference_available_t *)data;
807
808 if (!d->old_ref || strcmp(d->old_ref, ref)) {
809 size_t reflen = strlen(ref);
810 size_t newlen = strlen(d->new_ref);
811 size_t cmplen = reflen < newlen ? reflen : newlen;
812 const char *lead = reflen < newlen ? d->new_ref : ref;
813
814 if (!strncmp(d->new_ref, ref, cmplen) && lead[cmplen] == '/') {
815 d->available = 0;
816 return -1;
817 }
818 }
819
820 return 0;
821 }
822
823 static int reference_path_available(
824 git_repository *repo,
825 const char *ref,
826 const char* old_ref)
827 {
828 int error;
829 struct reference_available_t data;
830
831 data.new_ref = ref;
832 data.old_ref = old_ref;
833 data.available = 1;
834
835 error = git_reference_foreach(
836 repo, GIT_REF_LISTALL, _reference_available_cb, (void *)&data);
837 if (error < 0)
838 return error;
839
840 if (!data.available) {
841 giterr_set(GITERR_REFERENCE,
842 "The path to reference '%s' collides with an existing one", ref);
843 return -1;
844 }
845
846 return 0;
847 }
848
849 static int reference_exists(int *exists, git_repository *repo, const char *ref_name)
850 {
851 git_buf ref_path = GIT_BUF_INIT;
852
853 if (packed_load(repo) < 0)
854 return -1;
855
856 if (git_buf_joinpath(&ref_path, repo->path_repository, ref_name) < 0)
857 return -1;
858
859 if (git_path_isfile(ref_path.ptr) == true ||
860 git_strmap_exists(repo->references.packfile, ref_path.ptr))
861 {
862 *exists = 1;
863 } else {
864 *exists = 0;
865 }
866
867 git_buf_free(&ref_path);
868 return 0;
869 }
870
871 /*
872 * Check if a reference could be written to disk, based on:
873 *
874 * - Whether a reference with the same name already exists,
875 * and we are allowing or disallowing overwrites
876 *
877 * - Whether the name of the reference would collide with
878 * an existing path
879 */
880 static int reference_can_write(
881 git_repository *repo,
882 const char *refname,
883 const char *previous_name,
884 int force)
885 {
886 /* see if the reference shares a path with an existing reference;
887 * if a path is shared, we cannot create the reference, even when forcing */
888 if (reference_path_available(repo, refname, previous_name) < 0)
889 return -1;
890
891 /* check if the reference actually exists, but only if we are not forcing
892 * the rename. If we are forcing, it's OK to overwrite */
893 if (!force) {
894 int exists;
895
896 if (reference_exists(&exists, repo, refname) < 0)
897 return -1;
898
899 /* We cannot proceed if the reference already exists and we're not forcing
900 * the rename; the existing one would be overwritten */
901 if (exists) {
902 giterr_set(GITERR_REFERENCE,
903 "A reference with that name (%s) already exists", refname);
904 return GIT_EEXISTS;
905 }
906 }
907
908 /* FIXME: if the reference exists and we are forcing, do we really need to
909 * remove the reference first?
910 *
911 * Two cases:
912 *
913 * - the reference already exists and is loose: not a problem, the file
914 * gets overwritten on disk
915 *
916 * - the reference already exists and is packed: we write a new one as
917 * loose, which by all means renders the packed one useless
918 */
919
920 return 0;
921 }
922
923
924 static int packed_lookup(git_reference *ref)
925 {
926 struct packref *pack_ref = NULL;
927 git_strmap *packfile_refs;
928 khiter_t pos;
929
930 if (packed_load(ref->owner) < 0)
931 return -1;
932
933 /* maybe the packfile hasn't changed at all, so we don't
934 * have to re-lookup the reference */
935 if ((ref->flags & GIT_REF_PACKED) &&
936 ref->mtime == ref->owner->references.packfile_time)
937 return 0;
938
939 if (ref->flags & GIT_REF_SYMBOLIC) {
940 git__free(ref->target.symbolic);
941 ref->target.symbolic = NULL;
942 }
943
944 /* Look up on the packfile */
945 packfile_refs = ref->owner->references.packfile;
946 pos = git_strmap_lookup_index(packfile_refs, ref->name);
947 if (!git_strmap_valid_index(packfile_refs, pos)) {
948 giterr_set(GITERR_REFERENCE, "Reference '%s' not found", ref->name);
949 return GIT_ENOTFOUND;
950 }
951
952 pack_ref = git_strmap_value_at(packfile_refs, pos);
953
954 ref->flags = GIT_REF_OID | GIT_REF_PACKED;
955 ref->mtime = ref->owner->references.packfile_time;
956 git_oid_cpy(&ref->target.oid, &pack_ref->oid);
957
958 return 0;
959 }
960
961 static int reference_lookup(git_reference *ref)
962 {
963 int result;
964
965 result = loose_lookup(ref);
966 if (result == 0)
967 return 0;
968
969 /* only try to lookup this reference on the packfile if it
970 * wasn't found on the loose refs; not if there was a critical error */
971 if (result == GIT_ENOTFOUND) {
972 giterr_clear();
973 result = packed_lookup(ref);
974 if (result == 0)
975 return 0;
976 }
977
978 /* unexpected error; free the reference */
979 git_reference_free(ref);
980 return result;
981 }
982
983 /*
984 * Delete a reference.
985 * This is an internal method; the reference is removed
986 * from disk or the packfile, but the pointer is not freed
987 */
988 static int reference_delete(git_reference *ref)
989 {
990 int result;
991
992 assert(ref);
993
994 /* If the reference is packed, this is an expensive operation.
995 * We need to reload the packfile, remove the reference from the
996 * packing list, and repack */
997 if (ref->flags & GIT_REF_PACKED) {
998 git_strmap *packfile_refs;
999 struct packref *packref;
1000 khiter_t pos;
1001
1002 /* load the existing packfile */
1003 if (packed_load(ref->owner) < 0)
1004 return -1;
1005
1006 packfile_refs = ref->owner->references.packfile;
1007 pos = git_strmap_lookup_index(packfile_refs, ref->name);
1008 if (!git_strmap_valid_index(packfile_refs, pos)) {
1009 giterr_set(GITERR_REFERENCE,
1010 "Reference %s stopped existing in the packfile", ref->name);
1011 return -1;
1012 }
1013
1014 packref = git_strmap_value_at(packfile_refs, pos);
1015 git_strmap_delete_at(packfile_refs, pos);
1016
1017 git__free(packref);
1018 if (packed_write(ref->owner) < 0)
1019 return -1;
1020
1021 /* If the reference is loose, we can just remove the reference
1022 * from the filesystem */
1023 } else {
1024 git_reference *ref_in_pack;
1025 git_buf full_path = GIT_BUF_INIT;
1026
1027 if (git_buf_joinpath(&full_path, ref->owner->path_repository, ref->name) < 0)
1028 return -1;
1029
1030 result = p_unlink(full_path.ptr);
1031 git_buf_free(&full_path); /* done with path at this point */
1032
1033 if (result < 0) {
1034 giterr_set(GITERR_OS, "Failed to unlink '%s'", full_path.ptr);
1035 return -1;
1036 }
1037
1038 /* When deleting a loose reference, we have to ensure that an older
1039 * packed version of it doesn't exist */
1040 if (git_reference_lookup(&ref_in_pack, ref->owner, ref->name) == 0) {
1041 assert((ref_in_pack->flags & GIT_REF_PACKED) != 0);
1042 return git_reference_delete(ref_in_pack);
1043 }
1044
1045 giterr_clear();
1046 }
1047
1048 return 0;
1049 }
1050
1051 int git_reference_delete(git_reference *ref)
1052 {
1053 int result = reference_delete(ref);
1054 git_reference_free(ref);
1055 return result;
1056 }
1057
1058 int git_reference_lookup(git_reference **ref_out,
1059 git_repository *repo, const char *name)
1060 {
1061 return git_reference_lookup_resolved(ref_out, repo, name, 0);
1062 }
1063
1064 int git_reference_name_to_oid(
1065 git_oid *out, git_repository *repo, const char *name)
1066 {
1067 int error;
1068 git_reference *ref;
1069
1070 if ((error = git_reference_lookup_resolved(&ref, repo, name, -1)) < 0)
1071 return error;
1072
1073 git_oid_cpy(out, git_reference_oid(ref));
1074 git_reference_free(ref);
1075 return 0;
1076 }
1077
1078 int git_reference_lookup_resolved(
1079 git_reference **ref_out,
1080 git_repository *repo,
1081 const char *name,
1082 int max_nesting)
1083 {
1084 git_reference *scan;
1085 int result, nesting;
1086
1087 assert(ref_out && repo && name);
1088
1089 *ref_out = NULL;
1090
1091 if (max_nesting > MAX_NESTING_LEVEL)
1092 max_nesting = MAX_NESTING_LEVEL;
1093 else if (max_nesting < 0)
1094 max_nesting = DEFAULT_NESTING_LEVEL;
1095
1096 scan = git__calloc(1, sizeof(git_reference));
1097 GITERR_CHECK_ALLOC(scan);
1098
1099 scan->name = git__calloc(GIT_REFNAME_MAX + 1, sizeof(char));
1100 GITERR_CHECK_ALLOC(scan->name);
1101
1102 if ((result = git_reference__normalize_name_lax(
1103 scan->name,
1104 GIT_REFNAME_MAX,
1105 name)) < 0) {
1106 git_reference_free(scan);
1107 return result;
1108 }
1109
1110 scan->target.symbolic = git__strdup(scan->name);
1111 GITERR_CHECK_ALLOC(scan->target.symbolic);
1112
1113 scan->owner = repo;
1114 scan->flags = GIT_REF_SYMBOLIC;
1115
1116 for (nesting = max_nesting;
1117 nesting >= 0 && (scan->flags & GIT_REF_SYMBOLIC) != 0;
1118 nesting--)
1119 {
1120 if (nesting != max_nesting)
1121 strncpy(scan->name, scan->target.symbolic, GIT_REFNAME_MAX);
1122
1123 scan->mtime = 0;
1124
1125 if ((result = reference_lookup(scan)) < 0)
1126 return result; /* lookup git_reference_free on scan already */
1127 }
1128
1129 if ((scan->flags & GIT_REF_OID) == 0 && max_nesting != 0) {
1130 giterr_set(GITERR_REFERENCE,
1131 "Cannot resolve reference (>%u levels deep)", max_nesting);
1132 git_reference_free(scan);
1133 return -1;
1134 }
1135
1136 *ref_out = scan;
1137 return 0;
1138 }
1139
1140 /**
1141 * Getters
1142 */
1143 git_ref_t git_reference_type(git_reference *ref)
1144 {
1145 assert(ref);
1146
1147 if (ref->flags & GIT_REF_OID)
1148 return GIT_REF_OID;
1149
1150 if (ref->flags & GIT_REF_SYMBOLIC)
1151 return GIT_REF_SYMBOLIC;
1152
1153 return GIT_REF_INVALID;
1154 }
1155
1156 int git_reference_is_packed(git_reference *ref)
1157 {
1158 assert(ref);
1159 return !!(ref->flags & GIT_REF_PACKED);
1160 }
1161
1162 const char *git_reference_name(git_reference *ref)
1163 {
1164 assert(ref);
1165 return ref->name;
1166 }
1167
1168 git_repository *git_reference_owner(git_reference *ref)
1169 {
1170 assert(ref);
1171 return ref->owner;
1172 }
1173
1174 const git_oid *git_reference_oid(git_reference *ref)
1175 {
1176 assert(ref);
1177
1178 if ((ref->flags & GIT_REF_OID) == 0)
1179 return NULL;
1180
1181 return &ref->target.oid;
1182 }
1183
1184 const char *git_reference_target(git_reference *ref)
1185 {
1186 assert(ref);
1187
1188 if ((ref->flags & GIT_REF_SYMBOLIC) == 0)
1189 return NULL;
1190
1191 return ref->target.symbolic;
1192 }
1193
1194 int git_reference_create_symbolic(
1195 git_reference **ref_out,
1196 git_repository *repo,
1197 const char *name,
1198 const char *target,
1199 int force)
1200 {
1201 char normalized[GIT_REFNAME_MAX];
1202 git_reference *ref = NULL;
1203 int error;
1204
1205 if (git_reference__normalize_name_lax(
1206 normalized,
1207 sizeof(normalized),
1208 name) < 0)
1209 return -1;
1210
1211 if ((error = reference_can_write(repo, normalized, NULL, force)) < 0)
1212 return error;
1213
1214 if (reference_alloc(&ref, repo, normalized) < 0)
1215 return -1;
1216
1217 ref->flags |= GIT_REF_SYMBOLIC;
1218
1219 /* set the target; this will normalize the name automatically
1220 * and write the reference on disk */
1221 if (git_reference_set_target(ref, target) < 0) {
1222 git_reference_free(ref);
1223 return -1;
1224 }
1225 if (ref_out == NULL) {
1226 git_reference_free(ref);
1227 } else {
1228 *ref_out = ref;
1229 }
1230
1231 return 0;
1232 }
1233
1234 int git_reference_create_oid(
1235 git_reference **ref_out,
1236 git_repository *repo,
1237 const char *name,
1238 const git_oid *id,
1239 int force)
1240 {
1241 int error;
1242 git_reference *ref = NULL;
1243 char normalized[GIT_REFNAME_MAX];
1244
1245 if (git_reference__normalize_name_lax(
1246 normalized,
1247 sizeof(normalized),
1248 name) < 0)
1249 return -1;
1250
1251 if ((error = reference_can_write(repo, normalized, NULL, force)) < 0)
1252 return error;
1253
1254 if (reference_alloc(&ref, repo, name) < 0)
1255 return -1;
1256
1257 ref->flags |= GIT_REF_OID;
1258
1259 /* set the oid; this will write the reference on disk */
1260 if (git_reference_set_oid(ref, id) < 0) {
1261 git_reference_free(ref);
1262 return -1;
1263 }
1264
1265 if (ref_out == NULL) {
1266 git_reference_free(ref);
1267 } else {
1268 *ref_out = ref;
1269 }
1270
1271 return 0;
1272 }
1273 /*
1274 * Change the OID target of a reference.
1275 *
1276 * For both loose and packed references, just change
1277 * the oid in memory and (over)write the file in disk.
1278 *
1279 * We do not repack packed references because of performance
1280 * reasons.
1281 */
1282 int git_reference_set_oid(git_reference *ref, const git_oid *id)
1283 {
1284 git_odb *odb = NULL;
1285
1286 if ((ref->flags & GIT_REF_OID) == 0) {
1287 giterr_set(GITERR_REFERENCE, "Cannot set OID on symbolic reference");
1288 return -1;
1289 }
1290
1291 assert(ref->owner);
1292
1293 if (git_repository_odb__weakptr(&odb, ref->owner) < 0)
1294 return -1;
1295
1296 /* Don't let the user create references to OIDs that
1297 * don't exist in the ODB */
1298 if (!git_odb_exists(odb, id)) {
1299 giterr_set(GITERR_REFERENCE,
1300 "Target OID for the reference doesn't exist on the repository");
1301 return -1;
1302 }
1303
1304 /* Update the OID value on `ref` */
1305 git_oid_cpy(&ref->target.oid, id);
1306
1307 /* Write back to disk */
1308 return loose_write(ref);
1309 }
1310
1311 /*
1312 * Change the target of a symbolic reference.
1313 *
1314 * This is easy because symrefs cannot be inside
1315 * a pack. We just change the target in memory
1316 * and overwrite the file on disk.
1317 */
1318 int git_reference_set_target(git_reference *ref, const char *target)
1319 {
1320 char normalized[GIT_REFNAME_MAX];
1321
1322 if ((ref->flags & GIT_REF_SYMBOLIC) == 0) {
1323 giterr_set(GITERR_REFERENCE,
1324 "Cannot set symbolic target on a direct reference");
1325 return -1;
1326 }
1327
1328 if (git_reference__normalize_name_lax(
1329 normalized,
1330 sizeof(normalized),
1331 target))
1332 return -1;
1333
1334 git__free(ref->target.symbolic);
1335 ref->target.symbolic = git__strdup(normalized);
1336 GITERR_CHECK_ALLOC(ref->target.symbolic);
1337
1338 return loose_write(ref);
1339 }
1340
1341 int git_reference_rename(git_reference *ref, const char *new_name, int force)
1342 {
1343 int result;
1344 unsigned int normalization_flags;
1345 git_buf aux_path = GIT_BUF_INIT;
1346 char normalized[GIT_REFNAME_MAX];
1347 bool should_head_be_updated = false;
1348
1349 normalization_flags = ref->flags & GIT_REF_SYMBOLIC ?
1350 GIT_REF_FORMAT_ALLOW_ONELEVEL
1351 : GIT_REF_FORMAT_NORMAL;
1352
1353 if (git_reference_normalize_name(
1354 normalized,
1355 sizeof(normalized),
1356 new_name,
1357 normalization_flags) < 0)
1358 return -1;
1359
1360 if (reference_can_write(ref->owner, normalized, ref->name, force) < 0)
1361 return -1;
1362
1363 /* Initialize path now so we won't get an allocation failure once
1364 * we actually start removing things. */
1365 if (git_buf_joinpath(&aux_path, ref->owner->path_repository, new_name) < 0)
1366 return -1;
1367
1368 /*
1369 * Check if we have to update HEAD.
1370 */
1371 if ((should_head_be_updated = git_branch_is_head(ref)) < 0)
1372 goto cleanup;
1373
1374 /*
1375 * Now delete the old ref and remove an possibly existing directory
1376 * named `new_name`. Note that using the internal `reference_delete`
1377 * method deletes the ref from disk but doesn't free the pointer, so
1378 * we can still access the ref's attributes for creating the new one
1379 */
1380 if (reference_delete(ref) < 0)
1381 goto cleanup;
1382
1383 /*
1384 * Finally we can create the new reference.
1385 */
1386 if (ref->flags & GIT_REF_SYMBOLIC) {
1387 result = git_reference_create_symbolic(
1388 NULL, ref->owner, new_name, ref->target.symbolic, force);
1389 } else {
1390 result = git_reference_create_oid(
1391 NULL, ref->owner, new_name, &ref->target.oid, force);
1392 }
1393
1394 if (result < 0)
1395 goto rollback;
1396
1397 /*
1398 * Update HEAD it was poiting to the reference being renamed.
1399 */
1400 if (should_head_be_updated &&
1401 git_repository_set_head(ref->owner, new_name) < 0) {
1402 giterr_set(GITERR_REFERENCE,
1403 "Failed to update HEAD after renaming reference");
1404 goto cleanup;
1405 }
1406
1407 /*
1408 * Rename the reflog file, if it exists.
1409 */
1410 if ((git_reference_has_log(ref)) && (git_reflog_rename(ref, new_name) < 0))
1411 goto cleanup;
1412
1413 /*
1414 * Change the name of the reference given by the user.
1415 */
1416 git__free(ref->name);
1417 ref->name = git__strdup(new_name);
1418
1419 /* The reference is no longer packed */
1420 ref->flags &= ~GIT_REF_PACKED;
1421
1422 git_buf_free(&aux_path);
1423 return 0;
1424
1425 cleanup:
1426 git_buf_free(&aux_path);
1427 return -1;
1428
1429 rollback:
1430 /*
1431 * Try to create the old reference again, ignore failures
1432 */
1433 if (ref->flags & GIT_REF_SYMBOLIC)
1434 git_reference_create_symbolic(
1435 NULL, ref->owner, ref->name, ref->target.symbolic, 0);
1436 else
1437 git_reference_create_oid(
1438 NULL, ref->owner, ref->name, &ref->target.oid, 0);
1439
1440 /* The reference is no longer packed */
1441 ref->flags &= ~GIT_REF_PACKED;
1442
1443 git_buf_free(&aux_path);
1444 return -1;
1445 }
1446
1447 int git_reference_resolve(git_reference **ref_out, git_reference *ref)
1448 {
1449 if (ref->flags & GIT_REF_OID)
1450 return git_reference_lookup(ref_out, ref->owner, ref->name);
1451 else
1452 return git_reference_lookup_resolved(ref_out, ref->owner, ref->target.symbolic, -1);
1453 }
1454
1455 int git_reference_packall(git_repository *repo)
1456 {
1457 if (packed_load(repo) < 0 || /* load the existing packfile */
1458 packed_loadloose(repo) < 0 || /* add all the loose refs */
1459 packed_write(repo) < 0) /* write back to disk */
1460 return -1;
1461
1462 return 0;
1463 }
1464
1465 int git_reference_foreach(
1466 git_repository *repo,
1467 unsigned int list_flags,
1468 int (*callback)(const char *, void *),
1469 void *payload)
1470 {
1471 int result;
1472 struct dirent_list_data data;
1473 git_buf refs_path = GIT_BUF_INIT;
1474
1475 /* list all the packed references first */
1476 if (list_flags & GIT_REF_PACKED) {
1477 const char *ref_name;
1478 void *ref;
1479 GIT_UNUSED(ref);
1480
1481 if (packed_load(repo) < 0)
1482 return -1;
1483
1484 git_strmap_foreach(repo->references.packfile, ref_name, ref, {
1485 if (callback(ref_name, payload))
1486 return GIT_EUSER;
1487 });
1488 }
1489
1490 /* now list the loose references, trying not to
1491 * duplicate the ref names already in the packed-refs file */
1492
1493 data.repo_path_len = strlen(repo->path_repository);
1494 data.list_flags = list_flags;
1495 data.repo = repo;
1496 data.callback = callback;
1497 data.callback_payload = payload;
1498 data.callback_error = 0;
1499
1500 if (git_buf_joinpath(&refs_path, repo->path_repository, GIT_REFS_DIR) < 0)
1501 return -1;
1502
1503 result = git_path_direach(&refs_path, _dirent_loose_listall, &data);
1504
1505 git_buf_free(&refs_path);
1506
1507 return data.callback_error ? GIT_EUSER : result;
1508 }
1509
1510 static int cb__reflist_add(const char *ref, void *data)
1511 {
1512 return git_vector_insert((git_vector *)data, git__strdup(ref));
1513 }
1514
1515 int git_reference_list(
1516 git_strarray *array,
1517 git_repository *repo,
1518 unsigned int list_flags)
1519 {
1520 git_vector ref_list;
1521
1522 assert(array && repo);
1523
1524 array->strings = NULL;
1525 array->count = 0;
1526
1527 if (git_vector_init(&ref_list, 8, NULL) < 0)
1528 return -1;
1529
1530 if (git_reference_foreach(
1531 repo, list_flags, &cb__reflist_add, (void *)&ref_list) < 0) {
1532 git_vector_free(&ref_list);
1533 return -1;
1534 }
1535
1536 array->strings = (char **)ref_list.contents;
1537 array->count = ref_list.length;
1538 return 0;
1539 }
1540
1541 int git_reference_reload(git_reference *ref)
1542 {
1543 return reference_lookup(ref);
1544 }
1545
1546 void git_repository__refcache_free(git_refcache *refs)
1547 {
1548 assert(refs);
1549
1550 if (refs->packfile) {
1551 struct packref *reference;
1552
1553 git_strmap_foreach_value(refs->packfile, reference, {
1554 git__free(reference);
1555 });
1556
1557 git_strmap_free(refs->packfile);
1558 }
1559 }
1560
1561 static int is_valid_ref_char(char ch)
1562 {
1563 if ((unsigned) ch <= ' ')
1564 return 0;
1565
1566 switch (ch) {
1567 case '~':
1568 case '^':
1569 case ':':
1570 case '\\':
1571 case '?':
1572 case '[':
1573 case '*':
1574 return 0;
1575 default:
1576 return 1;
1577 }
1578 }
1579
1580 static int ensure_segment_validity(const char *name)
1581 {
1582 const char *current = name;
1583 char prev = '\0';
1584
1585 if (*current == '.')
1586 return -1; /* Refname starts with "." */
1587
1588 for (current = name; ; current++) {
1589 if (*current == '\0' || *current == '/')
1590 break;
1591
1592 if (!is_valid_ref_char(*current))
1593 return -1; /* Illegal character in refname */
1594
1595 if (prev == '.' && *current == '.')
1596 return -1; /* Refname contains ".." */
1597
1598 if (prev == '@' && *current == '{')
1599 return -1; /* Refname contains "@{" */
1600
1601 prev = *current;
1602 }
1603
1604 return (int)(current - name);
1605 }
1606
1607 static bool is_all_caps_and_underscore(const char *name, size_t len)
1608 {
1609 size_t i;
1610 char c;
1611
1612 assert(name && len > 0);
1613
1614 for (i = 0; i < len; i++)
1615 {
1616 c = name[i];
1617 if ((c < 'A' || c > 'Z') && c != '_')
1618 return false;
1619 }
1620
1621 if (*name == '_' || name[len - 1] == '_')
1622 return false;
1623
1624 return true;
1625 }
1626
1627 int git_reference__normalize_name(
1628 git_buf *buf,
1629 const char *name,
1630 unsigned int flags)
1631 {
1632 // Inspired from https://github.com/git/git/blob/f06d47e7e0d9db709ee204ed13a8a7486149f494/refs.c#L36-100
1633
1634 char *current;
1635 int segment_len, segments_count = 0, error = -1;
1636 unsigned int process_flags;
1637 bool normalize = (buf != NULL);
1638 assert(name);
1639
1640 process_flags = flags;
1641 current = (char *)name;
1642
1643 if (normalize)
1644 git_buf_clear(buf);
1645
1646 while (true) {
1647 segment_len = ensure_segment_validity(current);
1648 if (segment_len < 0) {
1649 if ((process_flags & GIT_REF_FORMAT_REFSPEC_PATTERN) &&
1650 current[0] == '*' &&
1651 (current[1] == '\0' || current[1] == '/')) {
1652 /* Accept one wildcard as a full refname component. */
1653 process_flags &= ~GIT_REF_FORMAT_REFSPEC_PATTERN;
1654 segment_len = 1;
1655 } else
1656 goto cleanup;
1657 }
1658
1659 if (segment_len > 0) {
1660 if (normalize) {
1661 size_t cur_len = git_buf_len(buf);
1662
1663 git_buf_joinpath(buf, git_buf_cstr(buf), current);
1664 git_buf_truncate(buf,
1665 cur_len + segment_len + (segments_count ? 1 : 0));
1666
1667 if (git_buf_oom(buf))
1668 goto cleanup;
1669 }
1670
1671 segments_count++;
1672 }
1673
1674 if (current[segment_len] == '\0')
1675 break;
1676
1677 current += segment_len + 1;
1678 }
1679
1680 /* A refname can not be empty */
1681 if (segment_len == 0 && segments_count == 0)
1682 goto cleanup;
1683
1684 /* A refname can not end with "." */
1685 if (current[segment_len - 1] == '.')
1686 goto cleanup;
1687
1688 /* A refname can not end with "/" */
1689 if (current[segment_len - 1] == '/')
1690 goto cleanup;
1691
1692 /* A refname can not end with ".lock" */
1693 if (!git__suffixcmp(name, GIT_FILELOCK_EXTENSION))
1694 goto cleanup;
1695
1696 if ((segments_count == 1 ) && !(flags & GIT_REF_FORMAT_ALLOW_ONELEVEL))
1697 goto cleanup;
1698
1699 if ((segments_count == 1 ) &&
1700 !(is_all_caps_and_underscore(name, (size_t)segment_len) ||
1701 ((flags & GIT_REF_FORMAT_REFSPEC_PATTERN) && !strcmp("*", name))))
1702 goto cleanup;
1703
1704 if ((segments_count > 1)
1705 && (is_all_caps_and_underscore(name, strchr(name, '/') - name)))
1706 goto cleanup;
1707
1708 error = 0;
1709
1710 cleanup:
1711 if (error)
1712 giterr_set(
1713 GITERR_REFERENCE,
1714 "The given reference name '%s' is not valid", name);
1715
1716 return error;
1717 }
1718
1719 int git_reference_normalize_name(
1720 char *buffer_out,
1721 size_t buffer_size,
1722 const char *name,
1723 unsigned int flags)
1724 {
1725 git_buf buf = GIT_BUF_INIT;
1726 int error;
1727
1728 if ((error = git_reference__normalize_name(&buf, name, flags)) < 0)
1729 goto cleanup;
1730
1731 if (git_buf_len(&buf) > buffer_size - 1) {
1732 giterr_set(
1733 GITERR_REFERENCE,
1734 "The provided buffer is too short to hold the normalization of '%s'", name);
1735 error = GIT_EBUFS;
1736 goto cleanup;
1737 }
1738
1739 git_buf_copy_cstr(buffer_out, buffer_size, &buf);
1740
1741 error = 0;
1742
1743 cleanup:
1744 git_buf_free(&buf);
1745 return error;
1746 }
1747
1748 int git_reference__normalize_name_lax(
1749 char *buffer_out,
1750 size_t out_size,
1751 const char *name)
1752 {
1753 return git_reference_normalize_name(
1754 buffer_out,
1755 out_size,
1756 name,
1757 GIT_REF_FORMAT_ALLOW_ONELEVEL);
1758 }
1759 #define GIT_REF_TYPEMASK (GIT_REF_OID | GIT_REF_SYMBOLIC)
1760
1761 int git_reference_cmp(git_reference *ref1, git_reference *ref2)
1762 {
1763 assert(ref1 && ref2);
1764
1765 /* let's put symbolic refs before OIDs */
1766 if ((ref1->flags & GIT_REF_TYPEMASK) != (ref2->flags & GIT_REF_TYPEMASK))
1767 return (ref1->flags & GIT_REF_SYMBOLIC) ? -1 : 1;
1768
1769 if (ref1->flags & GIT_REF_SYMBOLIC)
1770 return strcmp(ref1->target.symbolic, ref2->target.symbolic);
1771
1772 return git_oid_cmp(&ref1->target.oid, &ref2->target.oid);
1773 }
1774
1775 /* Update the reference named `ref_name` so it points to `oid` */
1776 int git_reference__update(git_repository *repo, const git_oid *oid, const char *ref_name)
1777 {
1778 git_reference *ref;
1779 int res;
1780
1781 res = git_reference_lookup(&ref, repo, ref_name);
1782
1783 /* If we haven't found the reference at all, we assume we need to create
1784 * a new reference and that's it */
1785 if (res == GIT_ENOTFOUND) {
1786 giterr_clear();
1787 return git_reference_create_oid(NULL, repo, ref_name, oid, 1);
1788 }
1789
1790 if (res < 0)
1791 return -1;
1792
1793 /* If we have found a reference, but it's symbolic, we need to update
1794 * the direct reference it points to */
1795 if (git_reference_type(ref) == GIT_REF_SYMBOLIC) {
1796 git_reference *aux;
1797 const char *sym_target;
1798
1799 /* The target pointed at by this reference */
1800 sym_target = git_reference_target(ref);
1801
1802 /* resolve the reference to the target it points to */
1803 res = git_reference_resolve(&aux, ref);
1804
1805 /*
1806 * if the symbolic reference pointed to an inexisting ref,
1807 * this is means we're creating a new branch, for example.
1808 * We need to create a new direct reference with that name
1809 */
1810 if (res == GIT_ENOTFOUND) {
1811 giterr_clear();
1812 res = git_reference_create_oid(NULL, repo, sym_target, oid, 1);
1813 git_reference_free(ref);
1814 return res;
1815 }
1816
1817 /* free the original symbolic reference now; not before because
1818 * we're using the `sym_target` pointer */
1819 git_reference_free(ref);
1820
1821 if (res < 0)
1822 return -1;
1823
1824 /* store the newly found direct reference in its place */
1825 ref = aux;
1826 }
1827
1828 /* ref is made to point to `oid`: ref is either the original reference,
1829 * or the target of the symbolic reference we've looked up */
1830 res = git_reference_set_oid(ref, oid);
1831 git_reference_free(ref);
1832 return res;
1833 }
1834
1835 struct glob_cb_data {
1836 const char *glob;
1837 int (*callback)(const char *, void *);
1838 void *payload;
1839 };
1840
1841 static int fromglob_cb(const char *reference_name, void *payload)
1842 {
1843 struct glob_cb_data *data = (struct glob_cb_data *)payload;
1844
1845 if (!p_fnmatch(data->glob, reference_name, 0))
1846 return data->callback(reference_name, data->payload);
1847
1848 return 0;
1849 }
1850
1851 int git_reference_foreach_glob(
1852 git_repository *repo,
1853 const char *glob,
1854 unsigned int list_flags,
1855 int (*callback)(
1856 const char *reference_name,
1857 void *payload),
1858 void *payload)
1859 {
1860 struct glob_cb_data data;
1861
1862 assert(repo && glob && callback);
1863
1864 data.glob = glob;
1865 data.callback = callback;
1866 data.payload = payload;
1867
1868 return git_reference_foreach(
1869 repo, list_flags, fromglob_cb, &data);
1870 }
1871
1872 int git_reference_has_log(
1873 git_reference *ref)
1874 {
1875 git_buf path = GIT_BUF_INIT;
1876 int result;
1877
1878 assert(ref);
1879
1880 if (git_buf_join_n(&path, '/', 3, ref->owner->path_repository, GIT_REFLOG_DIR, ref->name) < 0)
1881 return -1;
1882
1883 result = git_path_isfile(git_buf_cstr(&path));
1884 git_buf_free(&path);
1885
1886 return result;
1887 }
1888
1889 int git_reference_is_branch(git_reference *ref)
1890 {
1891 assert(ref);
1892 return git__prefixcmp(ref->name, GIT_REFS_HEADS_DIR) == 0;
1893 }
1894
1895 int git_reference_is_remote(git_reference *ref)
1896 {
1897 assert(ref);
1898 return git__prefixcmp(ref->name, GIT_REFS_REMOTES_DIR) == 0;
1899 }
1900
1901 static int peel_error(int error, git_reference *ref, const char* msg)
1902 {
1903 giterr_set(
1904 GITERR_INVALID,
1905 "The reference '%s' cannot be peeled - %s", git_reference_name(ref), msg);
1906 return error;
1907 }
1908
1909 static int reference_target(git_object **object, git_reference *ref)
1910 {
1911 const git_oid *oid;
1912
1913 oid = git_reference_oid(ref);
1914
1915 return git_object_lookup(object, git_reference_owner(ref), oid, GIT_OBJ_ANY);
1916 }
1917
1918 int git_reference_peel(
1919 git_object **peeled,
1920 git_reference *ref,
1921 git_otype target_type)
1922 {
1923 git_reference *resolved = NULL;
1924 git_object *target = NULL;
1925 int error;
1926
1927 assert(ref);
1928
1929 if ((error = git_reference_resolve(&resolved, ref)) < 0)
1930 return peel_error(error, ref, "Cannot resolve reference");
1931
1932 if ((error = reference_target(&target, resolved)) < 0) {
1933 peel_error(error, ref, "Cannot retrieve reference target");
1934 goto cleanup;
1935 }
1936
1937 if (target_type == GIT_OBJ_ANY && git_object_type(target) != GIT_OBJ_TAG)
1938 error = git_object__dup(peeled, target);
1939 else
1940 error = git_object_peel(peeled, target, target_type);
1941
1942 cleanup:
1943 git_object_free(target);
1944 git_reference_free(resolved);
1945 return error;
1946 }
1947
1948 int git_reference__is_valid_name(
1949 const char *refname,
1950 unsigned int flags)
1951 {
1952 giterr_clear();
1953 return git_reference__normalize_name(NULL, refname, flags) == 0;
1954 }
1955
1956 int git_reference_is_valid_name(
1957 const char *refname)
1958 {
1959 return git_reference__is_valid_name(
1960 refname,
1961 GIT_REF_FORMAT_ALLOW_ONELEVEL);
1962 }