refs.c 30.1 KB
Newer Older
1
/*
Edward Thomson committed
2
 * Copyright (C) the libgit2 contributors. All rights reserved.
3
 *
Vicent Marti committed
4 5
 * This file is part of libgit2, distributed under the GNU GPL v2 with
 * a Linking Exception. For full terms see the included COPYING file.
6 7 8
 */

#include "refs.h"
9

10 11
#include "hash.h"
#include "repository.h"
12
#include "futils.h"
13
#include "filebuf.h"
14
#include "pack.h"
15
#include "reflog.h"
16
#include "refdb.h"
17

Vicent Marti committed
18 19
#include <git2/tag.h>
#include <git2/object.h>
20
#include <git2/oid.h>
21
#include <git2/branch.h>
22 23
#include <git2/refs.h>
#include <git2/refdb.h>
24
#include <git2/sys/refs.h>
25
#include <git2/signature.h>
26
#include <git2/commit.h>
Vicent Marti committed
27

28 29
bool git_reference__enable_symbolic_ref_target_validation = true;

30 31 32 33
enum {
	GIT_PACKREF_HAS_PEEL = 1,
	GIT_PACKREF_WAS_LOOSE = 2
};
34

35
static git_reference *alloc_ref(const char *name)
36
{
37 38
	git_reference *ref = NULL;
	size_t namelen = strlen(name), reflen;
39

40 41 42 43
	if (!GIT_ADD_SIZET_OVERFLOW(&reflen, sizeof(git_reference), namelen) &&
		!GIT_ADD_SIZET_OVERFLOW(&reflen, reflen, 1) &&
		(ref = git__calloc(1, reflen)) != NULL)
		memcpy(ref->name, name, namelen + 1);
44 45 46 47 48

	return ref;
}

git_reference *git_reference__alloc_symbolic(
49
	const char *name, const char *target)
50
{
51
	git_reference *ref;
52

53
	assert(name && target);
54

55
	ref = alloc_ref(name);
56
	if (!ref)
57
		return NULL;
Vicent Marti committed
58

59
	ref->type = GIT_REFERENCE_SYMBOLIC;
Vicent Marti committed
60

61 62 63
	if ((ref->target.symbolic = git__strdup(target)) == NULL) {
		git__free(ref);
		return NULL;
64
	}
65

66 67 68 69 70 71 72 73 74 75
	return ref;
}

git_reference *git_reference__alloc(
	const char *name,
	const git_oid *oid,
	const git_oid *peel)
{
	git_reference *ref;

76
	assert(name && oid);
77

78
	ref = alloc_ref(name);
79 80 81
	if (!ref)
		return NULL;

82
	ref->type = GIT_REFERENCE_DIRECT;
83
	git_oid_cpy(&ref->target.oid, oid);
84 85

	if (peel != NULL)
86
		git_oid_cpy(&ref->peel, peel);
87

88
	return ref;
89
}
90

91 92
git_reference *git_reference__realloc(
	git_reference **ptr_to_ref, const char *name)
93
{
94
	size_t namelen, reflen;
95 96
	git_reference *rewrite = NULL;

97 98 99 100
	assert(ptr_to_ref && name);

	namelen = strlen(name);

101 102
	if (!GIT_ADD_SIZET_OVERFLOW(&reflen, sizeof(git_reference), namelen) &&
		!GIT_ADD_SIZET_OVERFLOW(&reflen, reflen, 1) &&
103
		(rewrite = git__realloc(*ptr_to_ref, reflen)) != NULL)
104
		memcpy(rewrite->name, name, namelen + 1);
105

106 107
	*ptr_to_ref = NULL;

108 109 110
	return rewrite;
}

111 112
int git_reference_dup(git_reference **dest, git_reference *source)
{
113
	if (source->type == GIT_REFERENCE_SYMBOLIC)
114 115 116 117
		*dest = git_reference__alloc_symbolic(source->name, source->target.symbolic);
	else
		*dest = git_reference__alloc(source->name, &source->target.oid, &source->peel);

118
	GIT_ERROR_CHECK_ALLOC(*dest);
119

120 121 122
	(*dest)->db = source->db;
	GIT_REFCOUNT_INC((*dest)->db);

123 124 125
	return 0;
}

126
void git_reference_free(git_reference *reference)
127
{
128 129
	if (reference == NULL)
		return;
130

131
	if (reference->type == GIT_REFERENCE_SYMBOLIC)
132
		git__free(reference->target.symbolic);
133

Vicent Marti committed
134 135
	if (reference->db)
		GIT_REFCOUNT_DEC(reference->db, git_refdb__free);
136 137

	git__free(reference);
138
}
139

140
int git_reference_delete(git_reference *ref)
141
{
142 143 144
	const git_oid *old_id = NULL;
	const char *old_target = NULL;

145 146 147 148 149
	if (!strcmp(ref->name, "HEAD")) {
		git_error_set(GIT_ERROR_REFERENCE, "cannot delete HEAD");
		return GIT_ERROR;
	}

150
	if (ref->type == GIT_REFERENCE_DIRECT)
151 152 153 154 155
		old_id = &ref->target.oid;
	else
		old_target = ref->target.symbolic;

	return git_refdb_delete(ref->db, ref->name, old_id, old_target);
156 157
}

158 159 160 161 162 163 164 165 166 167 168
int git_reference_remove(git_repository *repo, const char *name)
{
	git_refdb *db;
	int error;

	if ((error = git_repository_refdb__weakptr(&db, repo)) < 0)
		return error;

	return git_refdb_delete(db, name, NULL, NULL);
}

