refs.c 52.3 KB
Newer Older
1 2 3 4
/*
 * The backend-independent part of the reference module.
 */

Daniel Barkalow's avatar
Daniel Barkalow committed
5
#include "cache.h"
6
#include "config.h"
7
#include "hashmap.h"
8
#include "lockfile.h"
9
#include "iterator.h"
10
#include "refs.h"
11
#include "refs/refs-internal.h"
12 13
#include "object.h"
#include "tag.h"
14
#include "submodule.h"
15
#include "worktree.h"
16
#include "repository.h"
17

18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
/*
 * List of all available backends
 */
static struct ref_storage_be *refs_backends = &refs_be_files;

static struct ref_storage_be *find_ref_storage_backend(const char *name)
{
	struct ref_storage_be *be;
	for (be = refs_backends; be; be = be->next)
		if (!strcmp(be->name, name))
			return be;
	return NULL;
}

int ref_storage_backend_exists(const char *name)
{
	return find_ref_storage_backend(name) != NULL;
}

37
/*
38 39
 * How to handle various characters in refnames:
 * 0: An acceptable character for refs
40 41 42
 * 1: End-of-component
 * 2: ., look for a preceding . to reject .. in refs
 * 3: {, look for a preceding @ to reject @{ in refs
43
 * 4: A bad character: ASCII control characters, and
44 45
 *    ":", "?", "[", "\", "^", "~", SP, or TAB
 * 5: *, reject unless REFNAME_REFSPEC_PATTERN is set
46 47
 */
static unsigned char refname_disposition[256] = {
48 49
	1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
	4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
50
	4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 2, 1,
51
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
52
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
53 54 55
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
56 57 58 59 60 61 62
};

/*
 * Try to read one refname component from the front of refname.
 * Return the length of the component found, or -1 if the component is
 * not legal.  It is legal if it is something reasonable to have under
 * ".git/refs/"; We do not like it if:
63 64 65
 *
 * - any path component of it begins with ".", or
 * - it has double dots "..", or
66
 * - it has ASCII control characters, or
67 68
 * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or
 * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or
69 70 71
 * - it ends with a "/", or
 * - it ends with ".lock", or
 * - it contains a "@{" portion
72
 */
73
static int check_refname_component(const char *refname, int *flags)
74 75 76 77 78
{
	const char *cp;
	char last = '\0';

	for (cp = refname; ; cp++) {
79 80 81
		int ch = *cp & 255;
		unsigned char disp = refname_disposition[ch];
		switch (disp) {
82
		case 1:
83
			goto out;
84
		case 2:
85 86 87
			if (last == '.')
				return -1; /* Refname contains "..". */
			break;
88
		case 3:
89 90
			if (last == '@')
				return -1; /* Refname contains "@{". */
91
			break;
92
		case 4:
93
			return -1;
94 95 96 97 98 99 100 101 102 103
		case 5:
			if (!(*flags & REFNAME_REFSPEC_PATTERN))
				return -1; /* refspec can't be a pattern */

			/*
			 * Unset the pattern flag so that we only accept
			 * a single asterisk for one side of refspec.
			 */
			*flags &= ~ REFNAME_REFSPEC_PATTERN;
			break;
104
		}
105 106
		last = ch;
	}
107
out:
108
	if (cp == refname)
109
		return 0; /* Component has zero length. */
110 111
	if (refname[0] == '.')
		return -1; /* Component starts with '.'. */
112 113
	if (cp - refname >= LOCK_SUFFIX_LEN &&
	    !memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN))
114 115 116 117
		return -1; /* Refname ends with ".lock". */
	return cp - refname;
}

118
int check_refname_format(const char *refname, int flags)
119 120 121
{
	int component_len, component_count = 0;

122 123 124 125
	if (!strcmp(refname, "@"))
		/* Refname is a single character '@'. */
		return -1;

126 127
	while (1) {
		/* We are at the start of a path component. */
128 129 130 131
		component_len = check_refname_component(refname, &flags);
		if (component_len <= 0)
			return -1;

132 133 134 135 136 137 138 139 140 141 142 143 144 145
		component_count++;
		if (refname[component_len] == '\0')
			break;
		/* Skip to next component. */
		refname += component_len + 1;
	}

	if (refname[component_len - 1] == '.')
		return -1; /* Refname ends with '.'. */
	if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
		return -1; /* Refname has only one component. */
	return 0;
}

