builtin-branch.c 15.0 KB
Newer Older
L
Lars Hjemli 已提交
1 2 3 4 5 6 7 8
/*
 * Builtin "git branch"
 *
 * Copyright (c) 2006 Kristian Hgsberg <krh@redhat.com>
 * Based on git-branch.sh by Junio C Hamano.
 */

#include "cache.h"
9
#include "color.h"
L
Lars Hjemli 已提交
10 11 12 13 14
#include "refs.h"
#include "commit.h"
#include "builtin.h"

static const char builtin_branch_usage[] =
15
  "git-branch [-r] (-d | -D) <branchname> | [--track | --no-track] [-l] [-f] <branchname> [<start-point>] | (-m | -M) [<oldbranch>] <newbranch> | [--color | --no-color] [-r | -a] [-v [--abbrev=<length> | --no-abbrev]]";
L
Lars Hjemli 已提交
16

17 18 19 20
#define REF_UNKNOWN_TYPE    0x00
#define REF_LOCAL_BRANCH    0x01
#define REF_REMOTE_BRANCH   0x02
#define REF_TAG             0x04
L
Lars Hjemli 已提交
21 22 23 24

static const char *head;
static unsigned char head_sha1[20];

25 26
static int branch_track_remotes;

A
Andy Parkins 已提交
27 28 29 30 31
static int branch_use_color;
static char branch_colors[][COLOR_MAXLEN] = {
	"\033[m",	/* reset */
	"",		/* PLAIN (normal) */
	"\033[31m",	/* REMOTE (red) */
32 33
	"",		/* LOCAL (normal) */
	"\033[32m",	/* CURRENT (green) */
A
Andy Parkins 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
};
enum color_branch {
	COLOR_BRANCH_RESET = 0,
	COLOR_BRANCH_PLAIN = 1,
	COLOR_BRANCH_REMOTE = 2,
	COLOR_BRANCH_LOCAL = 3,
	COLOR_BRANCH_CURRENT = 4,
};

static int parse_branch_color_slot(const char *var, int ofs)
{
	if (!strcasecmp(var+ofs, "plain"))
		return COLOR_BRANCH_PLAIN;
	if (!strcasecmp(var+ofs, "reset"))
		return COLOR_BRANCH_RESET;
	if (!strcasecmp(var+ofs, "remote"))
		return COLOR_BRANCH_REMOTE;
	if (!strcasecmp(var+ofs, "local"))
		return COLOR_BRANCH_LOCAL;
	if (!strcasecmp(var+ofs, "current"))
		return COLOR_BRANCH_CURRENT;
	die("bad config variable '%s'", var);
}

int git_branch_config(const char *var, const char *value)
{
	if (!strcmp(var, "color.branch")) {
		branch_use_color = git_config_colorbool(var, value);
		return 0;
	}
64
	if (!prefixcmp(var, "color.branch.")) {
A
Andy Parkins 已提交
65 66 67 68
		int slot = parse_branch_color_slot(var, 13);
		color_parse(value, var, branch_colors[slot]);
		return 0;
	}
69 70 71
	if (!strcmp(var, "branch.autosetupmerge"))
		branch_track_remotes = git_config_bool(var, value);

A
Andy Parkins 已提交
72 73 74 75 76 77 78 79 80 81
	return git_default_config(var, value);
}

const char *branch_get_color(enum color_branch ix)
{
	if (branch_use_color)
		return branch_colors[ix];
	return "";
}