169
int git_reference_lookup(git_reference **ref_out,
170
	git_repository *repo, const char *name)
171
{
172 173 174
	return git_reference_lookup_resolved(ref_out, repo, name, 0);
}

175
int git_reference_name_to_id(
176 177 178 179 180 181 182 183
	git_oid *out, git_repository *repo, const char *name)
{
	int error;
	git_reference *ref;

	if ((error = git_reference_lookup_resolved(&ref, repo, name, -1)) < 0)
		return error;

184
	git_oid_cpy(out, git_reference_target(ref));
185 186 187 188
	git_reference_free(ref);
	return 0;
}

189
static int reference_normalize_for_repo(
190
	git_refname_t out,
191
	git_repository *repo,
192 193
	const char *name,
	bool validate)
194 195
{
	int precompose;
196
	unsigned int flags = GIT_REFERENCE_FORMAT_ALLOW_ONELEVEL;
197

198
	if (!git_repository__configmap_lookup(&precompose, repo, GIT_CONFIGMAP_PRECOMPOSE) &&
199
		precompose)
200
		flags |= GIT_REFERENCE_FORMAT__PRECOMPOSE_UNICODE;
201

202
	if (!validate)
203
		flags |= GIT_REFERENCE_FORMAT__VALIDATION_DISABLE;
204

205
	return git_reference_normalize_name(out, GIT_REFNAME_MAX, name, flags);
206 207
}

208 209 210 211 212 213
int git_reference_lookup_resolved(
	git_reference **ref_out,
	git_repository *repo,
	const char *name,
	int max_nesting)
{
214
	git_refname_t normalized;
215
	git_refdb *refdb;
216
	int error = 0;
217 218

	assert(ref_out && repo && name);
219

220 221 222
	if ((error = reference_normalize_for_repo(normalized, repo, name, true)) < 0 ||
	    (error = git_repository_refdb__weakptr(&refdb, repo)) < 0 ||
	    (error = git_refdb_resolve(ref_out, refdb, normalized, max_nesting)) < 0)
223
		return error;
224

225 226 227 228 229 230 231 232 233 234 235 236
	/*
	 * The resolved reference may be a symbolic reference in case its
	 * target doesn't exist. If the user asked us to resolve (e.g.
	 * `max_nesting != 0`), then we need to return an error in case we got
	 * a symbolic reference back.
	 */
	if (max_nesting && git_reference_type(*ref_out) == GIT_REFERENCE_SYMBOLIC) {
		git_reference_free(*ref_out);
		*ref_out = NULL;
		return GIT_ENOTFOUND;
	}

237
	return 0;
238 239
}

240 241
int git_reference_dwim(git_reference **out, git_repository *repo, const char *refname)
{
242
	int error = 0, i, valid;
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
	bool fallbackmode = true, foundvalid = false;
	git_reference *ref;
	git_buf refnamebuf = GIT_BUF_INIT, name = GIT_BUF_INIT;

	static const char* formatters[] = {
		"%s",
		GIT_REFS_DIR "%s",
		GIT_REFS_TAGS_DIR "%s",
		GIT_REFS_HEADS_DIR "%s",
		GIT_REFS_REMOTES_DIR "%s",
		GIT_REFS_REMOTES_DIR "%s/" GIT_HEAD_FILE,
		NULL
	};

	if (*refname)
		git_buf_puts(&name, refname);
	else {
		git_buf_puts(&name, GIT_HEAD_FILE);
		fallbackmode = false;
	}

	for (i = 0; formatters[i] && (fallbackmode || i == 0); i++) {

		git_buf_clear(&refnamebuf);

268 269
		if ((error = git_buf_printf(&refnamebuf, formatters[i], git_buf_cstr(&name))) < 0 ||
		    (error = git_reference_name_is_valid(&valid, git_buf_cstr(&refnamebuf))) < 0)
270 271
			goto cleanup;

272
		if (!valid) {
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
			error = GIT_EINVALIDSPEC;
			continue;
		}
		foundvalid = true;

		error = git_reference_lookup_resolved(&ref, repo, git_buf_cstr(&refnamebuf), -1);

		if (!error) {
			*out = ref;
			error = 0;
			goto cleanup;
		}

		if (error != GIT_ENOTFOUND)
			goto cleanup;
	}

cleanup:
	if (error && !foundvalid) {
		/* never found a valid reference name */
293
		git_error_set(GIT_ERROR_REFERENCE,
294
			"could not use '%s' as valid reference name", git_buf_cstr(&name));
295 296
	}

297
	if (error == GIT_ENOTFOUND)
298
		git_error_set(GIT_ERROR_REFERENCE, "no reference found for shorthand '%s'", refname);
299

300 301
	git_buf_dispose(&name);
	git_buf_dispose(&refnamebuf);
302 303 304
	return error;
}

305 306 307
/**
 * Getters
 */
308
git_reference_t git_reference_type(const git_reference *ref)
Vicent Marti committed
309 310
{
	assert(ref);
311
	return ref->type;
Vicent Marti committed
312 313
}

314
const char *git_reference_name(const git_reference *ref)
Vicent Marti committed
315 316
{
	assert(ref);
317
	return ref->name;
Vicent Marti committed
318 319
}

320
git_repository *git_reference_owner(const git_reference *ref)
321
{
322
	assert(ref);
323
	return ref->db->repo;
324 325
}

326
const git_oid *git_reference_target(const git_reference *ref)
Vicent Marti committed
327 328 329
{
	assert(ref);

330
	if (ref->type != GIT_REFERENCE_DIRECT)
Vicent Marti committed
331 332
		return NULL;

333
	return &ref->target.oid;
334 335 336 337 338 339
}

