builtin-branch.con commit t7004: Add tests for the git tag -n option. (5206d13)
   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
  14static 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]]";
  16
  17#define REF_UNKNOWN_TYPE    0x00
  18#define REF_LOCAL_BRANCH    0x01
  19#define REF_REMOTE_BRANCH   0x02
  20#define REF_TAG             0x04
  21
  22static const char *head;
  23static unsigned char head_sha1[20];
  24
  25static int branch_track = 1; /* 0 = none, 1 = remotes, 2 = all */
  26
  27static int branch_use_color;
  28static char branch_colors[][COLOR_MAXLEN] = {
  29        "\033[m",       /* reset */
  30        "",             /* PLAIN (normal) */
  31        "\033[31m",     /* REMOTE (red) */
  32        "",             /* LOCAL (normal) */
  33        "\033[32m",     /* CURRENT (green) */
  34};
  35enum color_branch {
  36        COLOR_BRANCH_RESET = 0,
  37        COLOR_BRANCH_PLAIN = 1,
  38        COLOR_BRANCH_REMOTE = 2,
  39        COLOR_BRANCH_LOCAL = 3,
  40        COLOR_BRANCH_CURRENT = 4,
  41};
  42
  43static int parse_branch_color_slot(const char *var, int ofs)
  44{
  45        if (!strcasecmp(var+ofs, "plain"))
  46                return COLOR_BRANCH_PLAIN;
  47        if (!strcasecmp(var+ofs, "reset"))
  48                return COLOR_BRANCH_RESET;
  49        if (!strcasecmp(var+ofs, "remote"))
  50                return COLOR_BRANCH_REMOTE;
  51        if (!strcasecmp(var+ofs, "local"))
  52                return COLOR_BRANCH_LOCAL;
  53        if (!strcasecmp(var+ofs, "current"))
  54                return COLOR_BRANCH_CURRENT;
  55        die("bad config variable '%s'", var);
  56}
  57
  58static int git_branch_config(const char *var, const char *value)
  59{
  60        if (!strcmp(var, "color.branch")) {
  61                branch_use_color = git_config_colorbool(var, value);
  62                return 0;
  63        }
  64        if (!prefixcmp(var, "color.branch.")) {
  65                int slot = parse_branch_color_slot(var, 13);
  66                color_parse(value, var, branch_colors[slot]);
  67                return 0;
  68        }
  69        if (!strcmp(var, "branch.autosetupmerge")) {
  70                if (!strcmp(value, "all"))
  71                        branch_track = 2;
  72                else
  73                        branch_track = git_config_bool(var, value);
  74        }
  75
  76        return git_default_config(var, value);
  77}
  78
  79static const char *branch_get_color(enum color_branch ix)
  80{
  81        if (branch_use_color)
  82                return branch_colors[ix];
  83        return "";
  84}
  85
  86static int delete_branches(int argc, const char **argv, int force, int kinds)
  87{
  88        struct commit *rev, *head_rev = head_rev;
  89        unsigned char sha1[20];
  90        char *name = NULL;
  91        const char *fmt, *remote;
  92        char section[PATH_MAX];
  93        int i;
  94        int ret = 0;
  95
  96        switch (kinds) {
  97        case REF_REMOTE_BRANCH:
  98                fmt = "refs/remotes/%s";
  99                remote = "remote ";
 100                force = 1;
 101                break;
 102        case REF_LOCAL_BRANCH:
 103                fmt = "refs/heads/%s";
 104                remote = "";
 105                break;
 106        default:
 107                die("cannot use -a with -d");
 108        }
 109
 110        if (!force) {
 111                head_rev = lookup_commit_reference(head_sha1);
 112                if (!head_rev)
 113                        die("Couldn't look up commit object for HEAD");
 114        }
 115        for (i = 0; i < argc; i++) {
 116                if (kinds == REF_LOCAL_BRANCH && !strcmp(head, argv[i])) {
 117                        error("Cannot delete the branch '%s' "
 118                                "which you are currently on.", argv[i]);
 119                        ret = 1;
 120                        continue;
 121                }
 122
 123                if (name)
 124                        free(name);
 125
 126                name = xstrdup(mkpath(fmt, argv[i]));
 127                if (!resolve_ref(name, sha1, 1, NULL)) {
 128                        error("%sbranch '%s' not found.",
 129                                        remote, argv[i]);
 130                        ret = 1;
 131                        continue;
 132                }
 133
 134                rev = lookup_commit_reference(sha1);
 135                if (!rev) {
 136                        error("Couldn't look up commit object for '%s'", name);
 137                        ret = 1;
 138                        continue;
 139                }
 140
 141                /* This checks whether the merge bases of branch and
 142                 * HEAD contains branch -- which means that the HEAD
 143                 * contains everything in both.
 144                 */
 145
 146                if (!force &&
 147                    !in_merge_bases(rev, &head_rev, 1)) {
 148                        error("The branch '%s' is not a strict subset of "
 149                                "your current HEAD.\n"
 150                                "If you are sure you want to delete it, "
 151                                "run 'git branch -D %s'.", argv[i], argv[i]);
 152                        ret = 1;
 153                        continue;
 154                }
 155
 156                if (delete_ref(name, sha1)) {
 157                        error("Error deleting %sbranch '%s'", remote,
 158                               argv[i]);
 159                        ret = 1;
 160                } else {
 161                        printf("Deleted %sbranch %s.\n", remote, argv[i]);
 162                        snprintf(section, sizeof(section), "branch.%s",
 163                                 argv[i]);
 164                        if (git_config_rename_section(section, NULL) < 0)
 165                                warning("Update of config-file failed");
 166                }
 167        }
 168
 169        if (name)
 170                free(name);
 171
 172        return(ret);
 173}
 174
 175struct ref_item {
 176        char *name;
 177        unsigned int kind;
 178        unsigned char sha1[20];
 179};
 180
 181struct ref_list {
 182        int index, alloc, maxwidth;
 183        struct ref_item *list;
 184        int kinds;
 185};
 186
 187static int append_ref(const char *refname, const unsigned char *sha1, int flags, void *cb_data)
 188{
 189        struct ref_list *ref_list = (struct ref_list*)(cb_data);
 190        struct ref_item *newitem;
 191        int kind = REF_UNKNOWN_TYPE;
 192        int len;
 193
 194        /* Detect kind */
 195        if (!prefixcmp(refname, "refs/heads/")) {
 196                kind = REF_LOCAL_BRANCH;
 197                refname += 11;
 198        } else if (!prefixcmp(refname, "refs/remotes/")) {
 199                kind = REF_REMOTE_BRANCH;
 200                refname += 13;
 201        } else if (!prefixcmp(refname, "refs/tags/")) {
 202                kind = REF_TAG;
 203                refname += 10;
 204        }
 205
 206        /* Don't add types the caller doesn't want */
 207        if ((kind & ref_list->kinds) == 0)
 208                return 0;
 209
 210        /* Resize buffer */
 211        if (ref_list->index >= ref_list->alloc) {
 212                ref_list->alloc = alloc_nr(ref_list->alloc);
 213                ref_list->list = xrealloc(ref_list->list,
 214                                ref_list->alloc * sizeof(struct ref_item));
 215        }
 216
 217        /* Record the new item */
 218        newitem = &(ref_list->list[ref_list->index++]);
 219        newitem->name = xstrdup(refname);
 220        newitem->kind = kind;
 221        hashcpy(newitem->sha1, sha1);
 222        len = strlen(newitem->name);
 223        if (len > ref_list->maxwidth)
 224                ref_list->maxwidth = len;
 225
 226        return 0;
 227}
 228
 229static void free_ref_list(struct ref_list *ref_list)
 230{
 231        int i;
 232
 233        for (i = 0; i < ref_list->index; i++)
 234                free(ref_list->list[i].name);
 235        free(ref_list->list);
 236}
 237
 238static int ref_cmp(const void *r1, const void *r2)
 239{
 240        struct ref_item *c1 = (struct ref_item *)(r1);
 241        struct ref_item *c2 = (struct ref_item *)(r2);
 242
 243        if (c1->kind != c2->kind)
 244                return c1->kind - c2->kind;
 245        return strcmp(c1->name, c2->name);
 246}
 247
 248static void print_ref_item(struct ref_item *item, int maxwidth, int verbose,
 249                           int abbrev, int current)
 250{
 251        char c;
 252        int color;
 253        struct commit *commit;
 254
 255        switch (item->kind) {
 256        case REF_LOCAL_BRANCH:
 257                color = COLOR_BRANCH_LOCAL;
 258                break;
 259        case REF_REMOTE_BRANCH:
 260                color = COLOR_BRANCH_REMOTE;
 261                break;
 262        default:
 263                color = COLOR_BRANCH_PLAIN;
 264                break;
 265        }
 266
 267        c = ' ';
 268        if (current) {
 269                c = '*';
 270                color = COLOR_BRANCH_CURRENT;
 271        }
 272
 273        if (verbose) {
 274                char *subject = NULL;
 275                unsigned long subject_len = 0;
 276                const char *sub = " **** invalid ref ****";
 277
 278                commit = lookup_commit(item->sha1);
 279                if (commit && !parse_commit(commit)) {
 280                        pretty_print_commit(CMIT_FMT_ONELINE, commit, ~0,
 281                                            &subject, &subject_len, 0,
 282                                            NULL, NULL, 0);
 283                        sub = subject;
 284                }
 285                printf("%c %s%-*s%s %s %s\n", c, branch_get_color(color),
 286                       maxwidth, item->name,
 287                       branch_get_color(COLOR_BRANCH_RESET),
 288                       find_unique_abbrev(item->sha1, abbrev), sub);
 289                if (subject)
 290                        free(subject);
 291        } else {
 292                printf("%c %s%s%s\n", c, branch_get_color(color), item->name,
 293                       branch_get_color(COLOR_BRANCH_RESET));
 294        }
 295}
 296
 297static void print_ref_list(int kinds, int detached, int verbose, int abbrev)
 298{
 299        int i;
 300        struct ref_list ref_list;
 301
 302        memset(&ref_list, 0, sizeof(ref_list));
 303        ref_list.kinds = kinds;
 304        for_each_ref(append_ref, &ref_list);
 305
 306        qsort(ref_list.list, ref_list.index, sizeof(struct ref_item), ref_cmp);
 307
 308        detached = (detached && (kinds & REF_LOCAL_BRANCH));
 309        if (detached) {
 310                struct ref_item item;
 311                item.name = xstrdup("(no branch)");
 312                item.kind = REF_LOCAL_BRANCH;
 313                hashcpy(item.sha1, head_sha1);
 314                if (strlen(item.name) > ref_list.maxwidth)
 315                              ref_list.maxwidth = strlen(item.name);
 316                print_ref_item(&item, ref_list.maxwidth, verbose, abbrev, 1);
 317                free(item.name);
 318        }
 319
 320        for (i = 0; i < ref_list.index; i++) {
 321                int current = !detached &&
 322                        (ref_list.list[i].kind == REF_LOCAL_BRANCH) &&
 323                        !strcmp(ref_list.list[i].name, head);
 324                print_ref_item(&ref_list.list[i], ref_list.maxwidth, verbose,
 325                               abbrev, current);
 326        }
 327
 328        free_ref_list(&ref_list);
 329}
 330
 331static char *config_repo;
 332static char *config_remote;
 333static const char *start_ref;
 334
 335static int get_remote_branch_name(const char *value)
 336{
 337        const char *colon;
 338        const char *end;
 339
 340        if (*value == '+')
 341                value++;
 342
 343        colon = strchr(value, ':');
 344        if (!colon)
 345                return 0;
 346
 347        end = value + strlen(value);
 348
 349        /*
 350         * Try an exact match first.  I.e. handle the case where the
 351         * value is "$anything:refs/foo/bar/baz" and start_ref is exactly
 352         * "refs/foo/bar/baz". Then the name at the remote is $anything.
 353         */
 354        if (!strcmp(colon + 1, start_ref)) {
 355                /* Truncate the value before the colon. */
 356                nfasprintf(&config_repo, "%.*s", colon - value, value);
 357                return 1;
 358        }
 359
 360        /*
 361         * Is this a wildcard match?
 362         */
 363        if ((end - 2 <= value) || end[-2] != '/' || end[-1] != '*' ||
 364            (colon - 2 <= value) || colon[-2] != '/' || colon[-1] != '*')
 365                return 0;
 366
 367        /*
 368         * Value is "refs/foo/bar/<asterisk>:refs/baz/boa/<asterisk>"
 369         * and start_ref begins with "refs/baz/boa/"; the name at the
 370         * remote is refs/foo/bar/ with the remaining part of the
 371         * start_ref.  The length of the prefix on the RHS is (end -
 372         * colon - 2), including the slash immediately before the
 373         * asterisk.
 374         */
 375        if ((strlen(start_ref) < end - colon - 2) ||
 376            memcmp(start_ref, colon + 1, end - colon - 2))
 377                return 0; /* does not match prefix */
 378
 379        /* Replace the asterisk with the remote branch name.  */
 380        nfasprintf(&config_repo, "%.*s%s",
 381                   (colon - 1) - value, value,
 382                   start_ref + (end - colon - 2));
 383        return 1;
 384}
 385
 386static int get_remote_config(const char *key, const char *value)
 387{
 388        const char *var;
 389        if (prefixcmp(key, "remote."))
 390                return 0;
 391
 392        var = strrchr(key, '.');
 393        if (var == key + 6 || strcmp(var, ".fetch"))
 394                return 0;
 395        /*
 396         * Ok, we are looking at key == "remote.$foo.fetch";
 397         */
 398        if (get_remote_branch_name(value))
 399                nfasprintf(&config_remote, "%.*s", var - (key + 7), key + 7);
 400
 401        return 0;
 402}
 403
 404static void set_branch_merge(const char *name, const char *config_remote,
 405                             const char *config_repo)
 406{
 407        char key[1024];
 408        if (sizeof(key) <=
 409            snprintf(key, sizeof(key), "branch.%s.remote", name))
 410                die("what a long branch name you have!");
 411        git_config_set(key, config_remote);
 412
 413        /*
 414         * We do not have to check if we have enough space for
 415         * the 'merge' key, since it's shorter than the
 416         * previous 'remote' key, which we already checked.
 417         */
 418        snprintf(key, sizeof(key), "branch.%s.merge", name);
 419        git_config_set(key, config_repo);
 420}
 421
 422static void set_branch_defaults(const char *name, const char *real_ref)
 423{
 424        /*
 425         * name is the name of new branch under refs/heads;
 426         * real_ref is typically refs/remotes/$foo/$bar, where
 427         * $foo is the remote name (there typically are no slashes)
 428         * and $bar is the branch name we map from the remote
 429         * (it could have slashes).
 430         */
 431        start_ref = real_ref;
 432        git_config(get_remote_config);
 433        if (!config_repo && !config_remote &&
 434            !prefixcmp(real_ref, "refs/heads/")) {
 435                set_branch_merge(name, ".", real_ref);
 436                printf("Branch %s set up to track local branch %s.\n",
 437                       name, real_ref);
 438        }
 439
 440        if (config_repo && config_remote) {
 441                set_branch_merge(name, config_remote, config_repo);
 442                printf("Branch %s set up to track remote branch %s.\n",
 443                       name, real_ref);
 444        }
 445
 446        if (config_repo)
 447                free(config_repo);
 448        if (config_remote)
 449                free(config_remote);
 450}
 451
 452static void create_branch(const char *name, const char *start_name,
 453                          int force, int reflog, int track)
 454{
 455        struct ref_lock *lock;
 456        struct commit *commit;
 457        unsigned char sha1[20];
 458        char *real_ref, ref[PATH_MAX], msg[PATH_MAX + 20];
 459        int forcing = 0;
 460
 461        snprintf(ref, sizeof ref, "refs/heads/%s", name);
 462        if (check_ref_format(ref))
 463                die("'%s' is not a valid branch name.", name);
 464
 465        if (resolve_ref(ref, sha1, 1, NULL)) {
 466                if (!force)
 467                        die("A branch named '%s' already exists.", name);
 468                else if (!is_bare_repository() && !strcmp(head, name))
 469                        die("Cannot force update the current branch.");
 470                forcing = 1;
 471        }
 472
 473        real_ref = NULL;
 474        if (get_sha1(start_name, sha1))
 475                die("Not a valid object name: '%s'.", start_name);
 476
 477        switch (dwim_ref(start_name, strlen(start_name), sha1, &real_ref)) {
 478        case 0:
 479                /* Not branching from any existing branch */
 480                real_ref = NULL;
 481                break;
 482        case 1:
 483                /* Unique completion -- good */
 484                break;
 485        default:
 486                die("Ambiguous object name: '%s'.", start_name);
 487                break;
 488        }
 489
 490        if ((commit = lookup_commit_reference(sha1)) == NULL)
 491                die("Not a valid branch point: '%s'.", start_name);
 492        hashcpy(sha1, commit->object.sha1);
 493
 494        lock = lock_any_ref_for_update(ref, NULL, 0);
 495        if (!lock)
 496                die("Failed to lock ref for update: %s.", strerror(errno));
 497
 498        if (reflog)
 499                log_all_ref_updates = 1;
 500
 501        if (forcing)
 502                snprintf(msg, sizeof msg, "branch: Reset from %s",
 503                         start_name);
 504        else
 505                snprintf(msg, sizeof msg, "branch: Created from %s",
 506                         start_name);
 507
 508        /* When branching off a remote branch, set up so that git-pull
 509           automatically merges from there.  So far, this is only done for
 510           remotes registered via .git/config.  */
 511        if (real_ref && (track == 2 ||
 512                                (track == 1 &&
 513                                 !prefixcmp(real_ref, "refs/remotes/"))))
 514                set_branch_defaults(name, real_ref);
 515
 516        if (write_ref_sha1(lock, sha1, msg) < 0)
 517                die("Failed to write ref: %s.", strerror(errno));
 518
 519        if (real_ref)
 520                free(real_ref);
 521}
 522
 523static void rename_branch(const char *oldname, const char *newname, int force)
 524{
 525        char oldref[PATH_MAX], newref[PATH_MAX], logmsg[PATH_MAX*2 + 100];
 526        unsigned char sha1[20];
 527        char oldsection[PATH_MAX], newsection[PATH_MAX];
 528
 529        if (!oldname)
 530                die("cannot rename the current branch while not on any.");
 531
 532        if (snprintf(oldref, sizeof(oldref), "refs/heads/%s", oldname) > sizeof(oldref))
 533                die("Old branchname too long");
 534
 535        if (check_ref_format(oldref))
 536                die("Invalid branch name: %s", oldref);
 537
 538        if (snprintf(newref, sizeof(newref), "refs/heads/%s", newname) > sizeof(newref))
 539                die("New branchname too long");
 540
 541        if (check_ref_format(newref))
 542                die("Invalid branch name: %s", newref);
 543
 544        if (resolve_ref(newref, sha1, 1, NULL) && !force)
 545                die("A branch named '%s' already exists.", newname);
 546
 547        snprintf(logmsg, sizeof(logmsg), "Branch: renamed %s to %s",
 548                 oldref, newref);
 549
 550        if (rename_ref(oldref, newref, logmsg))
 551                die("Branch rename failed");
 552
 553        /* no need to pass logmsg here as HEAD didn't really move */
 554        if (!strcmp(oldname, head) && create_symref("HEAD", newref, NULL))
 555                die("Branch renamed to %s, but HEAD is not updated!", newname);
 556
 557        snprintf(oldsection, sizeof(oldsection), "branch.%s", oldref + 11);
 558        snprintf(newsection, sizeof(newsection), "branch.%s", newref + 11);
 559        if (git_config_rename_section(oldsection, newsection) < 0)
 560                die("Branch is renamed, but update of config-file failed");
 561}
 562
 563int cmd_branch(int argc, const char **argv, const char *prefix)
 564{
 565        int delete = 0, force_delete = 0, force_create = 0;
 566        int rename = 0, force_rename = 0;
 567        int verbose = 0, abbrev = DEFAULT_ABBREV, detached = 0;
 568        int reflog = 0, track;
 569        int kinds = REF_LOCAL_BRANCH;
 570        int i;
 571
 572        git_config(git_branch_config);
 573        track = branch_track;
 574
 575        for (i = 1; i < argc; i++) {
 576                const char *arg = argv[i];
 577
 578                if (arg[0] != '-')
 579                        break;
 580                if (!strcmp(arg, "--")) {
 581                        i++;
 582                        break;
 583                }
 584                if (!strcmp(arg, "--track")) {
 585                        track = 2;
 586                        continue;
 587                }
 588                if (!strcmp(arg, "--no-track")) {
 589                        track = 0;
 590                        continue;
 591                }
 592                if (!strcmp(arg, "-d")) {
 593                        delete = 1;
 594                        continue;
 595                }
 596                if (!strcmp(arg, "-D")) {
 597                        delete = 1;
 598                        force_delete = 1;
 599                        continue;
 600                }
 601                if (!strcmp(arg, "-f")) {
 602                        force_create = 1;
 603                        continue;
 604                }
 605                if (!strcmp(arg, "-m")) {
 606                        rename = 1;
 607                        continue;
 608                }
 609                if (!strcmp(arg, "-M")) {
 610                        rename = 1;
 611                        force_rename = 1;
 612                        continue;
 613                }
 614                if (!strcmp(arg, "-r")) {
 615                        kinds = REF_REMOTE_BRANCH;
 616                        continue;
 617                }
 618                if (!strcmp(arg, "-a")) {
 619                        kinds = REF_REMOTE_BRANCH | REF_LOCAL_BRANCH;
 620                        continue;
 621                }
 622                if (!strcmp(arg, "-l")) {
 623                        reflog = 1;
 624                        continue;
 625                }
 626                if (!prefixcmp(arg, "--no-abbrev")) {
 627                        abbrev = 0;
 628                        continue;
 629                }
 630                if (!prefixcmp(arg, "--abbrev=")) {
 631                        abbrev = strtoul(arg + 9, NULL, 10);
 632                        if (abbrev < MINIMUM_ABBREV)
 633                                abbrev = MINIMUM_ABBREV;
 634                        else if (abbrev > 40)
 635                                abbrev = 40;
 636                        continue;
 637                }
 638                if (!strcmp(arg, "-v")) {
 639                        verbose = 1;
 640                        continue;
 641                }
 642                if (!strcmp(arg, "--color")) {
 643                        branch_use_color = 1;
 644                        continue;
 645                }
 646                if (!strcmp(arg, "--no-color")) {
 647                        branch_use_color = 0;
 648                        continue;
 649                }
 650                usage(builtin_branch_usage);
 651        }
 652
 653        if ((delete && rename) || (delete && force_create) ||
 654            (rename && force_create))
 655                usage(builtin_branch_usage);
 656
 657        head = resolve_ref("HEAD", head_sha1, 0, NULL);
 658        if (!head)
 659                die("Failed to resolve HEAD as a valid ref.");
 660        head = xstrdup(head);
 661        if (!strcmp(head, "HEAD")) {
 662                detached = 1;
 663        }
 664        else {
 665                if (prefixcmp(head, "refs/heads/"))
 666                        die("HEAD not found below refs/heads!");
 667                head += 11;
 668        }
 669
 670        if (delete)
 671                return delete_branches(argc - i, argv + i, force_delete, kinds);
 672        else if (i == argc)
 673                print_ref_list(kinds, detached, verbose, abbrev);
 674        else if (rename && (i == argc - 1))
 675                rename_branch(head, argv[i], force_rename);
 676        else if (rename && (i == argc - 2))
 677                rename_branch(argv[i], argv[i + 1], force_rename);
 678        else if (i == argc - 1 || i == argc - 2)
 679                create_branch(argv[i], (i == argc - 2) ? argv[i+1] : head,
 680                              force_create, reflog, track);
 681        else
 682                usage(builtin_branch_usage);
 683
 684        return 0;
 685}