82
static int delete_branches(int argc, const char **argv, int force, int kinds)
L
Lars Hjemli 已提交
83
{
84
	struct commit *rev, *head_rev = head_rev;
L
Lars Hjemli 已提交
85
	unsigned char sha1[20];
86
	char *name = NULL;
87
	const char *fmt, *remote;
L
Lars Hjemli 已提交
88
	int i;
89
	int ret = 0;
L
Lars Hjemli 已提交
90

91 92 93 94 95 96 97 98 99 100 101 102 103
	switch (kinds) {
	case REF_REMOTE_BRANCH:
		fmt = "refs/remotes/%s";
		remote = "remote ";
		force = 1;
		break;
	case REF_LOCAL_BRANCH:
		fmt = "refs/heads/%s";
		remote = "";
		break;
	default:
		die("cannot use -a with -d");
	}
L
Lars Hjemli 已提交
104

105 106 107 108 109
	if (!force) {
		head_rev = lookup_commit_reference(head_sha1);
		if (!head_rev)
			die("Couldn't look up commit object for HEAD");
	}
L
Lars Hjemli 已提交
110
	for (i = 0; i < argc; i++) {
111 112 113 114 115 116 117 118 119
		if (kinds == REF_LOCAL_BRANCH && !strcmp(head, argv[i])) {
			error("Cannot delete the branch '%s' "
				"which you are currently on.", argv[i]);
			ret = 1;
			continue;
		}

		if (name)
			free(name);
L
Lars Hjemli 已提交
120

121
		name = xstrdup(mkpath(fmt, argv[i]));
122 123 124 125 126 127
		if (!resolve_ref(name, sha1, 1, NULL)) {
			error("%sbranch '%s' not found.",
					remote, argv[i]);
			ret = 1;
			continue;
		}
L
Lars Hjemli 已提交
128 129

		rev = lookup_commit_reference(sha1);
130 131 132 133 134
		if (!rev) {
			error("Couldn't look up commit object for '%s'", name);
			ret = 1;
			continue;
		}
L
Lars Hjemli 已提交
135 136 137 138 139 140 141

		/* This checks whether the merge bases of branch and
		 * HEAD contains branch -- which means that the HEAD
		 * contains everything in both.
		 */

		if (!force &&
142
		    !in_merge_bases(rev, &head_rev, 1)) {
143 144 145 146 147 148
			error("The branch '%s' is not a strict subset of "
				"your current HEAD.\n"
				"If you are sure you want to delete it, "
				"run 'git branch -D %s'.", argv[i], argv[i]);
			ret = 1;
			continue;
L
Lars Hjemli 已提交
149 150
		}

151 152
		if (delete_ref(name, sha1)) {
			error("Error deleting %sbranch '%s'", remote,
153
			       argv[i]);
154 155
			ret = 1;
		} else
156
			printf("Deleted %sbranch %s.\n", remote, argv[i]);
L
Lars Hjemli 已提交
157 158 159

	}

160 161 162 163
	if (name)
		free(name);

	return(ret);
L
Lars Hjemli 已提交
164 165
}

166 167 168
struct ref_item {
	char *name;
	unsigned int kind;
169
	unsigned char sha1[20];
170 171 172
};

struct ref_list {
173
	int index, alloc, maxwidth;
174 175 176 177 178
	struct ref_item *list;
	int kinds;
};

static int append_ref(const char *refname, const unsigned char *sha1, int flags, void *cb_data)
L
Lars Hjemli 已提交
179
{
180 181 182
	struct ref_list *ref_list = (struct ref_list*)(cb_data);
	struct ref_item *newitem;
	int kind = REF_UNKNOWN_TYPE;
183
	int len;
184 185

	/* Detect kind */
186
	if (!prefixcmp(refname, "refs/heads/")) {
187 188
		kind = REF_LOCAL_BRANCH;
		refname += 11;
189
	} else if (!prefixcmp(refname, "refs/remotes/")) {
190 191
		kind = REF_REMOTE_BRANCH;
		refname += 13;
192
	} else if (!prefixcmp(refname, "refs/tags/")) {
193 194 195 196 197 198 199 200 201 202 203 204 205
		kind = REF_TAG;
		refname += 10;
	}

	/* Don't add types the caller doesn't want */
	if ((kind & ref_list->kinds) == 0)
		return 0;

	/* Resize buffer */
	if (ref_list->index >= ref_list->alloc) {
		ref_list->alloc = alloc_nr(ref_list->alloc);
		ref_list->list = xrealloc(ref_list->list,
				ref_list->alloc * sizeof(struct ref_item));
L
Lars Hjemli 已提交
206 207
	}

208 209 210 211
	/* Record the new item */
	newitem = &(ref_list->list[ref_list->index++]);
	newitem->name = xstrdup(refname);
	newitem->kind = kind;
212 213 214 215
	hashcpy(newitem->sha1, sha1);
	len = strlen(newitem->name);
	if (len > ref_list->maxwidth)
		ref_list->maxwidth = len;
L
Lars Hjemli 已提交
216 217 218 219

	return 0;
}