146
int refname_is_safe(const char *refname)
147
{
148 149 150
	const char *rest;

	if (skip_prefix(refname, "refs/", &rest)) {
151 152
		char *buf;
		int result;
153 154 155 156 157
		size_t restlen = strlen(rest);

		/* rest must not be empty, or start or end with "/" */
		if (!restlen || *rest == '/' || rest[restlen - 1] == '/')
			return 0;
158 159 160 161 162 163

		/*
		 * Does the refname try to escape refs/?
		 * For example: refs/foo/../bar is safe but refs/foo/../../bar
		 * is not.
		 */
164 165
		buf = xmallocz(restlen);
		result = !normalize_path_copy(buf, rest) && !strcmp(buf, rest);
166 167 168
		free(buf);
		return result;
	}
169 170

	do {
171 172 173
		if (!isupper(*refname) && *refname != '_')
			return 0;
		refname++;
174
	} while (*refname);
175 176 177
	return 1;
}

178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
/*
 * Return true if refname, which has the specified oid and flags, can
 * be resolved to an object in the database. If the referred-to object
 * does not exist, emit a warning and return false.
 */
int ref_resolves_to_object(const char *refname,
			   const struct object_id *oid,
			   unsigned int flags)
{
	if (flags & REF_ISBROKEN)
		return 0;
	if (!has_sha1_file(oid->hash)) {
		error("%s does not point to a valid object!", refname);
		return 0;
	}
	return 1;
}

Duy Nguyen's avatar
Duy Nguyen committed
196 197
char *refs_resolve_refdup(struct ref_store *refs,
			  const char *refname, int resolve_flags,
198
			  struct object_id *oid, int *flags)
Duy Nguyen's avatar
Duy Nguyen committed
199 200 201 202
{
	const char *result;

	result = refs_resolve_ref_unsafe(refs, refname, resolve_flags,
203
					 oid, flags);
Duy Nguyen's avatar
Duy Nguyen committed
204 205 206
	return xstrdup_or_null(result);
}

207
char *resolve_refdup(const char *refname, int resolve_flags,
208
		     struct object_id *oid, int *flags)
209
{
210
	return refs_resolve_refdup(get_main_ref_store(the_repository),
Duy Nguyen's avatar
Duy Nguyen committed
211
				   refname, resolve_flags,
212
				   oid, flags);
213 214
}

215 216 217 218 219 220
/* The argument to filter_refs */
struct ref_filter {
	const char *pattern;
	each_ref_fn *fn;
	void *cb_data;
};
221

Duy Nguyen's avatar
Duy Nguyen committed
222
int refs_read_ref_full(struct ref_store *refs, const char *refname,
223
		       int resolve_flags, struct object_id *oid, int *flags)
224
{
225
	if (refs_resolve_ref_unsafe(refs, refname, resolve_flags, oid, flags))
226 227
		return 0;
	return -1;
228 229
}

230
int read_ref_full(const char *refname, int resolve_flags, struct object_id *oid, int *flags)
Duy Nguyen's avatar
Duy Nguyen committed
231
{
232
	return refs_read_ref_full(get_main_ref_store(the_repository), refname,
233
				  resolve_flags, oid, flags);
Duy Nguyen's avatar
Duy Nguyen committed
234 235
}

236
int read_ref(const char *refname, struct object_id *oid)
237
{
238
	return read_ref_full(refname, RESOLVE_REF_READING, oid, NULL);
239 240
}

241
int ref_exists(const char *refname)
242
{
243
	return !!resolve_ref_unsafe(refname, RESOLVE_REF_READING, NULL, NULL);
244 245
}

246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
static int match_ref_pattern(const char *refname,
			     const struct string_list_item *item)
{
	int matched = 0;
	if (item->util == NULL) {
		if (!wildmatch(item->string, refname, 0))
			matched = 1;
	} else {
		const char *rest;
		if (skip_prefix(refname, item->string, &rest) &&
		    (!*rest || *rest == '/'))
			matched = 1;
	}
	return matched;
}

int ref_filter_match(const char *refname,
		     const struct string_list *include_patterns,
		     const struct string_list *exclude_patterns)
{
	struct string_list_item *item;

	if (exclude_patterns && exclude_patterns->nr) {
		for_each_string_list_item(item, exclude_patterns) {
			if (match_ref_pattern(refname, item))
				return 0;
		}
	}

	if (include_patterns && include_patterns->nr) {
		int found = 0;
		for_each_string_list_item(item, include_patterns) {
			if (match_ref_pattern(refname, item)) {
				found = 1;
				break;
			}
		}

		if (!found)
			return 0;
	}
	return 1;
}

290 291
static int filter_refs(const char *refname, const struct object_id *oid,
			   int flags, void *data)