const git_oid *git_reference_target_peel(const git_reference *ref)
{
	assert(ref);

340
	if (ref->type != GIT_REFERENCE_DIRECT || git_oid_is_zero(&ref->peel))
341 342
		return NULL;

343
	return &ref->peel;
Vicent Marti committed
344 345
}

346
const char *git_reference_symbolic_target(const git_reference *ref)
347
{
348
	assert(ref);
349

350
	if (ref->type != GIT_REFERENCE_SYMBOLIC)
351 352
		return NULL;

353
	return ref->target.symbolic;
354 355
}

356
static int reference__create(
357 358 359
	git_reference **ref_out,
	git_repository *repo,
	const char *name,
360 361
	const git_oid *oid,
	const char *symbolic,
362 363
	int force,
	const git_signature *signature,
364
	const char *log_message,
365 366
	const git_oid *old_id,
	const char *old_target)
367
{
368
	git_refname_t normalized;
369
	git_refdb *refdb;
370
	git_reference *ref = NULL;
371
	int error = 0;
372

373
	assert(repo && name);
374
	assert(symbolic || signature);
375

376 377 378
	if (ref_out)
		*ref_out = NULL;

379
	error = reference_normalize_for_repo(normalized, repo, name, true);
Vicent Marti committed
380 381 382 383 384
	if (error < 0)
		return error;

	error = git_repository_refdb__weakptr(&refdb, repo);
	if (error < 0)
385
		return error;
386 387 388

	if (oid != NULL) {
		assert(symbolic == NULL);
389

390
		if (!git_object__is_valid(repo, oid, GIT_OBJECT_ANY)) {
391
			git_error_set(GIT_ERROR_REFERENCE,
392
				"target OID for the reference doesn't exist on the repository");
393 394 395
			return -1;
		}

396
		ref = git_reference__alloc(normalized, oid, NULL);
397
	} else {
398
		git_refname_t normalized_target;
399

400 401
		error = reference_normalize_for_repo(normalized_target, repo,
			symbolic, git_reference__enable_symbolic_ref_target_validation);
402 403

		if (error < 0)
404 405
			return error;

406
		ref = git_reference__alloc_symbolic(normalized, normalized_target);
407
	}
408

409
	GIT_ERROR_CHECK_ALLOC(ref);
410

411
	if ((error = git_refdb_write(refdb, ref, force, signature, log_message, old_id, old_target)) < 0) {
412
		git_reference_free(ref);
413
		return error;
414
	}
415

416
	if (ref_out == NULL)
417
		git_reference_free(ref);
418
	else
419
		*ref_out = ref;
420

421
	return 0;
422 423
}

424
static int refs_configured_ident(git_signature **out, const git_repository *repo)
425 426 427 428 429 430 431 432
{
	if (repo->ident_name && repo->ident_email)
		return git_signature_now(out, repo->ident_name, repo->ident_email);

	/* if not configured let us fall-through to the next method  */
	return -1;
}

433
int git_reference__log_signature(git_signature **out, git_repository *repo)
434
{
435
	int error;
436
	git_signature *who;
437

438
	if(((error = refs_configured_ident(&who, repo)) < 0) &&
439
	   ((error = git_signature_default(&who, repo)) < 0) &&
440
	   ((error = git_signature_now(&who, "unknown", "unknown")) < 0))
441
		return error;
442

443 444
	*out = who;
	return 0;
445 446
}

447
int git_reference_create_matching(
448 449 450 451 452
	git_reference **ref_out,
	git_repository *repo,
	const char *name,
	const git_oid *id,
	int force,
453 454
	const git_oid *old_id,
	const char *log_message)
455

456
{
457 458
	int error;
	git_signature *who = NULL;
459

460
	assert(id);
461

462 463
	if ((error = git_reference__log_signature(&who, repo)) < 0)
		return error;
464 465

	error = reference__create(
466
		ref_out, repo, name, id, NULL, force, who, log_message, old_id, NULL);
Vicent Marti committed
467

468 469
	git_signature_free(who);
	return error;
470
}
471

472 473 474 475 476 477 478 479
int git_reference_create(
	git_reference **ref_out,
	git_repository *repo,
	const char *name,
	const git_oid *id,
	int force,
	const char *log_message)
{
480
        return git_reference_create_matching(ref_out, repo, name, id, force, NULL, log_message);
481 482
}

483
int git_reference_symbolic_create_matching(
484 485 486 487 488
	git_reference **ref_out,
	git_repository *repo,
	const char *name,
	const char *target,
	int force,
489 490
	const char *old_target,
	const char *log_message)
491
{
492 493 494 495 496
	int error;
	git_signature *who = NULL;

	assert(target);

497 498
	if ((error = git_reference__log_signature(&who, repo)) < 0)
		return error;
499

500
	error = reference__create(
501
		ref_out, repo, name, NULL, target, force, who, log_message, NULL, old_target);
502 503 504

	git_signature_free(who);
	return error;
505 506
}

507 508 509 510 511 512 513 514
int git_reference_symbolic_create(
	git_reference **ref_out,
	git_repository *repo,
	const char *name,
	const char *target,
	int force,
	const char *log_message)
{
515
	return git_reference_symbolic_create_matching(ref_out, repo, name, target, force, NULL, log_message);
516 517
}

518 519
static int ensure_is_an_updatable_direct_reference(git_reference *ref)
{
520
	if (ref->type == GIT_REFERENCE_DIRECT)
521
		return 0;
522

523
	git_error_set(GIT_ERROR_REFERENCE, "cannot set OID on symbolic reference");
524
	return -1;
525
}
526