220 221 222 223 224 225 226 227 228
static void free_ref_list(struct ref_list *ref_list)
{
	int i;

	for (i = 0; i < ref_list->index; i++)
		free(ref_list->list[i].name);
	free(ref_list->list);
}

L
Lars Hjemli 已提交
229 230
static int ref_cmp(const void *r1, const void *r2)
{
231 232 233 234 235 236
	struct ref_item *c1 = (struct ref_item *)(r1);
	struct ref_item *c2 = (struct ref_item *)(r2);

	if (c1->kind != c2->kind)
		return c1->kind - c2->kind;
	return strcmp(c1->name, c2->name);
L
Lars Hjemli 已提交
237 238
}

239 240
static void print_ref_item(struct ref_item *item, int maxwidth, int verbose,
			   int abbrev, int current)
241
{
242 243
	char c;
	int color;
244 245 246
	struct commit *commit;
	char subject[256];

247 248 249 250 251 252 253 254 255 256 257
	switch (item->kind) {
	case REF_LOCAL_BRANCH:
		color = COLOR_BRANCH_LOCAL;
		break;
	case REF_REMOTE_BRANCH:
		color = COLOR_BRANCH_REMOTE;
		break;
	default:
		color = COLOR_BRANCH_PLAIN;
		break;
	}
258

259 260 261 262 263
	c = ' ';
	if (current) {
		c = '*';
		color = COLOR_BRANCH_CURRENT;
	}
264

265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
	if (verbose) {
		commit = lookup_commit(item->sha1);
		if (commit && !parse_commit(commit))
			pretty_print_commit(CMIT_FMT_ONELINE, commit, ~0,
					    subject, sizeof(subject), 0,
					    NULL, NULL, 0);
		else
			strcpy(subject, " **** invalid ref ****");
		printf("%c %s%-*s%s %s %s\n", c, branch_get_color(color),
		       maxwidth, item->name,
		       branch_get_color(COLOR_BRANCH_RESET),
		       find_unique_abbrev(item->sha1, abbrev), subject);
	} else {
		printf("%c %s%s%s\n", c, branch_get_color(color), item->name,
		       branch_get_color(COLOR_BRANCH_RESET));
	}
281 282
}

L
Lars Hjemli 已提交
283
static void print_ref_list(int kinds, int detached, int verbose, int abbrev)
L
Lars Hjemli 已提交
284 285
{
	int i;
286
	struct ref_list ref_list;
L
Lars Hjemli 已提交
287

288 289 290
	memset(&ref_list, 0, sizeof(ref_list));
	ref_list.kinds = kinds;
	for_each_ref(append_ref, &ref_list);
L
Lars Hjemli 已提交
291

292
	qsort(ref_list.list, ref_list.index, sizeof(struct ref_item), ref_cmp);
L
Lars Hjemli 已提交
293

L
Lars Hjemli 已提交
294 295 296
	detached = (detached && (kinds & REF_LOCAL_BRANCH));
	if (detached) {
		struct ref_item item;
297
		item.name = xstrdup("(no branch)");
L
Lars Hjemli 已提交
298 299 300 301 302
		item.kind = REF_LOCAL_BRANCH;
		hashcpy(item.sha1, head_sha1);
		if (strlen(item.name) > ref_list.maxwidth)
			      ref_list.maxwidth = strlen(item.name);
		print_ref_item(&item, ref_list.maxwidth, verbose, abbrev, 1);
303
		free(item.name);
L
Lars Hjemli 已提交
304 305
	}

306
	for (i = 0; i < ref_list.index; i++) {
L
Lars Hjemli 已提交
307 308
		int current = !detached &&
			(ref_list.list[i].kind == REF_LOCAL_BRANCH) &&
309 310 311
			!strcmp(ref_list.list[i].name, head);
		print_ref_item(&ref_list.list[i], ref_list.maxwidth, verbose,
			       abbrev, current);
L
Lars Hjemli 已提交
312
	}
313 314

	free_ref_list(&ref_list);
L
Lars Hjemli 已提交
315 316
}