292
{
293 294
	struct ref_filter *filter = (struct ref_filter *)data;

295
	if (wildmatch(filter->pattern, refname, 0))
296 297
		return 0;
	return filter->fn(refname, oid, flags, filter->cb_data);
298 299
}

300
enum peel_status peel_object(const struct object_id *name, struct object_id *oid)
301
{
302
	struct object *o = lookup_unknown_object(name->hash);
303

304
	if (o->type == OBJ_NONE) {
305
		int type = oid_object_info(name, NULL);
306 307 308
		if (type < 0 || !object_as_type(o, type, 0))
			return PEEL_INVALID;
	}
309

310 311
	if (o->type != OBJ_TAG)
		return PEEL_NON_TAG;
312

313 314 315 316
	o = deref_tag_noverify(o);
	if (!o)
		return PEEL_INVALID;

317
	oidcpy(oid, &o->oid);
318
	return PEEL_PEELED;
319 320
}

321 322 323 324 325 326
struct warn_if_dangling_data {
	FILE *fp;
	const char *refname;
	const struct string_list *refnames;
	const char *msg_fmt;
};
327

328 329 330 331 332
static int warn_if_dangling_symref(const char *refname, const struct object_id *oid,
				   int flags, void *cb_data)
{
	struct warn_if_dangling_data *d = cb_data;
	const char *resolves_to;
333

334 335
	if (!(flags & REF_ISSYMREF))
		return 0;
336

337
	resolves_to = resolve_ref_unsafe(refname, 0, NULL, NULL);
338 339 340 341 342 343
	if (!resolves_to
	    || (d->refname
		? strcmp(resolves_to, d->refname)
		: !string_list_has_string(d->refnames, resolves_to))) {
		return 0;
	}
344

345 346 347
	fprintf(d->fp, d->msg_fmt, refname);
	fputc('\n', d->fp);
	return 0;
348 349
}

350
void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
351
{
352 353 354 355 356 357 358
	struct warn_if_dangling_data data;

	data.fp = fp;
	data.refname = refname;
	data.refnames = NULL;
	data.msg_fmt = msg_fmt;
	for_each_rawref(warn_if_dangling_symref, &data);
359 360
}

361
void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)
362
{
363
	struct warn_if_dangling_data data;
364

365 366 367 368 369
	data.fp = fp;
	data.refname = NULL;
	data.refnames = refnames;
	data.msg_fmt = msg_fmt;
	for_each_rawref(warn_if_dangling_symref, &data);
370 371
}

Duy Nguyen's avatar
Duy Nguyen committed
372 373 374 375 376
int refs_for_each_tag_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
{
	return refs_for_each_ref_in(refs, "refs/tags/", fn, cb_data);
}

377
int for_each_tag_ref(each_ref_fn fn, void *cb_data)
378
{
379
	return refs_for_each_tag_ref(get_main_ref_store(the_repository), fn, cb_data);
380 381
}

Duy Nguyen's avatar
Duy Nguyen committed
382 383 384
int refs_for_each_branch_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
{
	return refs_for_each_ref_in(refs, "refs/heads/", fn, cb_data);
385 386
}

387
int for_each_branch_ref(each_ref_fn fn, void *cb_data)
388
{
389
	return refs_for_each_branch_ref(get_main_ref_store(the_repository), fn, cb_data);
390 391
}

Duy Nguyen's avatar
Duy Nguyen committed
392 393 394
int refs_for_each_remote_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
{
	return refs_for_each_ref_in(refs, "refs/remotes/", fn, cb_data);
395
}
396

397
int for_each_remote_ref(each_ref_fn fn, void *cb_data)
398
{
399
	return refs_for_each_remote_ref(get_main_ref_store(the_repository), fn, cb_data);
400 401
}

402 403 404 405 406 407
int head_ref_namespaced(each_ref_fn fn, void *cb_data)
{
	struct strbuf buf = STRBUF_INIT;
	int ret = 0;
	struct object_id oid;
	int flag;
408

409
	strbuf_addf(&buf, "%sHEAD", get_git_namespace());
410
	if (!read_ref_full(buf.buf, RESOLVE_REF_READING, &oid, &flag))
411 412
		ret = fn(buf.buf, &oid, flag, cb_data);
	strbuf_release(&buf);
413

414
	return ret;
415
}
416

