3708a50ebead093f54b7f5c837b0390a8d8b76e0
   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#include "parse-options.h"
  15#include "branch.h"
  16
  17static const char * const builtin_branch_usage[] = {
  18        "git branch [options] [-r | -a] [--merged | --no-merged]",
  19        "git branch [options] [-l] [-f] <branchname> [<start-point>]",
  20        "git branch [options] [-r] (-d | -D) <branchname>",
  21        "git branch [options] (-m | -M) [<oldbranch>] <newbranch>",
  22        NULL
  23};
  24
  25#define REF_LOCAL_BRANCH    0x01
  26#define REF_REMOTE_BRANCH   0x02
  27
  28static const char *head;
  29static unsigned char head_sha1[20];
  30
  31static int branch_use_color = -1;
  32static char branch_colors[][COLOR_MAXLEN] = {
  33        "\033[m",       /* reset */
  34        "",             /* PLAIN (normal) */
  35        "\033[31m",     /* REMOTE (red) */
  36        "",             /* LOCAL (normal) */
  37        "\033[32m",     /* CURRENT (green) */
  38};
  39enum color_branch {
  40        COLOR_BRANCH_RESET = 0,
  41        COLOR_BRANCH_PLAIN = 1,
  42        COLOR_BRANCH_REMOTE = 2,
  43        COLOR_BRANCH_LOCAL = 3,
  44        COLOR_BRANCH_CURRENT = 4,
  45};
  46
  47static enum merge_filter {
  48        NO_FILTER = 0,
  49        SHOW_NOT_MERGED,
  50        SHOW_MERGED,
  51} merge_filter;
  52static unsigned char merge_filter_ref[20];
  53
  54static int parse_branch_color_slot(const char *var, int ofs)
  55{
  56        if (!strcasecmp(var+ofs, "plain"))
  57                return COLOR_BRANCH_PLAIN;
  58        if (!strcasecmp(var+ofs, "reset"))
  59                return COLOR_BRANCH_RESET;
  60        if (!strcasecmp(var+ofs, "remote"))
  61                return COLOR_BRANCH_REMOTE;
  62        if (!strcasecmp(var+ofs, "local"))
  63                return COLOR_BRANCH_LOCAL;
  64        if (!strcasecmp(var+ofs, "current"))
  65                return COLOR_BRANCH_CURRENT;
  66        die("bad config variable '%s'", var);
  67}
  68
  69static int git_branch_config(const char *var, const char *value, void *cb)
  70{
  71        if (!strcmp(var, "color.branch")) {
  72                branch_use_color = git_config_colorbool(var, value, -1);
  73                return 0;
  74        }
  75        if (!prefixcmp(var, "color.branch.")) {
  76                int slot = parse_branch_color_slot(var, 13);
  77                if (!value)
  78                        return config_error_nonbool(var);
  79                color_parse(value, var, branch_colors[slot]);
  80                return 0;
  81        }
  82        return git_color_default_config(var, value, cb);
  83}
  84
  85static const char *branch_get_color(enum color_branch ix)
  86{
  87        if (branch_use_color > 0)
  88                return branch_colors[ix];
  89        return "";
  90}
  91
  92static int delete_branches(int argc, const char **argv, int force, int kinds)
  93{
  94        struct commit *rev, *head_rev = head_rev;
  95        unsigned char sha1[20];
  96        char *name = NULL;
  97        const char *fmt, *remote;
  98        char section[PATH_MAX];
  99        int i;
 100        int ret = 0;
 101
 102        switch (kinds) {
 103        case REF_REMOTE_BRANCH:
 104                fmt = "refs/remotes/%s";
 105                remote = "remote ";
 106                force = 1;
 107                break;
 108        case REF_LOCAL_BRANCH:
 109                fmt = "refs/heads/%s";
 110                remote = "";
 111                break;
 112        default:
 113                die("cannot use -a with -d");
 114        }
 115
 116        if (!force) {
 117                head_rev = lookup_commit_reference(head_sha1);
 118                if (!head_rev)
 119                        die("Couldn't look up commit object for HEAD");
 120        }
 121        for (i = 0; i < argc; i++) {
 122                if (kinds == REF_LOCAL_BRANCH && !strcmp(head, argv[i])) {
 123                        error("Cannot delete the branch '%s' "
 124                                "which you are currently on.", argv[i]);
 125                        ret = 1;
 126                        continue;
 127                }
 128
 129                free(name);
 130
 131                name = xstrdup(mkpath(fmt, argv[i]));
 132                if (!resolve_ref(name, sha1, 1, NULL)) {
 133                        error("%sbranch '%s' not found.",
 134                                        remote, argv[i]);
 135                        ret = 1;
 136                        continue;
 137                }
 138
 139                rev = lookup_commit_reference(sha1);
 140                if (!rev) {
 141                        error("Couldn't look up commit object for '%s'", name);
 142                        ret = 1;
 143                        continue;
 144                }
 145
 146                /* This checks whether the merge bases of branch and
 147                 * HEAD contains branch -- which means that the HEAD
 148                 * contains everything in both.
 149                 */
 150
 151                if (!force &&
 152                    !in_merge_bases(rev, &head_rev, 1)) {
 153                        error("The branch '%s' is not an ancestor of "
 154                                "your current HEAD.\n"
 155                                "If you are sure you want to delete it, "
 156                                "run 'git branch -D %s'.", argv[i], argv[i]);
 157                        ret = 1;
 158                        continue;
 159                }
 160
 161                if (delete_ref(name, sha1)) {
 162                        error("Error deleting %sbranch '%s'", remote,
 163                               argv[i]);
 164                        ret = 1;
 165                } else {
 166                        printf("Deleted %sbranch %s.\n", remote, argv[i]);
 167                        snprintf(section, sizeof(section), "branch.%s",
 168                                 argv[i]);
 169                        if (git_config_rename_section(section, NULL) < 0)
 170                                warning("Update of config-file failed");
 171                }
 172        }
 173
 174        free(name);
 175
 176        return(ret);
 177}
 178
 179struct ref_item {
 180        char *name;
 181        unsigned int kind;
 182        unsigned char sha1[20];
 183};
 184
 185struct ref_list {
 186        int index, alloc, maxwidth;
 187        struct ref_item *list;
 188        struct commit_list *with_commit;
 189        int kinds;
 190};
 191
 192static int has_commit(const unsigned char *sha1, struct commit_list *with_commit)
 193{
 194        struct commit *commit;
 195
 196        if (!with_commit)
 197                return 1;
 198        commit = lookup_commit_reference_gently(sha1, 1);
 199        if (!commit)
 200                return 0;
 201        while (with_commit) {
 202                struct commit *other;
 203
 204                other = with_commit->item;
 205                with_commit = with_commit->next;
 206                if (in_merge_bases(other, &commit, 1))
 207                        return 1;
 208        }
 209        return 0;
 210}
 211
 212static int append_ref(const char *refname, const unsigned char *sha1, int flags, void *cb_data)
 213{
 214        struct ref_list *ref_list = (struct ref_list*)(cb_data);
 215        struct ref_item *newitem;
 216        int kind;
 217        int len;
 218        static struct commit_list branch;
 219
 220        /* Detect kind */
 221        if (!prefixcmp(refname, "refs/heads/")) {
 222                kind = REF_LOCAL_BRANCH;
 223                refname += 11;
 224        } else if (!prefixcmp(refname, "refs/remotes/")) {
 225                kind = REF_REMOTE_BRANCH;
 226                refname += 13;
 227        } else
 228                return 0;
 229
 230        /* Filter with with_commit if specified */
 231        if (!has_commit(sha1, ref_list->with_commit))
 232                return 0;
 233
 234        /* Don't add types the caller doesn't want */
 235        if ((kind & ref_list->kinds) == 0)
 236                return 0;
 237
 238        if (merge_filter != NO_FILTER) {
 239                branch.item = lookup_commit_reference_gently(sha1, 1);
 240                if (!branch.item)
 241                        die("Unable to lookup tip of branch %s", refname);
 242                if (merge_filter == SHOW_NOT_MERGED &&
 243                    has_commit(merge_filter_ref, &branch))
 244                        return 0;
 245                if (merge_filter == SHOW_MERGED &&
 246                    !has_commit(merge_filter_ref, &branch))
 247                        return 0;
 248        }
 249
 250        /* Resize buffer */
 251        if (ref_list->index >= ref_list->alloc) {
 252                ref_list->alloc = alloc_nr(ref_list->alloc);
 253                ref_list->list = xrealloc(ref_list->list,
 254                                ref_list->alloc * sizeof(struct ref_item));
 255        }
 256
 257        /* Record the new item */
 258        newitem = &(ref_list->list[ref_list->index++]);
 259        newitem->name = xstrdup(refname);
 260        newitem->kind = kind;
 261        hashcpy(newitem->sha1, sha1);
 262        len = strlen(newitem->name);
 263        if (len > ref_list->maxwidth)
 264                ref_list->maxwidth = len;
 265
 266        return 0;
 267}
 268
 269static void free_ref_list(struct ref_list *ref_list)
 270{
 271        int i;
 272
 273        for (i = 0; i < ref_list->index; i++)
 274                free(ref_list->list[i].name);
 275        free(ref_list->list);
 276}
 277
 278static int ref_cmp(const void *r1, const void *r2)
 279{
 280        struct ref_item *c1 = (struct ref_item *)(r1);
 281        struct ref_item *c2 = (struct ref_item *)(r2);
 282
 283        if (c1->kind != c2->kind)
 284                return c1->kind - c2->kind;
 285        return strcmp(c1->name, c2->name);
 286}
 287
 288static void fill_tracking_info(char *stat, const char *branch_name)
 289{
 290        int ours, theirs;
 291        struct branch *branch = branch_get(branch_name);
 292
 293        if (!stat_tracking_info(branch, &ours, &theirs) || (!ours && !theirs))
 294                return;
 295        if (!ours)
 296                sprintf(stat, "[behind %d] ", theirs);
 297        else if (!theirs)
 298                sprintf(stat, "[ahead %d] ", ours);
 299        else
 300                sprintf(stat, "[ahead %d, behind %d] ", ours, theirs);
 301}
 302
 303static void print_ref_item(struct ref_item *item, int maxwidth, int verbose,
 304                           int abbrev, int current)
 305{
 306        char c;
 307        int color;
 308        struct commit *commit;
 309
 310        switch (item->kind) {
 311        case REF_LOCAL_BRANCH:
 312                color = COLOR_BRANCH_LOCAL;
 313                break;
 314        case REF_REMOTE_BRANCH:
 315                color = COLOR_BRANCH_REMOTE;
 316                break;
 317        default:
 318                color = COLOR_BRANCH_PLAIN;
 319                break;
 320        }
 321
 322        c = ' ';
 323        if (current) {
 324                c = '*';
 325                color = COLOR_BRANCH_CURRENT;
 326        }
 327
 328        if (verbose) {
 329                struct strbuf subject;
 330                const char *sub = " **** invalid ref ****";
 331                char stat[128];
 332
 333                strbuf_init(&subject, 0);
 334                stat[0] = '\0';
 335
 336                commit = lookup_commit(item->sha1);
 337                if (commit && !parse_commit(commit)) {
 338                        pretty_print_commit(CMIT_FMT_ONELINE, commit,
 339                                            &subject, 0, NULL, NULL, 0, 0);
 340                        sub = subject.buf;
 341                }
 342
 343                if (item->kind == REF_LOCAL_BRANCH)
 344                        fill_tracking_info(stat, item->name);
 345
 346                printf("%c %s%-*s%s %s %s%s\n", c, branch_get_color(color),
 347                       maxwidth, item->name,
 348                       branch_get_color(COLOR_BRANCH_RESET),
 349                       find_unique_abbrev(item->sha1, abbrev),
 350                       stat, sub);
 351                strbuf_release(&subject);
 352        } else {
 353                printf("%c %s%s%s\n", c, branch_get_color(color), item->name,
 354                       branch_get_color(COLOR_BRANCH_RESET));
 355        }
 356}
 357
 358static void print_ref_list(int kinds, int detached, int verbose, int abbrev, struct commit_list *with_commit)
 359{
 360        int i;
 361        struct ref_list ref_list;
 362
 363        memset(&ref_list, 0, sizeof(ref_list));
 364        ref_list.kinds = kinds;
 365        ref_list.with_commit = with_commit;
 366        for_each_ref(append_ref, &ref_list);
 367
 368        qsort(ref_list.list, ref_list.index, sizeof(struct ref_item), ref_cmp);
 369
 370        detached = (detached && (kinds & REF_LOCAL_BRANCH));
 371        if (detached && has_commit(head_sha1, with_commit)) {
 372                struct ref_item item;
 373                item.name = xstrdup("(no branch)");
 374                item.kind = REF_LOCAL_BRANCH;
 375                hashcpy(item.sha1, head_sha1);
 376                if (strlen(item.name) > ref_list.maxwidth)
 377                              ref_list.maxwidth = strlen(item.name);
 378                print_ref_item(&item, ref_list.maxwidth, verbose, abbrev, 1);
 379                free(item.name);
 380        }
 381
 382        for (i = 0; i < ref_list.index; i++) {
 383                int current = !detached &&
 384                        (ref_list.list[i].kind == REF_LOCAL_BRANCH) &&
 385                        !strcmp(ref_list.list[i].name, head);
 386                print_ref_item(&ref_list.list[i], ref_list.maxwidth, verbose,
 387                               abbrev, current);
 388        }
 389
 390        free_ref_list(&ref_list);
 391}
 392
 393static void rename_branch(const char *oldname, const char *newname, int force)
 394{
 395        char oldref[PATH_MAX], newref[PATH_MAX], logmsg[PATH_MAX*2 + 100];
 396        unsigned char sha1[20];
 397        char oldsection[PATH_MAX], newsection[PATH_MAX];
 398
 399        if (!oldname)
 400                die("cannot rename the current branch while not on any.");
 401
 402        if (snprintf(oldref, sizeof(oldref), "refs/heads/%s", oldname) > sizeof(oldref))
 403                die("Old branchname too long");
 404
 405        if (check_ref_format(oldref))
 406                die("Invalid branch name: %s", oldref);
 407
 408        if (snprintf(newref, sizeof(newref), "refs/heads/%s", newname) > sizeof(newref))
 409                die("New branchname too long");
 410
 411        if (check_ref_format(newref))
 412                die("Invalid branch name: %s", newref);
 413
 414        if (resolve_ref(newref, sha1, 1, NULL) && !force)
 415                die("A branch named '%s' already exists.", newname);
 416
 417        snprintf(logmsg, sizeof(logmsg), "Branch: renamed %s to %s",
 418                 oldref, newref);
 419
 420        if (rename_ref(oldref, newref, logmsg))
 421                die("Branch rename failed");
 422
 423        /* no need to pass logmsg here as HEAD didn't really move */
 424        if (!strcmp(oldname, head) && create_symref("HEAD", newref, NULL))
 425                die("Branch renamed to %s, but HEAD is not updated!", newname);
 426
 427        snprintf(oldsection, sizeof(oldsection), "branch.%s", oldref + 11);
 428        snprintf(newsection, sizeof(newsection), "branch.%s", newref + 11);
 429        if (git_config_rename_section(oldsection, newsection) < 0)
 430                die("Branch is renamed, but update of config-file failed");
 431}
 432
 433static int opt_parse_with_commit(const struct option *opt, const char *arg, int unset)
 434{
 435        unsigned char sha1[20];
 436        struct commit *commit;
 437
 438        if (!arg)
 439                return -1;
 440        if (get_sha1(arg, sha1))
 441                die("malformed object name %s", arg);
 442        commit = lookup_commit_reference(sha1);
 443        if (!commit)
 444                die("no such commit %s", arg);
 445        commit_list_insert(commit, opt->value);
 446        return 0;
 447}
 448
 449static int opt_parse_merge_filter(const struct option *opt, const char *arg, int unset)
 450{
 451        merge_filter = ((opt->long_name[0] == 'n')
 452                        ? SHOW_NOT_MERGED
 453                        : SHOW_MERGED);
 454        if (unset)
 455                merge_filter = SHOW_NOT_MERGED; /* b/c for --no-merged */
 456        if (!arg)
 457                arg = "HEAD";
 458        if (get_sha1(arg, merge_filter_ref))
 459                die("malformed object name %s", arg);
 460        return 0;
 461}
 462
 463int cmd_branch(int argc, const char **argv, const char *prefix)
 464{
 465        int delete = 0, rename = 0, force_create = 0;
 466        int verbose = 0, abbrev = DEFAULT_ABBREV, detached = 0;
 467        int reflog = 0;
 468        enum branch_track track;
 469        int kinds = REF_LOCAL_BRANCH;
 470        struct commit_list *with_commit = NULL;
 471
 472        struct option options[] = {
 473                OPT_GROUP("Generic options"),
 474                OPT__VERBOSE(&verbose),
 475                OPT_SET_INT( 0 , "track",  &track, "set up tracking mode (see git-pull(1))",
 476                        BRANCH_TRACK_EXPLICIT),
 477                OPT_BOOLEAN( 0 , "color",  &branch_use_color, "use colored output"),
 478                OPT_SET_INT('r', NULL,     &kinds, "act on remote-tracking branches",
 479                        REF_REMOTE_BRANCH),
 480                {
 481                        OPTION_CALLBACK, 0, "contains", &with_commit, "commit",
 482                        "print only branches that contain the commit",
 483                        PARSE_OPT_LASTARG_DEFAULT,
 484                        opt_parse_with_commit, (intptr_t)"HEAD",
 485                },
 486                {
 487                        OPTION_CALLBACK, 0, "with", &with_commit, "commit",
 488                        "print only branches that contain the commit",
 489                        PARSE_OPT_HIDDEN | PARSE_OPT_LASTARG_DEFAULT,
 490                        opt_parse_with_commit, (intptr_t) "HEAD",
 491                },
 492                OPT__ABBREV(&abbrev),
 493
 494                OPT_GROUP("Specific git-branch actions:"),
 495                OPT_SET_INT('a', NULL, &kinds, "list both remote-tracking and local branches",
 496                        REF_REMOTE_BRANCH | REF_LOCAL_BRANCH),
 497                OPT_BIT('d', NULL, &delete, "delete fully merged branch", 1),
 498                OPT_BIT('D', NULL, &delete, "delete branch (even if not merged)", 2),
 499                OPT_BIT('m', NULL, &rename, "move/rename a branch and its reflog", 1),
 500                OPT_BIT('M', NULL, &rename, "move/rename a branch, even if target exists", 2),
 501                OPT_BOOLEAN('l', NULL, &reflog, "create the branch's reflog"),
 502                OPT_BOOLEAN('f', NULL, &force_create, "force creation (when already exists)"),
 503                {
 504                        OPTION_CALLBACK, 0, "no-merged", &merge_filter_ref,
 505                        "commit", "print only not merged branches",
 506                        PARSE_OPT_LASTARG_DEFAULT | PARSE_OPT_NONEG,
 507                        opt_parse_merge_filter, (intptr_t) "HEAD",
 508                },
 509                {
 510                        OPTION_CALLBACK, 0, "merged", &merge_filter_ref,
 511                        "commit", "print only merged branches",
 512                        PARSE_OPT_LASTARG_DEFAULT | PARSE_OPT_NONEG,
 513                        opt_parse_merge_filter, (intptr_t) "HEAD",
 514                },
 515                OPT_END(),
 516        };
 517
 518        git_config(git_branch_config, NULL);
 519
 520        if (branch_use_color == -1)
 521                branch_use_color = git_use_color_default;
 522
 523        track = git_branch_track;
 524
 525        head = resolve_ref("HEAD", head_sha1, 0, NULL);
 526        if (!head)
 527                die("Failed to resolve HEAD as a valid ref.");
 528        head = xstrdup(head);
 529        if (!strcmp(head, "HEAD")) {
 530                detached = 1;
 531        } else {
 532                if (prefixcmp(head, "refs/heads/"))
 533                        die("HEAD not found below refs/heads!");
 534                head += 11;
 535        }
 536        hashcpy(merge_filter_ref, head_sha1);
 537
 538        argc = parse_options(argc, argv, options, builtin_branch_usage, 0);
 539        if (!!delete + !!rename + !!force_create > 1)
 540                usage_with_options(builtin_branch_usage, options);
 541
 542        if (delete)
 543                return delete_branches(argc, argv, delete > 1, kinds);
 544        else if (argc == 0)
 545                print_ref_list(kinds, detached, verbose, abbrev, with_commit);
 546        else if (rename && (argc == 1))
 547                rename_branch(head, argv[0], rename > 1);
 548        else if (rename && (argc == 2))
 549                rename_branch(argv[0], argv[1], rename > 1);
 550        else if (argc <= 2)
 551                create_branch(head, argv[0], (argc == 2) ? argv[1] : head,
 552                              force_create, reflog, track);
 553        else
 554                usage_with_options(builtin_branch_usage, options);
 555
 556        return 0;
 557}