317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
static char *config_repo;
static char *config_remote;
static const char *start_ref;
static int start_len;
static int base_len;

static int get_remote_branch_name(const char *value)
{
	const char *colon;
	const char *end;

	if (*value == '+')
		value++;

	colon = strchr(value, ':');
	if (!colon)
		return 0;

	end = value + strlen(value);

	/* Try an exact match first.  */
	if (!strcmp(colon + 1, start_ref)) {
		/* Truncate the value before the colon.  */
		nfasprintf(&config_repo, "%.*s", colon - value, value);
		return 1;
	}

	/* Try with a wildcard match now.  */
	if (end - value > 2 && end[-2] == '/' && end[-1] == '*' &&
	    colon - value > 2 && colon[-2] == '/' && colon[-1] == '*' &&
	    (end - 2) - (colon + 1) == base_len &&
	    !strncmp(colon + 1, start_ref, base_len)) {
		/* Replace the star with the remote branch name.  */
		nfasprintf(&config_repo, "%.*s%s",
			   (colon - 2) - value, value,
			   start_ref + base_len);
		return 1;
	}

	return 0;
}

static int get_remote_config(const char *key, const char *value)
{
	const char *var;
	if (prefixcmp(key, "remote."))
		return 0;

	var = strrchr(key, '.');
	if (var == key + 6)
		return 0;

	if (!strcmp(var, ".fetch") && get_remote_branch_name(value))
		nfasprintf(&config_remote, "%.*s", var - (key + 7), key + 7);

	return 0;
}

static void set_branch_defaults(const char *name, const char *real_ref)
{
	char key[1024];
	const char *slash = strrchr(real_ref, '/');

	if (!slash)
		return;

	start_ref = real_ref;
	start_len = strlen(real_ref);
	base_len = slash - real_ref;
	git_config(get_remote_config);

	if (config_repo && config_remote) {
		if (sizeof(key) <=
		    snprintf(key, sizeof(key), "branch.%s.remote", name))
			die("what a long branch name you have!");
		git_config_set(key, config_remote);

		/*
		 * We do not have to check if we have enough space for
		 * the 'merge' key, since it's shorter than the
		 * previous 'remote' key, which we already checked.
		 */
		snprintf(key, sizeof(key), "branch.%s.merge", name);
		git_config_set(key, config_repo);

		printf("Branch %s set up to track remote branch %s.\n",
		       name, real_ref);
	}

	if (config_repo)
		free(config_repo);
	if (config_remote)
		free(config_remote);
}

J
Junio C Hamano 已提交
412
static void create_branch(const char *name, const char *start_name,
413
			  int force, int reflog, int track)