417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
void normalize_glob_ref(struct string_list_item *item, const char *prefix,
			const char *pattern)
{
	struct strbuf normalized_pattern = STRBUF_INIT;

	if (*pattern == '/')
		BUG("pattern must not start with '/'");

	if (prefix) {
		strbuf_addstr(&normalized_pattern, prefix);
	}
	else if (!starts_with(pattern, "refs/"))
		strbuf_addstr(&normalized_pattern, "refs/");
	strbuf_addstr(&normalized_pattern, pattern);
	strbuf_strip_suffix(&normalized_pattern, "/");

	item->string = strbuf_detach(&normalized_pattern, NULL);
	item->util = has_glob_specials(pattern) ? NULL : item->string;
	strbuf_release(&normalized_pattern);
}

438 439
int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
	const char *prefix, void *cb_data)
440
{
441 442 443
	struct strbuf real_pattern = STRBUF_INIT;
	struct ref_filter filter;
	int ret;
Ilari Liusvaara's avatar
Ilari Liusvaara committed
444

445
	if (!prefix && !starts_with(pattern, "refs/"))
Ilari Liusvaara's avatar
Ilari Liusvaara committed
446
		strbuf_addstr(&real_pattern, "refs/");
447 448
	else if (prefix)
		strbuf_addstr(&real_pattern, prefix);
Ilari Liusvaara's avatar
Ilari Liusvaara committed
449 450
	strbuf_addstr(&real_pattern, pattern);

451
	if (!has_glob_specials(pattern)) {
452
		/* Append implied '/' '*' if not present. */
453
		strbuf_complete(&real_pattern, '/');
Ilari Liusvaara's avatar
Ilari Liusvaara committed
454 455 456 457 458 459 460 461 462 463 464 465 466
		/* No need to check for '*', there is none. */
		strbuf_addch(&real_pattern, '*');
	}

	filter.pattern = real_pattern.buf;
	filter.fn = fn;
	filter.cb_data = cb_data;
	ret = for_each_ref(filter_refs, &filter);

	strbuf_release(&real_pattern);
	return ret;
}

467 468 469 470 471
int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
{
	return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
}

472
const char *prettify_refname(const char *name)
473
{
474 475 476 477 478
	if (skip_prefix(name, "refs/heads/", &name) ||
	    skip_prefix(name, "refs/tags/", &name) ||
	    skip_prefix(name, "refs/remotes/", &name))
		; /* nothing */
	return name;
479 480
}

481
static const char *ref_rev_parse_rules[] = {
Steffen Prohaska's avatar
Steffen Prohaska committed
482 483 484 485 486 487 488 489 490
	"%.*s",
	"refs/%.*s",
	"refs/tags/%.*s",
	"refs/heads/%.*s",
	"refs/remotes/%.*s",
	"refs/remotes/%.*s/HEAD",
	NULL
};

491
int refname_match(const char *abbrev_name, const char *full_name)
Steffen Prohaska's avatar
Steffen Prohaska committed
492 493 494 495
{
	const char **p;
	const int abbrev_name_len = strlen(abbrev_name);

496
	for (p = ref_rev_parse_rules; *p; p++) {
Steffen Prohaska's avatar
Steffen Prohaska committed
497 498 499 500 501 502 503 504
		if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
			return 1;
		}
	}

	return 0;
}

505 506 507 508 509 510 511 512
/*
 * *string and *len will only be substituted, and *string returned (for
 * later free()ing) if the string passed in is a magic short-hand form
 * to name a branch.
 */
static char *substitute_branch_name(const char **string, int *len)
{
	struct strbuf buf = STRBUF_INIT;
513
	int ret = interpret_branch_name(*string, *len, &buf, 0);
514 515 516 517 518 519 520 521 522 523 524

	if (ret == *len) {
		size_t size;
		*string = strbuf_detach(&buf, &size);
		*len = size;
		return (char *)*string;
	}

	return NULL;
}

525
int dwim_ref(const char *str, int len, struct object_id *oid, char **ref)
526 527
{
	char *last_branch = substitute_branch_name(&str, &len);
528
	int   refs_found  = expand_ref(str, len, oid, ref);
Duy Nguyen's avatar
Duy Nguyen committed
529 530 531 532
	free(last_branch);
	return refs_found;
}