527
int git_reference_set_target(
528 529
	git_reference **out,
	git_reference *ref,
530
	const git_oid *id,
531
	const char *log_message)
532 533
{
	int error;
534
	git_repository *repo;
535 536 537

	assert(out && ref && id);

538 539
	repo = ref->db->repo;

540 541 542
	if ((error = ensure_is_an_updatable_direct_reference(ref)) < 0)
		return error;

543
	return git_reference_create_matching(out, repo, ref->name, id, 1, &ref->target.oid, log_message);
544 545
}

546 547
static int ensure_is_an_updatable_symbolic_reference(git_reference *ref)
{
548
	if (ref->type == GIT_REFERENCE_SYMBOLIC)
549 550
		return 0;

551
	git_error_set(GIT_ERROR_REFERENCE, "cannot set symbolic target on a direct reference");
552 553 554
	return -1;
}

555 556 557
int git_reference_symbolic_set_target(
	git_reference **out,
	git_reference *ref,
558 559
	const char *target,
	const char *log_message)
Vicent Marti committed
560
{
561 562
	int error;

563
	assert(out && ref && target);
564

565 566
	if ((error = ensure_is_an_updatable_symbolic_reference(ref)) < 0)
		return error;
567

568
	return git_reference_symbolic_create_matching(
569
		out, ref->db->repo, ref->name, target, 1, ref->target.symbolic, log_message);
Vicent Marti committed
570 571
}

572 573 574
typedef struct {
    const char *old_name;
    git_refname_t new_name;
575
} refs_update_head_payload;
576

577
static int refs_update_head(git_repository *worktree, void *_payload)
578
{
579 580
	refs_update_head_payload *payload = (refs_update_head_payload *)_payload;
	git_reference *head = NULL, *updated = NULL;
581 582
	int error;

583
	if ((error = git_reference_lookup(&head, worktree, GIT_HEAD_FILE)) < 0)
584
		goto out;
585

586
	if (git_reference_type(head) != GIT_REFERENCE_SYMBOLIC ||
587
	    git__strcmp(git_reference_symbolic_target(head), payload->old_name) != 0)
588
		goto out;
589

590 591
	/* Update HEAD if it was pointing to the reference being renamed */
	if ((error = git_reference_symbolic_set_target(&updated, head, payload->new_name, NULL)) < 0) {
592
		git_error_set(GIT_ERROR_REFERENCE, "failed to update HEAD after renaming reference");
593 594 595 596
		goto out;
	}

out:
597
	git_reference_free(updated);
598 599 600 601
	git_reference_free(head);
	return error;
}

602 603 604 605
int git_reference_rename(
	git_reference **out,
	git_reference *ref,
	const char *new_name,
606 607
	int force,
	const char *log_message)
608
{
609
	refs_update_head_payload payload;
610
	git_signature *signature = NULL;
611
	git_repository *repo;
612
	int error;
613

614 615
	assert(out && ref);

616
	repo = git_reference_owner(ref);
617

618 619 620 621 622 623
	if ((error = git_reference__log_signature(&signature, repo)) < 0 ||
	    (error = reference_normalize_for_repo(payload.new_name, repo, new_name, true)) < 0 ||
	    (error = git_refdb_rename(out, ref->db, ref->name, payload.new_name, force, signature, log_message)) < 0)
		goto out;

	payload.old_name = ref->name;
624

625 626 627 628 629 630
	/* We may have to update any HEAD that was pointing to the renamed reference. */
	if ((error = git_repository_foreach_worktree(repo, refs_update_head, &payload)) < 0)
		goto out;

out:
	git_signature_free(signature);
631 632 633
	return error;
}

634
int git_reference_resolve(git_reference **ref_out, const git_reference *ref)
Vicent Marti committed
635
{
636
	switch (git_reference_type(ref)) {
637
	case GIT_REFERENCE_DIRECT:
638
		return git_reference_lookup(ref_out, ref->db->repo, ref->name);
639

640
	case GIT_REFERENCE_SYMBOLIC:
641 642 643
		return git_reference_lookup_resolved(ref_out, ref->db->repo, ref->target.symbolic, -1);

	default:
644
		git_error_set(GIT_ERROR_REFERENCE, "invalid reference");
645 646
		return -1;
	}
Vicent Marti committed
647 648
}

649 650
int git_reference_foreach(
	git_repository *repo,
651
	git_reference_foreach_cb callback,
652
	void *payload)
653
{
654
	git_reference_iterator *iter;
655
	git_reference *ref;
656 657
	int error;

658 659
	if ((error = git_reference_iterator_new(&iter, repo)) < 0)
		return error;
660

661 662
	while (!(error = git_reference_next(&ref, iter))) {
		if ((error = callback(ref, payload)) != 0) {
663
			git_error_set_after_callback(error);
664 665 666
			break;
		}
	}
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681

	if (error == GIT_ITEROVER)
		error = 0;

	git_reference_iterator_free(iter);
	return error;
}

int git_reference_foreach_name(
	git_repository *repo,
	git_reference_foreach_name_cb callback,
	void *payload)
{
	git_reference_iterator *iter;
	const char *refname;
682 683
	int error;

684 685
	if ((error = git_reference_iterator_new(&iter, repo)) < 0)
		return error;
686

687 688
	while (!(error = git_reference_next_name(&refname, iter))) {
		if ((error = callback(refname, payload)) != 0) {
689
			git_error_set_after_callback(error);
690 691 692
			break;
		}
	}
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710

	if (error == GIT_ITEROVER)
		error = 0;

	git_reference_iterator_free(iter);
	return error;
}