L
Lars Hjemli 已提交
414 415 416 417
{
	struct ref_lock *lock;
	struct commit *commit;
	unsigned char sha1[20];
418
	char *real_ref, ref[PATH_MAX], msg[PATH_MAX + 20];
419
	int forcing = 0;
L
Lars Hjemli 已提交
420 421 422 423 424 425 426 427

	snprintf(ref, sizeof ref, "refs/heads/%s", name);
	if (check_ref_format(ref))
		die("'%s' is not a valid branch name.", name);

	if (resolve_ref(ref, sha1, 1, NULL)) {
		if (!force)
			die("A branch named '%s' already exists.", name);
428
		else if (!is_bare_repository() && !strcmp(head, name))
L
Lars Hjemli 已提交
429
			die("Cannot force update the current branch.");
430
		forcing = 1;
L
Lars Hjemli 已提交
431 432
	}

433 434 435 436 437 438 439
	real_ref = NULL;
	if (get_sha1(start_name, sha1))
		die("Not a valid object name: '%s'.", start_name);

	switch (dwim_ref(start_name, strlen(start_name), sha1, &real_ref)) {
	case 0:
		/* Not branching from any existing branch */
440
		real_ref = NULL;
441 442 443 444 445
		break;
	case 1:
		/* Unique completion -- good */
		break;
	default:
446
		die("Ambiguous object name: '%s'.", start_name);
447 448
		break;
	}
J
Junio C Hamano 已提交
449 450 451

	if ((commit = lookup_commit_reference(sha1)) == NULL)
		die("Not a valid branch point: '%s'.", start_name);
L
Lars Hjemli 已提交
452 453 454 455 456 457
	hashcpy(sha1, commit->object.sha1);

	lock = lock_any_ref_for_update(ref, NULL);
	if (!lock)
		die("Failed to lock ref for update: %s.", strerror(errno));

458
	if (reflog)
L
Lars Hjemli 已提交
459
		log_all_ref_updates = 1;
460 461 462 463 464

	if (forcing)
		snprintf(msg, sizeof msg, "branch: Reset from %s",
			 start_name);
	else
J
Junio C Hamano 已提交
465 466
		snprintf(msg, sizeof msg, "branch: Created from %s",
			 start_name);
L
Lars Hjemli 已提交
467

468 469 470 471 472 473
	/* When branching off a remote branch, set up so that git-pull
	   automatically merges from there.  So far, this is only done for
	   remotes registered via .git/config.  */
	if (real_ref && track)
		set_branch_defaults(name, real_ref);

L
Lars Hjemli 已提交
474 475
	if (write_ref_sha1(lock, sha1, msg) < 0)
		die("Failed to write ref: %s.", strerror(errno));
476 477 478

	if (real_ref)
		free(real_ref);
L
Lars Hjemli 已提交
479 480
}

481 482
static void rename_branch(const char *oldname, const char *newname, int force)
{
483
	char oldref[PATH_MAX], newref[PATH_MAX], logmsg[PATH_MAX*2 + 100];
484 485
	unsigned char sha1[20];

J
Junio C Hamano 已提交
486
	if (!oldname)
P
Pavel Roskin 已提交
487
		die("cannot rename the current branch while not on any.");
J
Junio C Hamano 已提交
488

489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
	if (snprintf(oldref, sizeof(oldref), "refs/heads/%s", oldname) > sizeof(oldref))
		die("Old branchname too long");

	if (check_ref_format(oldref))
		die("Invalid branch name: %s", oldref);

	if (snprintf(newref, sizeof(newref), "refs/heads/%s", newname) > sizeof(newref))
		die("New branchname too long");

	if (check_ref_format(newref))
		die("Invalid branch name: %s", newref);

	if (resolve_ref(newref, sha1, 1, NULL) && !force)
		die("A branch named '%s' already exists.", newname);

504 505 506 507
	snprintf(logmsg, sizeof(logmsg), "Branch: renamed %s to %s",
		 oldref, newref);

	if (rename_ref(oldref, newref, logmsg))
508 509
		die("Branch rename failed");

510 511
	/* no need to pass logmsg here as HEAD didn't really move */
	if (!strcmp(oldname, head) && create_symref("HEAD", newref, NULL))
512 513 514
		die("Branch renamed to %s, but HEAD is not updated!", newname);
}