533
int expand_ref(const char *str, int len, struct object_id *oid, char **ref)
Duy Nguyen's avatar
Duy Nguyen committed
534
{
535 536
	const char **p, *r;
	int refs_found = 0;
Jeff King's avatar
Jeff King committed
537
	struct strbuf fullref = STRBUF_INIT;
538 539 540

	*ref = NULL;
	for (p = ref_rev_parse_rules; *p; p++) {
541 542
		struct object_id oid_from_ref;
		struct object_id *this_result;
543 544
		int flag;

545
		this_result = refs_found ? &oid_from_ref : oid;
Jeff King's avatar
Jeff King committed
546 547 548
		strbuf_reset(&fullref);
		strbuf_addf(&fullref, *p, len, str);
		r = resolve_ref_unsafe(fullref.buf, RESOLVE_REF_READING,
549
				       this_result, &flag);
550 551 552 553 554
		if (r) {
			if (!refs_found++)
				*ref = xstrdup(r);
			if (!warn_ambiguous_refs)
				break;
Jeff King's avatar
Jeff King committed
555 556 557 558
		} else if ((flag & REF_ISSYMREF) && strcmp(fullref.buf, "HEAD")) {
			warning("ignoring dangling symref %s.", fullref.buf);
		} else if ((flag & REF_ISBROKEN) && strchr(fullref.buf, '/')) {
			warning("ignoring broken ref %s.", fullref.buf);
559
		}
560
	}
Jeff King's avatar
Jeff King committed
561
	strbuf_release(&fullref);
562 563 564
	return refs_found;
}

565
int dwim_log(const char *str, int len, struct object_id *oid, char **log)
566 567 568 569
{
	char *last_branch = substitute_branch_name(&str, &len);
	const char **p;
	int logs_found = 0;
Jeff King's avatar
Jeff King committed
570
	struct strbuf path = STRBUF_INIT;
571 572 573

	*log = NULL;
	for (p = ref_rev_parse_rules; *p; p++) {
574
		struct object_id hash;
575 576
		const char *ref, *it;

Jeff King's avatar
Jeff King committed
577 578 579
		strbuf_reset(&path);
		strbuf_addf(&path, *p, len, str);
		ref = resolve_ref_unsafe(path.buf, RESOLVE_REF_READING,
580
					 &hash, NULL);
581 582
		if (!ref)
			continue;
Jeff King's avatar
Jeff King committed
583 584 585
		if (reflog_exists(path.buf))
			it = path.buf;
		else if (strcmp(ref, path.buf) && reflog_exists(ref))
586 587 588 589 590
			it = ref;
		else
			continue;
		if (!logs_found++) {
			*log = xstrdup(it);
591
			oidcpy(oid, &hash);
592
		}
593 594
		if (!warn_ambiguous_refs)
			break;
595
	}
Jeff King's avatar
Jeff King committed
596
	strbuf_release(&path);
597 598
	free(last_branch);
	return logs_found;
599 600
}

David Turner's avatar
David Turner committed
601 602
static int is_per_worktree_ref(const char *refname)
{
603 604
	return !strcmp(refname, "HEAD") ||
		starts_with(refname, "refs/bisect/");
David Turner's avatar
David Turner committed
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
}

static int is_pseudoref_syntax(const char *refname)
{
	const char *c;

	for (c = refname; *c; c++) {
		if (!isupper(*c) && *c != '-' && *c != '_')
			return 0;
	}

	return 1;
}

enum ref_type ref_type(const char *refname)
{
	if (is_per_worktree_ref(refname))
		return REF_TYPE_PER_WORKTREE;
	if (is_pseudoref_syntax(refname))
		return REF_TYPE_PSEUDOREF;
       return REF_TYPE_NORMAL;
}

628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
long get_files_ref_lock_timeout_ms(void)
{
	static int configured = 0;

	/* The default timeout is 100 ms: */
	static int timeout_ms = 100;

	if (!configured) {
		git_config_get_int("core.filesreflocktimeout", &timeout_ms);
		configured = 1;
	}

	return timeout_ms;
}

643 644
static int write_pseudoref(const char *pseudoref, const struct object_id *oid,
			   const struct object_id *old_oid, struct strbuf *err)
645 646 647 648 649 650 651
{
	const char *filename;
	int fd;
	static struct lock_file lock;
	struct strbuf buf = STRBUF_INIT;
	int ret = -1;

652 653 654
	if (!oid)
		return 0;

655
	strbuf_addf(&buf, "%s\n", oid_to_hex(oid));
656 657

	filename = git_path("%s", pseudoref);
658 659 660
	fd = hold_lock_file_for_update_timeout(&lock, filename,
					       LOCK_DIE_ON_ERROR,
					       get_files_ref_lock_timeout_ms());
661
	if (fd < 0) {
662
		strbuf_addf(err, "could not open '%s' for writing: %s",
663
			    filename, strerror(errno));
664
		goto done;
665 666
	}

667 668
	if (old_oid) {
		struct object_id actual_old_oid;
669

670
		if (read_ref(pseudoref, &actual_old_oid))
671
			die("could not read ref '%s'", pseudoref);
672
		if (oidcmp(&actual_old_oid, old_oid)) {
673
			strbuf_addf(err, "unexpected sha1 when writing '%s'", pseudoref);
674 675 676 677 678
			rollback_lock_file(&lock);
			goto done;
		}
	}

679
	if (write_in_full(fd, buf.buf, buf.len) < 0) {
680
		strbuf_addf(err, "could not write to '%s'", filename);
681 682 683 684 685 686 687 688 689 690 691
		rollback_lock_file(&lock);
		goto done;
	}

	commit_lock_file(&lock);
	ret = 0;
done:
	strbuf_release(&buf);
	return ret;
}

