Code

3f9e7c2def4795328302863d1f6ca8f0c6e79f27
[git.git] / builtin-branch.c
1 /*
2  * Builtin "git branch"
3  *
4  * Copyright (c) 2006 Kristian Høgsberg <krh@redhat.com>
5  * Based on git-branch.sh by Junio C Hamano.
6  */
8 #include "cache.h"
9 #include "color.h"
10 #include "refs.h"
11 #include "commit.h"
12 #include "builtin.h"
13 #include "remote.h"
15 static const char builtin_branch_usage[] =
16   "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]]";
18 #define REF_UNKNOWN_TYPE    0x00
19 #define REF_LOCAL_BRANCH    0x01
20 #define REF_REMOTE_BRANCH   0x02
21 #define REF_TAG             0x04
23 static const char *head;
24 static unsigned char head_sha1[20];
26 static int branch_track = 1;
28 static int branch_use_color;
29 static char branch_colors[][COLOR_MAXLEN] = {
30         "\033[m",       /* reset */
31         "",             /* PLAIN (normal) */
32         "\033[31m",     /* REMOTE (red) */
33         "",             /* LOCAL (normal) */
34         "\033[32m",     /* CURRENT (green) */
35 };
36 enum color_branch {
37         COLOR_BRANCH_RESET = 0,
38         COLOR_BRANCH_PLAIN = 1,
39         COLOR_BRANCH_REMOTE = 2,
40         COLOR_BRANCH_LOCAL = 3,
41         COLOR_BRANCH_CURRENT = 4,
42 };
44 static int parse_branch_color_slot(const char *var, int ofs)
45 {
46         if (!strcasecmp(var+ofs, "plain"))
47                 return COLOR_BRANCH_PLAIN;
48         if (!strcasecmp(var+ofs, "reset"))
49                 return COLOR_BRANCH_RESET;
50         if (!strcasecmp(var+ofs, "remote"))
51                 return COLOR_BRANCH_REMOTE;
52         if (!strcasecmp(var+ofs, "local"))
53                 return COLOR_BRANCH_LOCAL;
54         if (!strcasecmp(var+ofs, "current"))
55                 return COLOR_BRANCH_CURRENT;
56         die("bad config variable '%s'", var);
57 }
59 static int git_branch_config(const char *var, const char *value)
60 {
61         if (!strcmp(var, "color.branch")) {
62                 branch_use_color = git_config_colorbool(var, value);
63                 return 0;
64         }
65         if (!prefixcmp(var, "color.branch.")) {
66                 int slot = parse_branch_color_slot(var, 13);
67                 color_parse(value, var, branch_colors[slot]);
68                 return 0;
69         }
70         if (!strcmp(var, "branch.autosetupmerge"))
71                         branch_track = git_config_bool(var, value);
73         return git_default_config(var, value);
74 }
76 static const char *branch_get_color(enum color_branch ix)
77 {
78         if (branch_use_color)
79                 return branch_colors[ix];
80         return "";
81 }
83 static int delete_branches(int argc, const char **argv, int force, int kinds)
84 {
85         struct commit *rev, *head_rev = head_rev;
86         unsigned char sha1[20];
87         char *name = NULL;
88         const char *fmt, *remote;
89         char section[PATH_MAX];
90         int i;
91         int ret = 0;
93         switch (kinds) {
94         case REF_REMOTE_BRANCH:
95                 fmt = "refs/remotes/%s";
96                 remote = "remote ";
97                 force = 1;
98                 break;
99         case REF_LOCAL_BRANCH:
100                 fmt = "refs/heads/%s";
101                 remote = "";
102                 break;
103         default:
104                 die("cannot use -a with -d");
105         }
107         if (!force) {
108                 head_rev = lookup_commit_reference(head_sha1);
109                 if (!head_rev)
110                         die("Couldn't look up commit object for HEAD");
111         }
112         for (i = 0; i < argc; i++) {
113                 if (kinds == REF_LOCAL_BRANCH && !strcmp(head, argv[i])) {
114                         error("Cannot delete the branch '%s' "
115                                 "which you are currently on.", argv[i]);
116                         ret = 1;
117                         continue;
118                 }
120                 if (name)
121                         free(name);
123                 name = xstrdup(mkpath(fmt, argv[i]));
124                 if (!resolve_ref(name, sha1, 1, NULL)) {
125                         error("%sbranch '%s' not found.",
126                                         remote, argv[i]);
127                         ret = 1;
128                         continue;
129                 }
131                 rev = lookup_commit_reference(sha1);
132                 if (!rev) {
133                         error("Couldn't look up commit object for '%s'", name);
134                         ret = 1;
135                         continue;
136                 }
138                 /* This checks whether the merge bases of branch and
139                  * HEAD contains branch -- which means that the HEAD
140                  * contains everything in both.
141                  */
143                 if (!force &&
144                     !in_merge_bases(rev, &head_rev, 1)) {
145                         error("The branch '%s' is not a strict subset of "
146                                 "your current HEAD.\n"
147                                 "If you are sure you want to delete it, "
148                                 "run 'git branch -D %s'.", argv[i], argv[i]);
149                         ret = 1;
150                         continue;
151                 }
153                 if (delete_ref(name, sha1)) {
154                         error("Error deleting %sbranch '%s'", remote,
155                                argv[i]);
156                         ret = 1;
157                 } else {
158                         printf("Deleted %sbranch %s.\n", remote, argv[i]);
159                         snprintf(section, sizeof(section), "branch.%s",
160                                  argv[i]);
161                         if (git_config_rename_section(section, NULL) < 0)
162                                 warning("Update of config-file failed");
163                 }
164         }
166         if (name)
167                 free(name);
169         return(ret);
172 struct ref_item {
173         char *name;
174         unsigned int kind;
175         unsigned char sha1[20];
176 };
178 struct ref_list {
179         int index, alloc, maxwidth;
180         struct ref_item *list;
181         int kinds;
182 };
184 static int append_ref(const char *refname, const unsigned char *sha1, int flags, void *cb_data)
186         struct ref_list *ref_list = (struct ref_list*)(cb_data);
187         struct ref_item *newitem;
188         int kind = REF_UNKNOWN_TYPE;
189         int len;
191         /* Detect kind */
192         if (!prefixcmp(refname, "refs/heads/")) {
193                 kind = REF_LOCAL_BRANCH;
194                 refname += 11;
195         } else if (!prefixcmp(refname, "refs/remotes/")) {
196                 kind = REF_REMOTE_BRANCH;
197                 refname += 13;
198         } else if (!prefixcmp(refname, "refs/tags/")) {
199                 kind = REF_TAG;
200                 refname += 10;
201         }
203         /* Don't add types the caller doesn't want */
204         if ((kind & ref_list->kinds) == 0)
205                 return 0;
207         /* Resize buffer */
208         if (ref_list->index >= ref_list->alloc) {
209                 ref_list->alloc = alloc_nr(ref_list->alloc);
210                 ref_list->list = xrealloc(ref_list->list,
211                                 ref_list->alloc * sizeof(struct ref_item));
212         }
214         /* Record the new item */
215         newitem = &(ref_list->list[ref_list->index++]);
216         newitem->name = xstrdup(refname);
217         newitem->kind = kind;
218         hashcpy(newitem->sha1, sha1);
219         len = strlen(newitem->name);
220         if (len > ref_list->maxwidth)
221                 ref_list->maxwidth = len;
223         return 0;
226 static void free_ref_list(struct ref_list *ref_list)
228         int i;
230         for (i = 0; i < ref_list->index; i++)
231                 free(ref_list->list[i].name);
232         free(ref_list->list);
235 static int ref_cmp(const void *r1, const void *r2)
237         struct ref_item *c1 = (struct ref_item *)(r1);
238         struct ref_item *c2 = (struct ref_item *)(r2);
240         if (c1->kind != c2->kind)
241                 return c1->kind - c2->kind;
242         return strcmp(c1->name, c2->name);
245 static void print_ref_item(struct ref_item *item, int maxwidth, int verbose,
246                            int abbrev, int current)
248         char c;
249         int color;
250         struct commit *commit;
252         switch (item->kind) {
253         case REF_LOCAL_BRANCH:
254                 color = COLOR_BRANCH_LOCAL;
255                 break;
256         case REF_REMOTE_BRANCH:
257                 color = COLOR_BRANCH_REMOTE;
258                 break;
259         default:
260                 color = COLOR_BRANCH_PLAIN;
261                 break;
262         }
264         c = ' ';
265         if (current) {
266                 c = '*';
267                 color = COLOR_BRANCH_CURRENT;
268         }
270         if (verbose) {
271                 char *subject = NULL;
272                 unsigned long subject_len = 0;
273                 const char *sub = " **** invalid ref ****";
275                 commit = lookup_commit(item->sha1);
276                 if (commit && !parse_commit(commit)) {
277                         pretty_print_commit(CMIT_FMT_ONELINE, commit, ~0,
278                                             &subject, &subject_len, 0,
279                                             NULL, NULL, 0);
280                         sub = subject;
281                 }
282                 printf("%c %s%-*s%s %s %s\n", c, branch_get_color(color),
283                        maxwidth, item->name,
284                        branch_get_color(COLOR_BRANCH_RESET),
285                        find_unique_abbrev(item->sha1, abbrev), sub);
286                 if (subject)
287                         free(subject);
288         } else {
289                 printf("%c %s%s%s\n", c, branch_get_color(color), item->name,
290                        branch_get_color(COLOR_BRANCH_RESET));
291         }
294 static void print_ref_list(int kinds, int detached, int verbose, int abbrev)
296         int i;
297         struct ref_list ref_list;
299         memset(&ref_list, 0, sizeof(ref_list));
300         ref_list.kinds = kinds;
301         for_each_ref(append_ref, &ref_list);
303         qsort(ref_list.list, ref_list.index, sizeof(struct ref_item), ref_cmp);
305         detached = (detached && (kinds & REF_LOCAL_BRANCH));
306         if (detached) {
307                 struct ref_item item;
308                 item.name = xstrdup("(no branch)");
309                 item.kind = REF_LOCAL_BRANCH;
310                 hashcpy(item.sha1, head_sha1);
311                 if (strlen(item.name) > ref_list.maxwidth)
312                               ref_list.maxwidth = strlen(item.name);
313                 print_ref_item(&item, ref_list.maxwidth, verbose, abbrev, 1);
314                 free(item.name);
315         }
317         for (i = 0; i < ref_list.index; i++) {
318                 int current = !detached &&
319                         (ref_list.list[i].kind == REF_LOCAL_BRANCH) &&
320                         !strcmp(ref_list.list[i].name, head);
321                 print_ref_item(&ref_list.list[i], ref_list.maxwidth, verbose,
322                                abbrev, current);
323         }
325         free_ref_list(&ref_list);
328 struct tracking {
329         struct refspec spec;
330         char *src;
331         const char *remote;
332         int matches;
333 };
335 static int find_tracked_branch(struct remote *remote, void *priv)
337         struct tracking *tracking = priv;
339         if (!remote_find_tracking(remote, &tracking->spec)) {
340                 if (++tracking->matches == 1) {
341                         tracking->src = tracking->spec.src;
342                         tracking->remote = remote->name;
343                 } else {
344                         free(tracking->spec.src);
345                         if (tracking->src) {
346                                 free(tracking->src);
347                                 tracking->src = NULL;
348                         }
349                 }
350                 tracking->spec.src = NULL;
351         }
353         return 0;
357 /*
358  * This is called when new_ref is branched off of orig_ref, and tries
359  * to infer the settings for branch.<new_ref>.{remote,merge} from the
360  * config.
361  */
362 static int setup_tracking(const char *new_ref, const char *orig_ref)
364         char key[1024];
365         struct tracking tracking;
367         if (strlen(new_ref) > 1024 - 7 - 7 - 1)
368                 return error("Tracking not set up: name too long: %s",
369                                 new_ref);
371         memset(&tracking, 0, sizeof(tracking));
372         tracking.spec.dst = (char *)orig_ref;
373         if (for_each_remote(find_tracked_branch, &tracking) ||
374                         !tracking.matches)
375                 return 1;
377         if (tracking.matches > 1)
378                 return error("Not tracking: ambiguous information for ref %s",
379                                 orig_ref);
381         if (tracking.matches == 1) {
382                 sprintf(key, "branch.%s.remote", new_ref);
383                 git_config_set(key, tracking.remote ?  tracking.remote : ".");
384                 sprintf(key, "branch.%s.merge", new_ref);
385                 git_config_set(key, tracking.src);
386                 free(tracking.src);
387                 printf("Branch %s set up to track remote branch %s.\n",
388                                new_ref, orig_ref);
389         }
391         return 0;
394 static void create_branch(const char *name, const char *start_name,
395                           int force, int reflog, int track)
397         struct ref_lock *lock;
398         struct commit *commit;
399         unsigned char sha1[20];
400         char *real_ref, ref[PATH_MAX], msg[PATH_MAX + 20];
401         int forcing = 0;
403         snprintf(ref, sizeof ref, "refs/heads/%s", name);
404         if (check_ref_format(ref))
405                 die("'%s' is not a valid branch name.", name);
407         if (resolve_ref(ref, sha1, 1, NULL)) {
408                 if (!force)
409                         die("A branch named '%s' already exists.", name);
410                 else if (!is_bare_repository() && !strcmp(head, name))
411                         die("Cannot force update the current branch.");
412                 forcing = 1;
413         }
415         real_ref = NULL;
416         if (get_sha1(start_name, sha1))
417                 die("Not a valid object name: '%s'.", start_name);
419         switch (dwim_ref(start_name, strlen(start_name), sha1, &real_ref)) {
420         case 0:
421                 /* Not branching from any existing branch */
422                 real_ref = NULL;
423                 break;
424         case 1:
425                 /* Unique completion -- good */
426                 break;
427         default:
428                 die("Ambiguous object name: '%s'.", start_name);
429                 break;
430         }
432         if ((commit = lookup_commit_reference(sha1)) == NULL)
433                 die("Not a valid branch point: '%s'.", start_name);
434         hashcpy(sha1, commit->object.sha1);
436         lock = lock_any_ref_for_update(ref, NULL, 0);
437         if (!lock)
438                 die("Failed to lock ref for update: %s.", strerror(errno));
440         if (reflog)
441                 log_all_ref_updates = 1;
443         if (forcing)
444                 snprintf(msg, sizeof msg, "branch: Reset from %s",
445                          start_name);
446         else
447                 snprintf(msg, sizeof msg, "branch: Created from %s",
448                          start_name);
450         /* When branching off a remote branch, set up so that git-pull
451            automatically merges from there.  So far, this is only done for
452            remotes registered via .git/config.  */
453         if (real_ref && track)
454                 setup_tracking(name, real_ref);
456         if (write_ref_sha1(lock, sha1, msg) < 0)
457                 die("Failed to write ref: %s.", strerror(errno));
459         if (real_ref)
460                 free(real_ref);
463 static void rename_branch(const char *oldname, const char *newname, int force)
465         char oldref[PATH_MAX], newref[PATH_MAX], logmsg[PATH_MAX*2 + 100];
466         unsigned char sha1[20];
467         char oldsection[PATH_MAX], newsection[PATH_MAX];
469         if (!oldname)
470                 die("cannot rename the current branch while not on any.");
472         if (snprintf(oldref, sizeof(oldref), "refs/heads/%s", oldname) > sizeof(oldref))
473                 die("Old branchname too long");
475         if (check_ref_format(oldref))
476                 die("Invalid branch name: %s", oldref);
478         if (snprintf(newref, sizeof(newref), "refs/heads/%s", newname) > sizeof(newref))
479                 die("New branchname too long");
481         if (check_ref_format(newref))
482                 die("Invalid branch name: %s", newref);
484         if (resolve_ref(newref, sha1, 1, NULL) && !force)
485                 die("A branch named '%s' already exists.", newname);
487         snprintf(logmsg, sizeof(logmsg), "Branch: renamed %s to %s",
488                  oldref, newref);
490         if (rename_ref(oldref, newref, logmsg))
491                 die("Branch rename failed");
493         /* no need to pass logmsg here as HEAD didn't really move */
494         if (!strcmp(oldname, head) && create_symref("HEAD", newref, NULL))
495                 die("Branch renamed to %s, but HEAD is not updated!", newname);
497         snprintf(oldsection, sizeof(oldsection), "branch.%s", oldref + 11);
498         snprintf(newsection, sizeof(newsection), "branch.%s", newref + 11);
499         if (git_config_rename_section(oldsection, newsection) < 0)
500                 die("Branch is renamed, but update of config-file failed");
503 int cmd_branch(int argc, const char **argv, const char *prefix)
505         int delete = 0, force_delete = 0, force_create = 0;
506         int rename = 0, force_rename = 0;
507         int verbose = 0, abbrev = DEFAULT_ABBREV, detached = 0;
508         int reflog = 0, track;
509         int kinds = REF_LOCAL_BRANCH;
510         int i;
512         git_config(git_branch_config);
513         track = branch_track;
515         for (i = 1; i < argc; i++) {
516                 const char *arg = argv[i];
518                 if (arg[0] != '-')
519                         break;
520                 if (!strcmp(arg, "--")) {
521                         i++;
522                         break;
523                 }
524                 if (!strcmp(arg, "--track")) {
525                         track = 1;
526                         continue;
527                 }
528                 if (!strcmp(arg, "--no-track")) {
529                         track = 0;
530                         continue;
531                 }
532                 if (!strcmp(arg, "-d")) {
533                         delete = 1;
534                         continue;
535                 }
536                 if (!strcmp(arg, "-D")) {
537                         delete = 1;
538                         force_delete = 1;
539                         continue;
540                 }
541                 if (!strcmp(arg, "-f")) {
542                         force_create = 1;
543                         continue;
544                 }
545                 if (!strcmp(arg, "-m")) {
546                         rename = 1;
547                         continue;
548                 }
549                 if (!strcmp(arg, "-M")) {
550                         rename = 1;
551                         force_rename = 1;
552                         continue;
553                 }
554                 if (!strcmp(arg, "-r")) {
555                         kinds = REF_REMOTE_BRANCH;
556                         continue;
557                 }
558                 if (!strcmp(arg, "-a")) {
559                         kinds = REF_REMOTE_BRANCH | REF_LOCAL_BRANCH;
560                         continue;
561                 }
562                 if (!strcmp(arg, "-l")) {
563                         reflog = 1;
564                         continue;
565                 }
566                 if (!prefixcmp(arg, "--no-abbrev")) {
567                         abbrev = 0;
568                         continue;
569                 }
570                 if (!prefixcmp(arg, "--abbrev=")) {
571                         abbrev = strtoul(arg + 9, NULL, 10);
572                         if (abbrev < MINIMUM_ABBREV)
573                                 abbrev = MINIMUM_ABBREV;
574                         else if (abbrev > 40)
575                                 abbrev = 40;
576                         continue;
577                 }
578                 if (!strcmp(arg, "-v")) {
579                         verbose = 1;
580                         continue;
581                 }
582                 if (!strcmp(arg, "--color")) {
583                         branch_use_color = 1;
584                         continue;
585                 }
586                 if (!strcmp(arg, "--no-color")) {
587                         branch_use_color = 0;
588                         continue;
589                 }
590                 usage(builtin_branch_usage);
591         }
593         if ((delete && rename) || (delete && force_create) ||
594             (rename && force_create))
595                 usage(builtin_branch_usage);
597         head = resolve_ref("HEAD", head_sha1, 0, NULL);
598         if (!head)
599                 die("Failed to resolve HEAD as a valid ref.");
600         head = xstrdup(head);
601         if (!strcmp(head, "HEAD")) {
602                 detached = 1;
603         }
604         else {
605                 if (prefixcmp(head, "refs/heads/"))
606                         die("HEAD not found below refs/heads!");
607                 head += 11;
608         }
610         if (delete)
611                 return delete_branches(argc - i, argv + i, force_delete, kinds);
612         else if (i == argc)
613                 print_ref_list(kinds, detached, verbose, abbrev);
614         else if (rename && (i == argc - 1))
615                 rename_branch(head, argv[i], force_rename);
616         else if (rename && (i == argc - 2))
617                 rename_branch(argv[i], argv[i + 1], force_rename);
618         else if (i == argc - 1 || i == argc - 2)
619                 create_branch(argv[i], (i == argc - 2) ? argv[i+1] : head,
620                               force_create, reflog, track);
621         else
622                 usage(builtin_branch_usage);
624         return 0;