L
Lars Hjemli 已提交
515 516
int cmd_branch(int argc, const char **argv, const char *prefix)
{
517
	int delete = 0, force_delete = 0, force_create = 0;
518
	int rename = 0, force_rename = 0;
L
Lars Hjemli 已提交
519
	int verbose = 0, abbrev = DEFAULT_ABBREV, detached = 0;
520
	int reflog = 0, track;
521
	int kinds = REF_LOCAL_BRANCH;
L
Lars Hjemli 已提交
522 523
	int i;

A
Andy Parkins 已提交
524
	git_config(git_branch_config);
525
	track = branch_track_remotes;
L
Lars Hjemli 已提交
526 527 528 529 530 531 532 533 534 535

	for (i = 1; i < argc; i++) {
		const char *arg = argv[i];

		if (arg[0] != '-')
			break;
		if (!strcmp(arg, "--")) {
			i++;
			break;
		}
536 537 538 539 540 541 542 543
		if (!strcmp(arg, "--track")) {
			track = 1;
			continue;
		}
		if (!strcmp(arg, "--no-track")) {
			track = 0;
			continue;
		}
L
Lars Hjemli 已提交
544 545 546 547 548 549 550 551 552 553 554 555 556
		if (!strcmp(arg, "-d")) {
			delete = 1;
			continue;
		}
		if (!strcmp(arg, "-D")) {
			delete = 1;
			force_delete = 1;
			continue;
		}
		if (!strcmp(arg, "-f")) {
			force_create = 1;
			continue;
		}
557 558 559 560 561 562 563 564 565
		if (!strcmp(arg, "-m")) {
			rename = 1;
			continue;
		}
		if (!strcmp(arg, "-M")) {
			rename = 1;
			force_rename = 1;
			continue;
		}
L
Lars Hjemli 已提交
566
		if (!strcmp(arg, "-r")) {
567 568 569 570 571
			kinds = REF_REMOTE_BRANCH;
			continue;
		}
		if (!strcmp(arg, "-a")) {
			kinds = REF_REMOTE_BRANCH | REF_LOCAL_BRANCH;
L
Lars Hjemli 已提交
572 573 574 575 576 577
			continue;
		}
		if (!strcmp(arg, "-l")) {
			reflog = 1;
			continue;
		}
578 579 580 581
		if (!prefixcmp(arg, "--no-abbrev")) {
			abbrev = 0;
			continue;
		}
582
		if (!prefixcmp(arg, "--abbrev=")) {
583 584 585 586 587
			abbrev = strtoul(arg + 9, NULL, 10);
			if (abbrev < MINIMUM_ABBREV)
				abbrev = MINIMUM_ABBREV;
			else if (abbrev > 40)
				abbrev = 40;
588 589 590 591 592 593
			continue;
		}
		if (!strcmp(arg, "-v")) {
			verbose = 1;
			continue;
		}
A
Andy Parkins 已提交
594 595 596 597 598 599 600 601
		if (!strcmp(arg, "--color")) {
			branch_use_color = 1;
			continue;
		}
		if (!strcmp(arg, "--no-color")) {
			branch_use_color = 0;
			continue;
		}
L
Lars Hjemli 已提交
602 603 604
		usage(builtin_branch_usage);
	}

605 606 607 608
	if ((delete && rename) || (delete && force_create) ||
	    (rename && force_create))
		usage(builtin_branch_usage);

L
Lars Hjemli 已提交
609 610 611
	head = xstrdup(resolve_ref("HEAD", head_sha1, 0, NULL));
	if (!head)
		die("Failed to resolve HEAD as a valid ref.");
L
Lars Hjemli 已提交
612 613 614 615
	if (!strcmp(head, "HEAD")) {
		detached = 1;
	}
	else {
616
		if (prefixcmp(head, "refs/heads/"))
L
Lars Hjemli 已提交
617 618 619
			die("HEAD not found below refs/heads!");
		head += 11;
	}
L
Lars Hjemli 已提交
620 621

	if (delete)
622
		return delete_branches(argc - i, argv + i, force_delete, kinds);
L
Lars Hjemli 已提交
623
	else if (i == argc)
L
Lars Hjemli 已提交
624
		print_ref_list(kinds, detached, verbose, abbrev);
625 626 627 628
	else if (rename && (i == argc - 1))
		rename_branch(head, argv[i], force_rename);
	else if (rename && (i == argc - 2))
		rename_branch(argv[i], argv[i + 1], force_rename);
629 630 631
	else if (i == argc - 1 || i == argc - 2)
		create_branch(argv[i], (i == argc - 2) ? argv[i+1] : head,
			      force_create, reflog, track);
L
Lars Hjemli 已提交
632 633 634 635 636
	else
		usage(builtin_branch_usage);

	return 0;
}