692
static int delete_pseudoref(const char *pseudoref, const struct object_id *old_oid)
693 694 695 696 697 698
{
	static struct lock_file lock;
	const char *filename;

	filename = git_path("%s", pseudoref);

699
	if (old_oid && !is_null_oid(old_oid)) {
700
		int fd;
701
		struct object_id actual_old_oid;
702

703 704 705
		fd = hold_lock_file_for_update_timeout(
				&lock, filename, LOCK_DIE_ON_ERROR,
				get_files_ref_lock_timeout_ms());
706 707
		if (fd < 0)
			die_errno(_("Could not open '%s' for writing"), filename);
708
		if (read_ref(pseudoref, &actual_old_oid))
709
			die("could not read ref '%s'", pseudoref);
710
		if (oidcmp(&actual_old_oid, old_oid)) {
711 712 713
			warning("Unexpected sha1 when deleting %s", pseudoref);
			rollback_lock_file(&lock);
			return -1;
714
		}
715 716 717 718 719

		unlink(filename);
		rollback_lock_file(&lock);
	} else {
		unlink(filename);
720
	}
721

722
	return 0;
Daniel Barkalow's avatar
Daniel Barkalow committed
723
}
724

725 726
int refs_delete_ref(struct ref_store *refs, const char *msg,
		    const char *refname,
727
		    const struct object_id *old_oid,
728
		    unsigned int flags)
729
{
730
	struct ref_transaction *transaction;
731
	struct strbuf err = STRBUF_INIT;
732

733
	if (ref_type(refname) == REF_TYPE_PSEUDOREF) {
734
		assert(refs == get_main_ref_store(the_repository));
735
		return delete_pseudoref(refname, old_oid);
736
	}
737

738
	transaction = ref_store_transaction_begin(refs, &err);
739
	if (!transaction ||
740
	    ref_transaction_delete(transaction, refname, old_oid,
741
				   flags, msg, &err) ||
742
	    ref_transaction_commit(transaction, &err)) {
743 744 745
		error("%s", err.buf);
		ref_transaction_free(transaction);
		strbuf_release(&err);
746
		return 1;
747
	}
748 749
	ref_transaction_free(transaction);
	strbuf_release(&err);
750 751
	return 0;
}
752

753
int delete_ref(const char *msg, const char *refname,
754
	       const struct object_id *old_oid, unsigned int flags)
755
{
756
	return refs_delete_ref(get_main_ref_store(the_repository), msg, refname,
757
			       old_oid, flags);
758 759
}

760
int copy_reflog_msg(char *buf, const char *msg)
761 762 763 764
{
	char *cp = buf;
	char c;
	int wasspace = 1;
765

766 767 768 769 770 771 772 773
	*cp++ = '\t';
	while ((c = *msg++)) {
		if (wasspace && isspace(c))
			continue;
		wasspace = isspace(c);
		if (wasspace)
			c = ' ';
		*cp++ = c;
774
	}
775 776 777 778 779
	while (buf < cp && isspace(cp[-1]))
		cp--;
	*cp++ = '\n';
	return cp - buf;
}
780

781
int should_autocreate_reflog(const char *refname)
782
{
783 784 785 786 787 788 789 790 791
	switch (log_all_ref_updates) {
	case LOG_REFS_ALWAYS:
		return 1;
	case LOG_REFS_NORMAL:
		return starts_with(refname, "refs/heads/") ||
			starts_with(refname, "refs/remotes/") ||
			starts_with(refname, "refs/notes/") ||
			!strcmp(refname, "HEAD");
	default:
792
		return 0;
793
	}
794 795
}

796
int is_branch(const char *refname)
797
{
798
	return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
799 800
}

