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