int git_reference_foreach_glob(
	git_repository *repo,
	const char *glob,
	git_reference_foreach_name_cb callback,
	void *payload)
{
	git_reference_iterator *iter;
	const char *refname;
	int error;

711 712
	if ((error = git_reference_iterator_glob_new(&iter, repo, glob)) < 0)
		return error;
713

714 715
	while (!(error = git_reference_next_name(&refname, iter))) {
		if ((error = callback(refname, payload)) != 0) {
716
			git_error_set_after_callback(error);
717 718 719
			break;
		}
	}
720 721 722 723 724 725

	if (error == GIT_ITEROVER)
		error = 0;

	git_reference_iterator_free(iter);
	return error;
726 727
}

728 729 730 731 732 733 734
int git_reference_iterator_new(git_reference_iterator **out, git_repository *repo)
{
	git_refdb *refdb;

	if (git_repository_refdb__weakptr(&refdb, repo) < 0)
		return -1;

735
	return git_refdb_iterator(out, refdb, NULL);
736 737
}

738 739
int git_reference_iterator_glob_new(
	git_reference_iterator **out, git_repository *repo, const char *glob)
740
{
741
	git_refdb *refdb;
742

743 744 745
	if (git_repository_refdb__weakptr(&refdb, repo) < 0)
		return -1;

746
	return git_refdb_iterator(out, refdb, glob);
747 748
}

Vicent Marti committed
749
int git_reference_next(git_reference **out, git_reference_iterator *iter)
750
{
751 752 753 754 755 756
	return git_refdb_iterator_next(out, iter);
}

int git_reference_next_name(const char **out, git_reference_iterator *iter)
{
	return git_refdb_iterator_next_name(out, iter);
757 758 759 760
}

void git_reference_iterator_free(git_reference_iterator *iter)
{
761 762 763
	if (iter == NULL)
		return;

764
	git_refdb_iterator_free(iter);
765 766
}

767
static int cb__reflist_add(const char *ref, void *data)
768
{
769
	char *name = git__strdup(ref);
770
	GIT_ERROR_CHECK_ALLOC(name);
771
	return git_vector_insert((git_vector *)data, name);
772 773
}

774
int git_reference_list(
775
	git_strarray *array,
776
	git_repository *repo)
777 778 779 780 781 782 783 784
{
	git_vector ref_list;

	assert(array && repo);

	array->strings = NULL;
	array->count = 0;

785
	if (git_vector_init(&ref_list, 8, NULL) < 0)
786
		return -1;
787

788
	if (git_reference_foreach_name(
789
			repo, &cb__reflist_add, (void *)&ref_list) < 0) {
790
		git_vector_free(&ref_list);
791
		return -1;
792 793
	}

794 795
	array->strings = (char **)git_vector_detach(&array->count, NULL, &ref_list);

796
	return 0;
797
}
Vicent Marti committed
798

799
static int is_valid_ref_char(char ch)
800
{
801
	if ((unsigned) ch <= ' ')
802
		return 0;
803 804 805 806 807 808 809 810

	switch (ch) {
	case '~':
	case '^':
	case ':':
	case '\\':
	case '?':
	case '[':
811
		return 0;
812
	default:
813
		return 1;
814 815 816
	}
}

817
static int ensure_segment_validity(const char *name, char may_contain_glob)
818
{
819 820
	const char *current = name;
	char prev = '\0';
821 822
	const int lock_len = (int)strlen(GIT_FILELOCK_EXTENSION);
	int segment_len;
823

824 825
	if (*current == '.')
		return -1; /* Refname starts with "." */
826

827 828 829
	for (current = name; ; current++) {
		if (*current == '\0' || *current == '/')
			break;
830

831 832
		if (!is_valid_ref_char(*current))
			return -1; /* Illegal character in refname */
833

834 835
		if (prev == '.' && *current == '.')
			return -1; /* Refname contains ".." */
836

837 838
		if (prev == '@' && *current == '{')
			return -1; /* Refname contains "@{" */
839

840 841 842 843 844 845
		if (*current == '*') {
			if (!may_contain_glob)
				return -1;
			may_contain_glob = 0;
		}

846 847
		prev = *current;
	}
848

849 850
	segment_len = (int)(current - name);

851
	/* A refname component can not end with ".lock" */
852
	if (segment_len >= lock_len &&
853
		!memcmp(current - lock_len, GIT_FILELOCK_EXTENSION, lock_len))
854 855
			return -1;

856
	return segment_len;
857
}
858

859
static bool is_all_caps_and_underscore(const char *name, size_t len)
860
{
861
	size_t i;
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
	char c;

	assert(name && len > 0);

	for (i = 0; i < len; i++)
	{
		c = name[i];
		if ((c < 'A' || c > 'Z') && c != '_')
			return false;
	}

	if (*name == '_' || name[len - 1] == '_')
		return false;

	return true;
}