801 802
struct read_ref_at_cb {
	const char *refname;
803
	timestamp_t at_time;
804 805
	int cnt;
	int reccnt;
806
	struct object_id *oid;
807 808
	int found_it;

809 810
	struct object_id ooid;
	struct object_id noid;
811
	int tz;
812
	timestamp_t date;
813
	char **msg;
814
	timestamp_t *cutoff_time;
815 816 817 818
	int *cutoff_tz;
	int *cutoff_cnt;
};

819
static int read_ref_at_ent(struct object_id *ooid, struct object_id *noid,
820
		const char *email, timestamp_t timestamp, int tz,
821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
		const char *message, void *cb_data)
{
	struct read_ref_at_cb *cb = cb_data;

	cb->reccnt++;
	cb->tz = tz;
	cb->date = timestamp;

	if (timestamp <= cb->at_time || cb->cnt == 0) {
		if (cb->msg)
			*cb->msg = xstrdup(message);
		if (cb->cutoff_time)
			*cb->cutoff_time = timestamp;
		if (cb->cutoff_tz)
			*cb->cutoff_tz = tz;
		if (cb->cutoff_cnt)
			*cb->cutoff_cnt = cb->reccnt - 1;
		/*
839
		 * we have not yet updated cb->[n|o]oid so they still
840 841
		 * hold the values for the previous record.
		 */
842 843 844
		if (!is_null_oid(&cb->ooid)) {
			oidcpy(cb->oid, noid);
			if (oidcmp(&cb->ooid, noid))
845
				warning("Log for ref %s has gap after %s.",
846
					cb->refname, show_date(cb->date, cb->tz, DATE_MODE(RFC2822)));
847 848
		}
		else if (cb->date == cb->at_time)
849 850
			oidcpy(cb->oid, noid);
		else if (oidcmp(noid, cb->oid))
851 852
			warning("Log for ref %s unexpectedly ended on %s.",
				cb->refname, show_date(cb->date, cb->tz,
853
						       DATE_MODE(RFC2822)));
854 855
		oidcpy(&cb->ooid, ooid);
		oidcpy(&cb->noid, noid);
856 857 858
		cb->found_it = 1;
		return 1;
	}
859 860
	oidcpy(&cb->ooid, ooid);
	oidcpy(&cb->noid, noid);
861 862 863 864 865
	if (cb->cnt > 0)
		cb->cnt--;
	return 0;
}

866
static int read_ref_at_ent_oldest(struct object_id *ooid, struct object_id *noid,
867
				  const char *email, timestamp_t timestamp,
868 869 870 871 872 873 874 875 876 877 878 879
				  int tz, const char *message, void *cb_data)
{
	struct read_ref_at_cb *cb = cb_data;

	if (cb->msg)
		*cb->msg = xstrdup(message);
	if (cb->cutoff_time)
		*cb->cutoff_time = timestamp;
	if (cb->cutoff_tz)
		*cb->cutoff_tz = tz;
	if (cb->cutoff_cnt)
		*cb->cutoff_cnt = cb->reccnt;
880 881 882
	oidcpy(cb->oid, ooid);
	if (is_null_oid(cb->oid))
		oidcpy(cb->oid, noid);
883 884
	/* We just want the first entry */
	return 1;
885 886
}

887
int read_ref_at(const char *refname, unsigned int flags, timestamp_t at_time, int cnt,
888
		struct object_id *oid, char **msg,
889
		timestamp_t *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
890
{
891
	struct read_ref_at_cb cb;
892

893 894 895 896 897 898 899 900
	memset(&cb, 0, sizeof(cb));
	cb.refname = refname;
	cb.at_time = at_time;
	cb.cnt = cnt;
	cb.msg = msg;
	cb.cutoff_time = cutoff_time;
	cb.cutoff_tz = cutoff_tz;
	cb.cutoff_cnt = cutoff_cnt;
901
	cb.oid = oid;
902 903 904

	for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);

905
	if (!cb.reccnt) {
906
		if (flags & GET_OID_QUIETLY)
907 908 909 910
			exit(128);
		else
			die("Log for %s is empty.", refname);
	}
911 912 913 914
	if (cb.found_it)
		return 0;

	for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);
915

916
	return 1;
917
}
918

919 920
struct ref_transaction *ref_store_transaction_begin(struct ref_store *refs,
						    struct strbuf *err)
921
{
922
	struct ref_transaction *tr;
923 924
	assert(err);

925 926 927 928 929 930 931
	tr = xcalloc(1, sizeof(struct ref_transaction));
	tr->ref_store = refs;
	return tr;
}

struct ref_transaction *ref_transaction_begin(struct strbuf *err)
{
932
	return ref_store_transaction_begin(get_main_ref_store(the_repository), err);
933 934
}

