On error, do not list all commands, but point to --help option
[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  */
7
8 #include "cache.h"
9 #include "color.h"
10 #include "refs.h"
11 #include "commit.h"
12 #include "builtin.h"
13 #include "remote.h"
14
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]]";
17
18 #define REF_UNKNOWN_TYPE    0x00
19 #define REF_LOCAL_BRANCH    0x01
20 #define REF_REMOTE_BRANCH   0x02
21 #define REF_TAG             0x04
22
23 static const char *head;
24 static unsigned char head_sha1[20];
25
26 static int branch_track = 1;
27
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 };
43
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 }
58
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);
72
73         return git_default_config(var, value);
74 }
75
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 }
82
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;
92
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         }
106
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                 }
119
120                 if (name)
121                         free(name);
122
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                 }
130
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                 }
137
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                  */
142
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                 }
152
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         }
165
166         if (name)
167                 free(name);
168
169         return(ret);
170 }
171
172 struct ref_item {
173         char *name;
174         unsigned int kind;
175         unsigned char sha1[20];
176 };
177
178 struct ref_list {
179         int index, alloc, maxwidth;
180         struct ref_item *list;
181         int kinds;
182 };
183
184 static int append_ref(const char *refname, const unsigned char *sha1, int flags, void *cb_data)
185 {
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;
190
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         }
202
203         /* Don't add types the caller doesn't want */
204         if ((kind & ref_list->kinds) == 0)
205                 return 0;
206
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         }
213
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;
222
223         return 0;
224 }
225
226 static void free_ref_list(struct ref_list *ref_list)
227 {
228         int i;
229
230         for (i = 0; i < ref_list->index; i++)
231                 free(ref_list->list[i].name);
232         free(ref_list->list);
233 }
234
235 static int ref_cmp(const void *r1, const void *r2)
236 {
237         struct ref_item *c1 = (struct ref_item *)(r1);
238         struct ref_item *c2 = (struct ref_item *)(r2);
239
240         if (c1->kind != c2->kind)
241                 return c1->kind - c2->kind;
242         return strcmp(c1->name, c2->name);
243 }
244
245 static void print_ref_item(struct ref_item *item, int maxwidth, int verbose,
246                            int abbrev, int current)
247 {
248         char c;
249         int color;
250         struct commit *commit;
251
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         }
263
264         c = ' ';
265         if (current) {
266                 c = '*';
267                 color = COLOR_BRANCH_CURRENT;
268         }
269
270         if (verbose) {
271                 struct strbuf subject;
272                 const char *sub = " **** invalid ref ****";
273
274                 strbuf_init(&subject, 0);
275
276                 commit = lookup_commit(item->sha1);
277                 if (commit && !parse_commit(commit)) {
278                         pretty_print_commit(CMIT_FMT_ONELINE, commit,
279                                             &subject, 0, NULL, NULL, 0);
280                         sub = subject.buf;
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                 strbuf_release(&subject);
287         } else {
288                 printf("%c %s%s%s\n", c, branch_get_color(color), item->name,
289                        branch_get_color(COLOR_BRANCH_RESET));
290         }
291 }
292
293 static void print_ref_list(int kinds, int detached, int verbose, int abbrev)
294 {
295         int i;
296         struct ref_list ref_list;
297
298         memset(&ref_list, 0, sizeof(ref_list));
299         ref_list.kinds = kinds;
300         for_each_ref(append_ref, &ref_list);
301
302         qsort(ref_list.list, ref_list.index, sizeof(struct ref_item), ref_cmp);
303
304         detached = (detached && (kinds & REF_LOCAL_BRANCH));
305         if (detached) {
306                 struct ref_item item;
307                 item.name = xstrdup("(no branch)");
308                 item.kind = REF_LOCAL_BRANCH;
309                 hashcpy(item.sha1, head_sha1);
310                 if (strlen(item.name) > ref_list.maxwidth)
311                               ref_list.maxwidth = strlen(item.name);
312                 print_ref_item(&item, ref_list.maxwidth, verbose, abbrev, 1);
313                 free(item.name);
314         }
315
316         for (i = 0; i < ref_list.index; i++) {
317                 int current = !detached &&
318                         (ref_list.list[i].kind == REF_LOCAL_BRANCH) &&
319                         !strcmp(ref_list.list[i].name, head);
320                 print_ref_item(&ref_list.list[i], ref_list.maxwidth, verbose,
321                                abbrev, current);
322         }
323
324         free_ref_list(&ref_list);
325 }
326
327 struct tracking {
328         struct refspec spec;
329         char *src;
330         const char *remote;
331         int matches;
332 };
333
334 static int find_tracked_branch(struct remote *remote, void *priv)
335 {
336         struct tracking *tracking = priv;
337
338         if (!remote_find_tracking(remote, &tracking->spec)) {
339                 if (++tracking->matches == 1) {
340                         tracking->src = tracking->spec.src;
341                         tracking->remote = remote->name;
342                 } else {
343                         free(tracking->spec.src);
344                         if (tracking->src) {
345                                 free(tracking->src);
346                                 tracking->src = NULL;
347                         }
348                 }
349                 tracking->spec.src = NULL;
350         }
351
352         return 0;
353 }
354
355
356 /*
357  * This is called when new_ref is branched off of orig_ref, and tries
358  * to infer the settings for branch.<new_ref>.{remote,merge} from the
359  * config.
360  */
361 static int setup_tracking(const char *new_ref, const char *orig_ref)
362 {
363         char key[1024];
364         struct tracking tracking;
365
366         if (strlen(new_ref) > 1024 - 7 - 7 - 1)
367                 return error("Tracking not set up: name too long: %s",
368                                 new_ref);
369
370         memset(&tracking, 0, sizeof(tracking));
371         tracking.spec.dst = (char *)orig_ref;
372         if (for_each_remote(find_tracked_branch, &tracking) ||
373                         !tracking.matches)
374                 return 1;
375
376         if (tracking.matches > 1)
377                 return error("Not tracking: ambiguous information for ref %s",
378                                 orig_ref);
379
380         if (tracking.matches == 1) {
381                 sprintf(key, "branch.%s.remote", new_ref);
382                 git_config_set(key, tracking.remote ?  tracking.remote : ".");
383                 sprintf(key, "branch.%s.merge", new_ref);
384                 git_config_set(key, tracking.src);
385                 free(tracking.src);
386                 printf("Branch %s set up to track remote branch %s.\n",
387                                new_ref, orig_ref);
388         }
389
390         return 0;
391 }
392
393 static void create_branch(const char *name, const char *start_name,
394                           int force, int reflog, int track)
395 {
396         struct ref_lock *lock;
397         struct commit *commit;
398         unsigned char sha1[20];
399         char *real_ref, ref[PATH_MAX], msg[PATH_MAX + 20];
400         int forcing = 0;
401
402         snprintf(ref, sizeof ref, "refs/heads/%s", name);
403         if (check_ref_format(ref))
404                 die("'%s' is not a valid branch name.", name);
405
406         if (resolve_ref(ref, sha1, 1, NULL)) {
407                 if (!force)
408                         die("A branch named '%s' already exists.", name);
409                 else if (!is_bare_repository() && !strcmp(head, name))
410                         die("Cannot force update the current branch.");
411                 forcing = 1;
412         }
413
414         real_ref = NULL;
415         if (get_sha1(start_name, sha1))
416                 die("Not a valid object name: '%s'.", start_name);
417
418         switch (dwim_ref(start_name, strlen(start_name), sha1, &real_ref)) {
419         case 0:
420                 /* Not branching from any existing branch */
421                 real_ref = NULL;
422                 break;
423         case 1:
424                 /* Unique completion -- good */
425                 break;
426         default:
427                 die("Ambiguous object name: '%s'.", start_name);
428                 break;
429         }
430
431         if ((commit = lookup_commit_reference(sha1)) == NULL)
432                 die("Not a valid branch point: '%s'.", start_name);
433         hashcpy(sha1, commit->object.sha1);
434
435         lock = lock_any_ref_for_update(ref, NULL, 0);
436         if (!lock)
437                 die("Failed to lock ref for update: %s.", strerror(errno));
438
439         if (reflog)
440                 log_all_ref_updates = 1;
441
442         if (forcing)
443                 snprintf(msg, sizeof msg, "branch: Reset from %s",
444                          start_name);
445         else
446                 snprintf(msg, sizeof msg, "branch: Created from %s",
447                          start_name);
448
449         /* When branching off a remote branch, set up so that git-pull
450            automatically merges from there.  So far, this is only done for
451            remotes registered via .git/config.  */
452         if (real_ref && track)
453                 setup_tracking(name, real_ref);
454
455         if (write_ref_sha1(lock, sha1, msg) < 0)
456                 die("Failed to write ref: %s.", strerror(errno));
457
458         if (real_ref)
459                 free(real_ref);
460 }
461
462 static void rename_branch(const char *oldname, const char *newname, int force)
463 {
464         char oldref[PATH_MAX], newref[PATH_MAX], logmsg[PATH_MAX*2 + 100];
465         unsigned char sha1[20];
466         char oldsection[PATH_MAX], newsection[PATH_MAX];
467
468         if (!oldname)
469                 die("cannot rename the current branch while not on any.");
470
471         if (snprintf(oldref, sizeof(oldref), "refs/heads/%s", oldname) > sizeof(oldref))
472                 die("Old branchname too long");
473
474         if (check_ref_format(oldref))
475                 die("Invalid branch name: %s", oldref);
476
477         if (snprintf(newref, sizeof(newref), "refs/heads/%s", newname) > sizeof(newref))
478                 die("New branchname too long");
479
480         if (check_ref_format(newref))
481                 die("Invalid branch name: %s", newref);
482
483         if (resolve_ref(newref, sha1, 1, NULL) && !force)
484                 die("A branch named '%s' already exists.", newname);
485
486         snprintf(logmsg, sizeof(logmsg), "Branch: renamed %s to %s",
487                  oldref, newref);
488
489         if (rename_ref(oldref, newref, logmsg))
490                 die("Branch rename failed");
491
492         /* no need to pass logmsg here as HEAD didn't really move */
493         if (!strcmp(oldname, head) && create_symref("HEAD", newref, NULL))
494                 die("Branch renamed to %s, but HEAD is not updated!", newname);
495
496         snprintf(oldsection, sizeof(oldsection), "branch.%s", oldref + 11);
497         snprintf(newsection, sizeof(newsection), "branch.%s", newref + 11);
498         if (git_config_rename_section(oldsection, newsection) < 0)
499                 die("Branch is renamed, but update of config-file failed");
500 }
501
502 int cmd_branch(int argc, const char **argv, const char *prefix)
503 {
504         int delete = 0, force_delete = 0, force_create = 0;
505         int rename = 0, force_rename = 0;
506         int verbose = 0, abbrev = DEFAULT_ABBREV, detached = 0;
507         int reflog = 0, track;
508         int kinds = REF_LOCAL_BRANCH;
509         int i;
510
511         git_config(git_branch_config);
512         track = branch_track;
513
514         for (i = 1; i < argc; i++) {
515                 const char *arg = argv[i];
516
517                 if (arg[0] != '-')
518                         break;
519                 if (!strcmp(arg, "--")) {
520                         i++;
521                         break;
522                 }
523                 if (!strcmp(arg, "--track")) {
524                         track = 1;
525                         continue;
526                 }
527                 if (!strcmp(arg, "--no-track")) {
528                         track = 0;
529                         continue;
530                 }
531                 if (!strcmp(arg, "-d")) {
532                         delete = 1;
533                         continue;
534                 }
535                 if (!strcmp(arg, "-D")) {
536                         delete = 1;
537                         force_delete = 1;
538                         continue;
539                 }
540                 if (!strcmp(arg, "-f")) {
541                         force_create = 1;
542                         continue;
543                 }
544                 if (!strcmp(arg, "-m")) {
545                         rename = 1;
546                         continue;
547                 }
548                 if (!strcmp(arg, "-M")) {
549                         rename = 1;
550                         force_rename = 1;
551                         continue;
552                 }
553                 if (!strcmp(arg, "-r")) {
554                         kinds = REF_REMOTE_BRANCH;
555                         continue;
556                 }
557                 if (!strcmp(arg, "-a")) {
558                         kinds = REF_REMOTE_BRANCH | REF_LOCAL_BRANCH;
559                         continue;
560                 }
561                 if (!strcmp(arg, "-l")) {
562                         reflog = 1;
563                         continue;
564                 }
565                 if (!prefixcmp(arg, "--no-abbrev")) {
566                         abbrev = 0;
567                         continue;
568                 }
569                 if (!prefixcmp(arg, "--abbrev=")) {
570                         abbrev = strtoul(arg + 9, NULL, 10);
571                         if (abbrev < MINIMUM_ABBREV)
572                                 abbrev = MINIMUM_ABBREV;
573                         else if (abbrev > 40)
574                                 abbrev = 40;
575                         continue;
576                 }
577                 if (!strcmp(arg, "-v")) {
578                         verbose = 1;
579                         continue;
580                 }
581                 if (!strcmp(arg, "--color")) {
582                         branch_use_color = 1;
583                         continue;
584                 }
585                 if (!strcmp(arg, "--no-color")) {
586                         branch_use_color = 0;
587                         continue;
588                 }
589                 usage(builtin_branch_usage);
590         }
591
592         if ((delete && rename) || (delete && force_create) ||
593             (rename && force_create))
594                 usage(builtin_branch_usage);
595
596         head = resolve_ref("HEAD", head_sha1, 0, NULL);
597         if (!head)
598                 die("Failed to resolve HEAD as a valid ref.");
599         head = xstrdup(head);
600         if (!strcmp(head, "HEAD")) {
601                 detached = 1;
602         }
603         else {
604                 if (prefixcmp(head, "refs/heads/"))
605                         die("HEAD not found below refs/heads!");
606                 head += 11;
607         }
608
609         if (delete)
610                 return delete_branches(argc - i, argv + i, force_delete, kinds);
611         else if (i == argc)
612                 print_ref_list(kinds, detached, verbose, abbrev);
613         else if (rename && (i == argc - 1))
614                 rename_branch(head, argv[i], force_rename);
615         else if (rename && (i == argc - 2))
616                 rename_branch(argv[i], argv[i + 1], force_rename);
617         else if (i == argc - 1 || i == argc - 2)
618                 create_branch(argv[i], (i == argc - 2) ? argv[i+1] : head,
619                               force_create, reflog, track);
620         else
621                 usage(builtin_branch_usage);
622
623         return 0;
624 }