879
/* Inspired from https://github.com/git/git/blob/f06d47e7e0d9db709ee204ed13a8a7486149f494/refs.c#L36-100 */
880 881 882 883 884
int git_reference__normalize_name(
	git_buf *buf,
	const char *name,
	unsigned int flags)
{
885
	const char *current;
886
	int segment_len, segments_count = 0, error = GIT_EINVALIDSPEC;
887 888
	unsigned int process_flags;
	bool normalize = (buf != NULL);
889
	bool validate = (flags & GIT_REFERENCE_FORMAT__VALIDATION_DISABLE) == 0;
890 891

#ifdef GIT_USE_ICONV
892
	git_path_iconv_t ic = GIT_PATH_ICONV_INIT;
893
#endif
894

895
	assert(name);
896

897
	process_flags = flags;
898 899
	current = (char *)name;

900
	if (validate && *current == '/')
901 902
		goto cleanup;

903 904
	if (normalize)
		git_buf_clear(buf);
905

906
#ifdef GIT_USE_ICONV
907
	if ((flags & GIT_REFERENCE_FORMAT__PRECOMPOSE_UNICODE) != 0) {
908 909 910 911
		size_t namelen = strlen(current);
		if ((error = git_path_iconv_init_precompose(&ic)) < 0 ||
			(error = git_path_iconv(&ic, &current, &namelen)) < 0)
			goto cleanup;
912
		error = GIT_EINVALIDSPEC;
913
	}
914
#endif
915

916 917 918 919 920 921 922
	if (!validate) {
		git_buf_sets(buf, current);

		error = git_buf_oom(buf) ? -1 : 0;
		goto cleanup;
	}

923
	while (true) {
924 925 926 927 928
		char may_contain_glob = process_flags & GIT_REFERENCE_FORMAT_REFSPEC_PATTERN;

		segment_len = ensure_segment_validity(current, may_contain_glob);
		if (segment_len < 0)
			goto cleanup;
929

930
		if (segment_len > 0) {
931 932 933 934 935 936 937
			/*
			 * There may only be one glob in a pattern, thus we reset
			 * the pattern-flag in case the current segment has one.
			 */
			if (memchr(current, '*', segment_len))
				process_flags &= ~GIT_REFERENCE_FORMAT_REFSPEC_PATTERN;

938
			if (normalize) {
939
				size_t cur_len = git_buf_len(buf);
940

941
				git_buf_joinpath(buf, git_buf_cstr(buf), current);
942
				git_buf_truncate(buf,
943
					cur_len + segment_len + (segments_count ? 1 : 0));
944

945 946
				if (git_buf_oom(buf)) {
					error = -1;
947
					goto cleanup;
948
				}
949
			}
950

951
			segments_count++;
952
		}
953

954 955
		/* No empty segment is allowed when not normalizing */
		if (segment_len == 0 && !normalize)
956
			goto cleanup;
957

958 959
		if (current[segment_len] == '\0')
			break;
960

961
		current += segment_len + 1;
962
	}
963

964
	/* A refname can not be empty */
965
	if (segment_len == 0 && segments_count == 0)
966 967 968 969 970 971 972 973 974 975
		goto cleanup;

	/* A refname can not end with "." */
	if (current[segment_len - 1] == '.')
		goto cleanup;

	/* A refname can not end with "/" */
	if (current[segment_len - 1] == '/')
		goto cleanup;

976
	if ((segments_count == 1 ) && !(flags & GIT_REFERENCE_FORMAT_ALLOW_ONELEVEL))
977 978 979
		goto cleanup;

	if ((segments_count == 1 ) &&
980
	    !(flags & GIT_REFERENCE_FORMAT_REFSPEC_SHORTHAND) &&
981
		!(is_all_caps_and_underscore(name, (size_t)segment_len) ||
982
			((flags & GIT_REFERENCE_FORMAT_REFSPEC_PATTERN) && !strcmp("*", name))))
983 984 985 986 987
			goto cleanup;

	if ((segments_count > 1)
		&& (is_all_caps_and_underscore(name, strchr(name, '/') - name)))
			goto cleanup;
988

989
	error = 0;
990

991
cleanup:
992
	if (error == GIT_EINVALIDSPEC)
993 994
		git_error_set(
			GIT_ERROR_REFERENCE,
995
			"the given reference name '%s' is not valid", name);
996

997
	if (error && normalize)
998
		git_buf_dispose(buf);
999

1000
#ifdef GIT_USE_ICONV
1001
	git_path_iconv_clear(&ic);
1002
#endif
1003

1004 1005
	return error;
}
1006

1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
int git_reference_normalize_name(
	char *buffer_out,
	size_t buffer_size,
	const char *name,
	unsigned int flags)
{
	git_buf buf = GIT_BUF_INIT;
	int error;

	if ((error = git_reference__normalize_name(&buf, name, flags)) < 0)
		goto cleanup;

	if (git_buf_len(&buf) > buffer_size - 1) {
1020 1021
		git_error_set(
		GIT_ERROR_REFERENCE,
1022
		"the provided buffer is too short to hold the normalization of '%s'", name);
1023 1024 1025 1026 1027 1028 1029 1030 1031
		error = GIT_EBUFS;
		goto cleanup;
	}

	git_buf_copy_cstr(buffer_out, buffer_size, &buf);

	error = 0;

cleanup:
1032
	git_buf_dispose(&buf);
1033
	return error;
1034
}
1035

1036
#define GIT_REFERENCE_TYPEMASK (GIT_REFERENCE_DIRECT | GIT_REFERENCE_SYMBOLIC)
1037

Jacques Germishuys committed
1038 1039 1040
int git_reference_cmp(
	const git_reference *ref1,
	const git_reference *ref2)
1041
{
1042
	git_reference_t type1, type2;
1043 1044
	assert(ref1 && ref2);

1045 1046 1047
	type1 = git_reference_type(ref1);
	type2 = git_reference_type(ref2);

1048
	/* let's put symbolic refs before OIDs */
1049
	if (type1 != type2)
1050
		return (type1 == GIT_REFERENCE_SYMBOLIC) ? -1 : 1;
1051

1052
	if (type1 == GIT_REFERENCE_SYMBOLIC)
1053 1054
		return strcmp(ref1->target.symbolic, ref2->target.symbolic);

1055
	return git_oid__cmp(&ref1->target.oid, &ref2->target.oid);
1056 1057
}