935
void ref_transaction_free(struct ref_transaction *transaction)
936
{
937
	size_t i;
938

939 940 941
	if (!transaction)
		return;

942 943 944 945 946 947 948 949 950 951 952 953 954
	switch (transaction->state) {
	case REF_TRANSACTION_OPEN:
	case REF_TRANSACTION_CLOSED:
		/* OK */
		break;
	case REF_TRANSACTION_PREPARED:
		die("BUG: free called on a prepared reference transaction");
		break;
	default:
		die("BUG: unexpected reference transaction state");
		break;
	}

955 956
	for (i = 0; i < transaction->nr; i++) {
		free(transaction->updates[i]->msg);
957
		free(transaction->updates[i]);
958
	}
959 960 961 962
	free(transaction->updates);
	free(transaction);
}

963 964 965
struct ref_update *ref_transaction_add_update(
		struct ref_transaction *transaction,
		const char *refname, unsigned int flags,
966 967
		const struct object_id *new_oid,
		const struct object_id *old_oid,
968
		const char *msg)
969
{
970
	struct ref_update *update;
971 972 973 974

	if (transaction->state != REF_TRANSACTION_OPEN)
		die("BUG: update called for transaction that is not open");

975
	FLEX_ALLOC_STR(update, refname, refname);
976 977
	ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
	transaction->updates[transaction->nr++] = update;
978 979 980 981

	update->flags = flags;

	if (flags & REF_HAVE_NEW)
982
		oidcpy(&update->new_oid, new_oid);
983
	if (flags & REF_HAVE_OLD)
984
		oidcpy(&update->old_oid, old_oid);
985
	update->msg = xstrdup_or_null(msg);
986 987 988
	return update;
}

989 990
int ref_transaction_update(struct ref_transaction *transaction,
			   const char *refname,
991 992
			   const struct object_id *new_oid,
			   const struct object_id *old_oid,
993
			   unsigned int flags, const char *msg,
994
			   struct strbuf *err)
995
{
996 997
	assert(err);

998
	if ((new_oid && !is_null_oid(new_oid)) ?
999 1000
	    check_refname_format(refname, REFNAME_ALLOW_ONELEVEL) :
	    !refname_is_safe(refname)) {
1001
		strbuf_addf(err, "refusing to update ref with bad name '%s'",
1002 1003 1004 1005
			    refname);
		return -1;
	}

1006 1007
	if (flags & ~REF_TRANSACTION_UPDATE_ALLOWED_FLAGS)
		BUG("illegal flags 0x%x passed to ref_transaction_update()", flags);
1008

1009
	flags |= (new_oid ? REF_HAVE_NEW : 0) | (old_oid ? REF_HAVE_OLD : 0);
1010 1011

	ref_transaction_add_update(transaction, refname, flags,
1012
				   new_oid, old_oid, msg);
1013
	return 0;
1014 1015
}

1016 1017
int ref_transaction_create(struct ref_transaction *transaction,
			   const char *refname,
1018
			   const struct object_id *new_oid,
1019
			   unsigned int flags, const char *msg,
1020
			   struct strbuf *err)
1021
{
1022 1023 1024 1025
	if (!new_oid || is_null_oid(new_oid))
		die("BUG: create called without valid new_oid");
	return ref_transaction_update(transaction, refname, new_oid,
				      &null_oid, flags, msg, err);
1026 1027
}

1028 1029
int ref_transaction_delete(struct ref_transaction *transaction,
			   const char *refname,
1030
			   const struct object_id *old_oid,
1031
			   unsigned int flags, const char *msg,
1032
			   struct strbuf *err)
1033
{
1034 1035
	if (old_oid && is_null_oid(old_oid))
		die("BUG: delete called with old_oid set to zeros");
1036
	return ref_transaction_update(transaction, refname,
1037
				      &null_oid, old_oid,
1038
				      flags, msg, err);
1039 1040
}

1041 1042
int ref_transaction_verify(struct ref_transaction *transaction,
			   const char *refname,
1043
			   const struct object_id *old_oid,
1044 1045 1046
			   unsigned int flags,
			   struct strbuf *err)
{
1047 1048
	if (!old_oid)
		die("BUG: verify called with old_oid set to NULL");
1049
	return ref_transaction_update(transaction, refname,
1050
				      NULL, old_oid,
1051 1052 1053
				      flags, NULL, err);
}

1054
int refs_update_ref(struct ref_store *refs, const char *msg,
1055 1056
		    const char *refname, const struct object_id *new_oid,
		    const struct object_id *old_oid, unsigned int flags,
1057
		    enum action_on_err onerr)