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