1058 1059 1060 1061 1062 1063 1064 1065
/*
 * Starting with the reference given by `ref_name`, follows symbolic
 * references until a direct reference is found and updated the OID
 * on that direct reference to `oid`.
 */
int git_reference__update_terminal(
	git_repository *repo,
	const char *ref_name,
1066
	const git_oid *oid,
1067
	const git_signature *sig,
1068
	const char *log_message)
1069
{
1070
	git_reference *ref = NULL, *ref2 = NULL;
1071
	git_signature *who = NULL;
1072
	git_refdb *refdb = NULL;
1073 1074 1075 1076
	const git_signature *to_use;
	int error = 0;

	if (!sig && (error = git_reference__log_signature(&who, repo)) < 0)
1077
		goto out;
1078 1079 1080

	to_use = sig ? sig : who;

1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
	if ((error = git_repository_refdb__weakptr(&refdb, repo)) < 0)
		goto out;

	if ((error = git_refdb_resolve(&ref, refdb, ref_name, -1)) < 0) {
		if (error == GIT_ENOTFOUND) {
			git_error_clear();
			error = reference__create(&ref2, repo, ref_name, oid, NULL, 0, to_use,
						  log_message, NULL, NULL);
		}
		goto out;
	}

	/* In case the resolved reference is symbolic, then it's a dangling symref. */
	if (git_reference_type(ref) == GIT_REFERENCE_SYMBOLIC) {
1095
		error = reference__create(&ref2, repo, ref->target.symbolic, oid, NULL, 0, to_use,
1096
					  log_message, NULL, NULL);
1097
	} else {
1098
		error = reference__create(&ref2, repo, ref->name, oid, NULL, 1, to_use,
1099 1100 1101
					  log_message, &ref->target.oid, NULL);
	}

1102
out:
1103 1104
	git_reference_free(ref2);
	git_reference_free(ref);
1105 1106
	git_signature_free(who);
	return error;
1107 1108
}

1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
static const char *commit_type(const git_commit *commit)
{
	unsigned int count = git_commit_parentcount(commit);

	if (count >= 2)
		return " (merge)";
	else if (count == 0)
		return " (initial)";
	else
		return "";
}

1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
int git_reference__update_for_commit(
	git_repository *repo,
	git_reference *ref,
	const char *ref_name,
	const git_oid *id,
	const char *operation)
{
	git_reference *ref_new = NULL;
	git_commit *commit = NULL;
	git_buf reflog_msg = GIT_BUF_INIT;
1131
	const git_signature *who;
1132 1133 1134 1135 1136
	int error;

	if ((error = git_commit_lookup(&commit, repo, id)) < 0 ||
		(error = git_buf_printf(&reflog_msg, "%s%s: %s",
			operation ? operation : "commit",
1137
			commit_type(commit),
1138 1139 1140
			git_commit_summary(commit))) < 0)
		goto done;

1141 1142 1143 1144 1145 1146 1147 1148 1149
	who = git_commit_committer(commit);

	if (ref) {
		if ((error = ensure_is_an_updatable_direct_reference(ref)) < 0)
			return error;

		error = reference__create(&ref_new, repo, ref->name, id, NULL, 1, who,
					  git_buf_cstr(&reflog_msg), &ref->target.oid, NULL);
	}
1150 1151
	else
		error = git_reference__update_terminal(
1152
			repo, ref_name, id, who, git_buf_cstr(&reflog_msg));
1153 1154 1155

done:
	git_reference_free(ref_new);
1156
	git_buf_dispose(&reflog_msg);
1157 1158 1159 1160
	git_commit_free(commit);
	return error;
}

1161
int git_reference_has_log(git_repository *repo, const char *refname)
1162
{
1163 1164
	int error;
	git_refdb *refdb;
1165

1166
	assert(repo && refname);
1167

1168 1169
	if ((error = git_repository_refdb__weakptr(&refdb, repo)) < 0)
		return error;
1170

1171
	return git_refdb_has_log(refdb, refname);
1172
}
1173

1174 1175 1176 1177 1178 1179 1180 1181 1182
int git_reference_ensure_log(git_repository *repo, const char *refname)
{
	int error;
	git_refdb *refdb;

	assert(repo && refname);

	if ((error = git_repository_refdb__weakptr(&refdb, repo)) < 0)
		return error;
1183

1184
	return git_refdb_ensure_log(refdb, refname);
1185
}
1186

1187 1188 1189 1190 1191
int git_reference__is_branch(const char *ref_name)
{
	return git__prefixcmp(ref_name, GIT_REFS_HEADS_DIR) == 0;
}

1192
int git_reference_is_branch(const git_reference *ref)
1193 1194
{
	assert(ref);
1195
	return git_reference__is_branch(ref->name);
1196
}
1197

1198 1199 1200 1201 1202
int git_reference__is_remote(const char *ref_name)
{
	return git__prefixcmp(ref_name, GIT_REFS_REMOTES_DIR) == 0;
}

Jacques Germishuys committed
1203
int git_reference_is_remote(const git_reference *ref)
1204 1205
{
	assert(ref);
1206
	return git_reference__is_remote(ref->name);
1207
}
1208

1209 1210 1211 1212 1213
int git_reference__is_tag(const char *ref_name)
{
	return git__prefixcmp(ref_name, GIT_REFS_TAGS_DIR) == 0;
}

Jacques Germishuys committed
1214
int git_reference_is_tag(const git_reference *ref)
1215 1216 1217 1218 1219
{
	assert(ref);
	return git_reference__is_tag(ref->name);
}

1220 1221 1222 1223 1224
int git_reference__is_note(const char *ref_name)
{
	return git__prefixcmp(ref_name, GIT_REFS_NOTES_DIR) == 0;
}

Jacques Germishuys committed
1225
int git_reference_is_note(const git_reference *ref)
1226 1227 1228 1229 1230
{
	assert(ref);
	return git_reference__is_note(ref->name);
}

1231
static int peel_error(int error, const git_reference *ref, const char* msg)
1232
{
1233 1234
	git_error_set(
		GIT_ERROR_INVALID,
1235
		"the reference '%s' cannot be peeled - %s", git_reference_name(ref), msg);
1236 1237 1238 1239
	return error;
}

int git_reference_peel(
1240
	git_object **peeled,
1241
	const git_reference *ref,
1242
	git_object_t target_type)
1243
{
1244 1245
	const git_reference *resolved = NULL;
	git_reference *allocated = NULL;
1246 1247 1248 1249 1250
	git_object *target = NULL;
	int error;

	assert(ref);

1251
	if (ref->type == GIT_REFERENCE_DIRECT) {
1252 1253
		resolved = ref;
	} else {
1254
		if ((error = git_reference_resolve(&allocated, ref)) < 0)
1255
			return peel_error(error, ref, "Cannot resolve reference");
1256 1257

		resolved = allocated;
1258 1259
	}

1260 1261 1262 1263 1264 1265
	/*
	 * If we try to peel an object to a tag, we cannot use
	 * the fully peeled object, as that will always resolve
	 * to a commit. So we only want to use the peeled value
	 * if it is not zero and the target is not a tag.
	 */
1266
	if (target_type != GIT_OBJECT_TAG && !git_oid_is_zero(&resolved->peel)) {
1267
		error = git_object_lookup(&target,
1268
			git_reference_owner(ref), &resolved->peel, GIT_OBJECT_ANY);
1269 1270
	} else {
		error = git_object_lookup(&target,
1271
			git_reference_owner(ref), &resolved->target.oid, GIT_OBJECT_ANY);
1272
	}
1273

1274
	if (error < 0) {
1275 1276 1277
		peel_error(error, ref, "Cannot retrieve reference target");
		goto cleanup;
	}
1278

1279
	if (target_type == GIT_OBJECT_ANY && git_object_type(target) != GIT_OBJECT_TAG)
1280
		error = git_object_dup(peeled, target);
1281
	else
1282 1283 1284 1285
		error = git_object_peel(peeled, target, target_type);

cleanup:
	git_object_free(target);
1286
	git_reference_free(allocated);
1287

1288 1289
	return error;
}
1290

1291 1292 1293 1294
int git_reference__name_is_valid(
	int *valid,
	const char *refname,
	unsigned int flags)
1295
{
1296
	int error;
nulltoken committed
1297

1298 1299
	GIT_ASSERT(valid && refname);

1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
	*valid = 0;

	error = git_reference__normalize_name(NULL, refname, flags);

	if (!error)
		*valid = 1;
	else if (error == GIT_EINVALIDSPEC)
		error = 0;

	return error;
1310 1311
}

1312 1313 1314 1315 1316
int git_reference_name_is_valid(int *valid, const char *refname)
{
	return git_reference__name_is_valid(valid, refname, GIT_REFERENCE_FORMAT_ALLOW_ONELEVEL);
}

1317
const char *git_reference__shorthand(const char *name)
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
{
	if (!git__prefixcmp(name, GIT_REFS_HEADS_DIR))
		return name + strlen(GIT_REFS_HEADS_DIR);
	else if (!git__prefixcmp(name, GIT_REFS_TAGS_DIR))
		return name + strlen(GIT_REFS_TAGS_DIR);
	else if (!git__prefixcmp(name, GIT_REFS_REMOTES_DIR))
		return name + strlen(GIT_REFS_REMOTES_DIR);
	else if (!git__prefixcmp(name, GIT_REFS_DIR))
		return name + strlen(GIT_REFS_DIR);

	/* No shorthands are avaiable, so just return the name */
	return name;
}
1331 1332 1333 1334 1335

const char *git_reference_shorthand(const git_reference *ref)
{
	return git_reference__shorthand(ref->name);
}
1336 1337 1338 1339 1340 1341 1342

int git_reference__is_unborn_head(bool *unborn, const git_reference *ref, git_repository *repo)
{
	int error;
	git_reference *tmp_ref;
	assert(unborn && ref && repo);

1343
	if (ref->type == GIT_REFERENCE_DIRECT) {
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359
		*unborn = 0;
		return 0;
	}

	error = git_reference_lookup_resolved(&tmp_ref, repo, ref->name, -1);
	git_reference_free(tmp_ref);

	if (error != 0 && error != GIT_ENOTFOUND)
		return error;
	else if (error == GIT_ENOTFOUND && git__strcmp(ref->name, GIT_HEAD_FILE) == 0)
		*unborn = true;
	else
		*unborn = false;

	return 0;
}
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374

/* Deprecated functions */

#ifndef GIT_DEPRECATE_HARD

int git_reference_is_valid_name(const char *refname)
{
	int valid = 0;

	git_reference__name_is_valid(&valid, refname, GIT_REFERENCE_FORMAT_ALLOW_ONELEVEL);

	return valid;
}

#endif