builtin / branch.con commit Merge branch 'ab/i18n' (d7c03ca)
   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#include "diff.h"
  17#include "revision.h"
  18
  19static const char * const builtin_branch_usage[] = {
  20        "git branch [options] [-r | -a] [--merged | --no-merged]",
  21        "git branch [options] [-l] [-f] <branchname> [<start-point>]",
  22        "git branch [options] [-r] (-d | -D) <branchname>...",
  23        "git branch [options] (-m | -M) [<oldbranch>] <newbranch>",
  24        NULL
  25};
  26
  27#define REF_LOCAL_BRANCH    0x01
  28#define REF_REMOTE_BRANCH   0x02
  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        GIT_COLOR_RESET,
  36        GIT_COLOR_NORMAL,       /* PLAIN */
  37        GIT_COLOR_RED,          /* REMOTE */
  38        GIT_COLOR_NORMAL,       /* LOCAL */
  39        GIT_COLOR_GREEN,        /* CURRENT */
  40};
  41enum color_branch {
  42        BRANCH_COLOR_RESET = 0,
  43        BRANCH_COLOR_PLAIN = 1,
  44        BRANCH_COLOR_REMOTE = 2,
  45        BRANCH_COLOR_LOCAL = 3,
  46        BRANCH_COLOR_CURRENT = 4
  47};
  48
  49static enum merge_filter {
  50        NO_FILTER = 0,
  51        SHOW_NOT_MERGED,
  52        SHOW_MERGED
  53} merge_filter;
  54static unsigned char merge_filter_ref[20];
  55
  56static int parse_branch_color_slot(const char *var, int ofs)
  57{
  58        if (!strcasecmp(var+ofs, "plain"))
  59                return BRANCH_COLOR_PLAIN;
  60        if (!strcasecmp(var+ofs, "reset"))
  61                return BRANCH_COLOR_RESET;
  62        if (!strcasecmp(var+ofs, "remote"))
  63                return BRANCH_COLOR_REMOTE;
  64        if (!strcasecmp(var+ofs, "local"))
  65                return BRANCH_COLOR_LOCAL;
  66        if (!strcasecmp(var+ofs, "current"))
  67                return BRANCH_COLOR_CURRENT;
  68        return -1;
  69}
  70
  71static int git_branch_config(const char *var, const char *value, void *cb)
  72{
  73        if (!strcmp(var, "color.branch")) {
  74                branch_use_color = git_config_colorbool(var, value);
  75                return 0;
  76        }
  77        if (!prefixcmp(var, "color.branch.")) {
  78                int slot = parse_branch_color_slot(var, 13);
  79                if (slot < 0)
  80                        return 0;
  81                if (!value)
  82                        return config_error_nonbool(var);
  83                color_parse(value, var, branch_colors[slot]);
  84                return 0;
  85        }
  86        return git_color_default_config(var, value, cb);
  87}
  88
  89static const char *branch_get_color(enum color_branch ix)
  90{
  91        if (want_color(branch_use_color))
  92                return branch_colors[ix];
  93        return "";
  94}
  95
  96static int branch_merged(int kind, const char *name,
  97                         struct commit *rev, struct commit *head_rev)
  98{
  99        /*
 100         * This checks whether the merge bases of branch and HEAD (or
 101         * the other branch this branch builds upon) contains the
 102         * branch, which means that the branch has already been merged
 103         * safely to HEAD (or the other branch).
 104         */
 105        struct commit *reference_rev = NULL;
 106        const char *reference_name = NULL;
 107        void *reference_name_to_free = NULL;
 108        int merged;
 109
 110        if (kind == REF_LOCAL_BRANCH) {
 111                struct branch *branch = branch_get(name);
 112                unsigned char sha1[20];
 113
 114                if (branch &&
 115                    branch->merge &&
 116                    branch->merge[0] &&
 117                    branch->merge[0]->dst &&
 118                    (reference_name = reference_name_to_free =
 119                     resolve_refdup(branch->merge[0]->dst, sha1, 1, NULL)) != NULL)
 120                        reference_rev = lookup_commit_reference(sha1);
 121        }
 122        if (!reference_rev)
 123                reference_rev = head_rev;
 124
 125        merged = in_merge_bases(rev, &reference_rev, 1);
 126
 127        /*
 128         * After the safety valve is fully redefined to "check with
 129         * upstream, if any, otherwise with HEAD", we should just
 130         * return the result of the in_merge_bases() above without
 131         * any of the following code, but during the transition period,
 132         * a gentle reminder is in order.
 133         */
 134        if ((head_rev != reference_rev) &&
 135            in_merge_bases(rev, &head_rev, 1) != merged) {
 136                if (merged)
 137                        warning(_("deleting branch '%s' that has been merged to\n"
 138                                "         '%s', but not yet merged to HEAD."),
 139                                name, reference_name);
 140                else
 141                        warning(_("not deleting branch '%s' that is not yet merged to\n"
 142                                "         '%s', even though it is merged to HEAD."),
 143                                name, reference_name);
 144        }
 145        free(reference_name_to_free);
 146        return merged;
 147}
 148
 149static int delete_branches(int argc, const char **argv, int force, int kinds,
 150                           int quiet)
 151{
 152        struct commit *rev, *head_rev = NULL;
 153        unsigned char sha1[20];
 154        char *name = NULL;
 155        const char *fmt;
 156        int i;
 157        int ret = 0;
 158        int remote_branch = 0;
 159        struct strbuf bname = STRBUF_INIT;
 160
 161        switch (kinds) {
 162        case REF_REMOTE_BRANCH:
 163                fmt = "refs/remotes/%s";
 164                /* For subsequent UI messages */
 165                remote_branch = 1;
 166
 167                force = 1;
 168                break;
 169        case REF_LOCAL_BRANCH:
 170                fmt = "refs/heads/%s";
 171                break;
 172        default:
 173                die(_("cannot use -a with -d"));
 174        }
 175
 176        if (!force) {
 177                head_rev = lookup_commit_reference(head_sha1);
 178                if (!head_rev)
 179                        die(_("Couldn't look up commit object for HEAD"));
 180        }
 181        for (i = 0; i < argc; i++, strbuf_release(&bname)) {
 182                strbuf_branchname(&bname, argv[i]);
 183                if (kinds == REF_LOCAL_BRANCH && !strcmp(head, bname.buf)) {
 184                        error(_("Cannot delete the branch '%s' "
 185                              "which you are currently on."), bname.buf);
 186                        ret = 1;
 187                        continue;
 188                }
 189
 190                free(name);
 191
 192                name = xstrdup(mkpath(fmt, bname.buf));
 193                if (read_ref(name, sha1)) {
 194                        error(remote_branch
 195                              ? _("remote branch '%s' not found.")
 196                              : _("branch '%s' not found."), bname.buf);
 197                        ret = 1;
 198                        continue;
 199                }
 200
 201                rev = lookup_commit_reference(sha1);
 202                if (!rev) {
 203                        error(_("Couldn't look up commit object for '%s'"), name);
 204                        ret = 1;
 205                        continue;
 206                }
 207
 208                if (!force && !branch_merged(kinds, bname.buf, rev, head_rev)) {
 209                        error(_("The branch '%s' is not fully merged.\n"
 210                              "If you are sure you want to delete it, "
 211                              "run 'git branch -D %s'."), bname.buf, bname.buf);
 212                        ret = 1;
 213                        continue;
 214                }
 215
 216                if (delete_ref(name, sha1, 0)) {
 217                        error(remote_branch
 218                              ? _("Error deleting remote branch '%s'")
 219                              : _("Error deleting branch '%s'"),
 220                              bname.buf);
 221                        ret = 1;
 222                } else {
 223                        struct strbuf buf = STRBUF_INIT;
 224                        if (!quiet)
 225                                printf(remote_branch
 226                                       ? _("Deleted remote branch %s (was %s).\n")
 227                                       : _("Deleted branch %s (was %s).\n"),
 228                                       bname.buf,
 229                                       find_unique_abbrev(sha1, DEFAULT_ABBREV));
 230                        strbuf_addf(&buf, "branch.%s", bname.buf);
 231                        if (git_config_rename_section(buf.buf, NULL) < 0)
 232                                warning(_("Update of config-file failed"));
 233                        strbuf_release(&buf);
 234                }
 235        }
 236
 237        free(name);
 238
 239        return(ret);
 240}
 241
 242struct ref_item {
 243        char *name;
 244        char *dest;
 245        unsigned int kind, len;
 246        struct commit *commit;
 247};
 248
 249struct ref_list {
 250        struct rev_info revs;
 251        int index, alloc, maxwidth, verbose, abbrev;
 252        struct ref_item *list;
 253        struct commit_list *with_commit;
 254        int kinds;
 255};
 256
 257static char *resolve_symref(const char *src, const char *prefix)
 258{
 259        unsigned char sha1[20];
 260        int flag;
 261        const char *dst, *cp;
 262
 263        dst = resolve_ref_unsafe(src, sha1, 0, &flag);
 264        if (!(dst && (flag & REF_ISSYMREF)))
 265                return NULL;
 266        if (prefix && (cp = skip_prefix(dst, prefix)))
 267                dst = cp;
 268        return xstrdup(dst);
 269}
 270
 271struct append_ref_cb {
 272        struct ref_list *ref_list;
 273        const char **pattern;
 274        int ret;
 275};
 276
 277static int match_patterns(const char **pattern, const char *refname)
 278{
 279        if (!*pattern)
 280                return 1; /* no pattern always matches */
 281        while (*pattern) {
 282                if (!fnmatch(*pattern, refname, 0))
 283                        return 1;
 284                pattern++;
 285        }
 286        return 0;
 287}
 288
 289static int append_ref(const char *refname, const unsigned char *sha1, int flags, void *cb_data)
 290{
 291        struct append_ref_cb *cb = (struct append_ref_cb *)(cb_data);
 292        struct ref_list *ref_list = cb->ref_list;
 293        struct ref_item *newitem;
 294        struct commit *commit;
 295        int kind, i;
 296        const char *prefix, *orig_refname = refname;
 297
 298        static struct {
 299                int kind;
 300                const char *prefix;
 301                int pfxlen;
 302        } ref_kind[] = {
 303                { REF_LOCAL_BRANCH, "refs/heads/", 11 },
 304                { REF_REMOTE_BRANCH, "refs/remotes/", 13 },
 305        };
 306
 307        /* Detect kind */
 308        for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
 309                prefix = ref_kind[i].prefix;
 310                if (strncmp(refname, prefix, ref_kind[i].pfxlen))
 311                        continue;
 312                kind = ref_kind[i].kind;
 313                refname += ref_kind[i].pfxlen;
 314                break;
 315        }
 316        if (ARRAY_SIZE(ref_kind) <= i)
 317                return 0;
 318
 319        /* Don't add types the caller doesn't want */
 320        if ((kind & ref_list->kinds) == 0)
 321                return 0;
 322
 323        if (!match_patterns(cb->pattern, refname))
 324                return 0;
 325
 326        commit = NULL;
 327        if (ref_list->verbose || ref_list->with_commit || merge_filter != NO_FILTER) {
 328                commit = lookup_commit_reference_gently(sha1, 1);
 329                if (!commit) {
 330                        cb->ret = error(_("branch '%s' does not point at a commit"), refname);
 331                        return 0;
 332                }
 333
 334                /* Filter with with_commit if specified */
 335                if (!is_descendant_of(commit, ref_list->with_commit))
 336                        return 0;
 337
 338                if (merge_filter != NO_FILTER)
 339                        add_pending_object(&ref_list->revs,
 340                                           (struct object *)commit, refname);
 341        }
 342
 343        ALLOC_GROW(ref_list->list, ref_list->index + 1, ref_list->alloc);
 344
 345        /* Record the new item */
 346        newitem = &(ref_list->list[ref_list->index++]);
 347        newitem->name = xstrdup(refname);
 348        newitem->kind = kind;
 349        newitem->commit = commit;
 350        newitem->len = strlen(refname);
 351        newitem->dest = resolve_symref(orig_refname, prefix);
 352        /* adjust for "remotes/" */
 353        if (newitem->kind == REF_REMOTE_BRANCH &&
 354            ref_list->kinds != REF_REMOTE_BRANCH)
 355                newitem->len += 8;
 356        if (newitem->len > ref_list->maxwidth)
 357                ref_list->maxwidth = newitem->len;
 358
 359        return 0;
 360}
 361
 362static void free_ref_list(struct ref_list *ref_list)
 363{
 364        int i;
 365
 366        for (i = 0; i < ref_list->index; i++) {
 367                free(ref_list->list[i].name);
 368                free(ref_list->list[i].dest);
 369        }
 370        free(ref_list->list);
 371}
 372
 373static int ref_cmp(const void *r1, const void *r2)
 374{
 375        struct ref_item *c1 = (struct ref_item *)(r1);
 376        struct ref_item *c2 = (struct ref_item *)(r2);
 377
 378        if (c1->kind != c2->kind)
 379                return c1->kind - c2->kind;
 380        return strcmp(c1->name, c2->name);
 381}
 382
 383static void fill_tracking_info(struct strbuf *stat, const char *branch_name,
 384                int show_upstream_ref)
 385{
 386        int ours, theirs;
 387        struct branch *branch = branch_get(branch_name);
 388
 389        if (!stat_tracking_info(branch, &ours, &theirs)) {
 390                if (branch && branch->merge && branch->merge[0]->dst &&
 391                    show_upstream_ref)
 392                        strbuf_addf(stat, "[%s] ",
 393                            shorten_unambiguous_ref(branch->merge[0]->dst, 0));
 394                return;
 395        }
 396
 397        strbuf_addch(stat, '[');
 398        if (show_upstream_ref)
 399                strbuf_addf(stat, "%s: ",
 400                        shorten_unambiguous_ref(branch->merge[0]->dst, 0));
 401        if (!ours)
 402                strbuf_addf(stat, _("behind %d] "), theirs);
 403        else if (!theirs)
 404                strbuf_addf(stat, _("ahead %d] "), ours);
 405        else
 406                strbuf_addf(stat, _("ahead %d, behind %d] "), ours, theirs);
 407}
 408
 409static int matches_merge_filter(struct commit *commit)
 410{
 411        int is_merged;
 412
 413        if (merge_filter == NO_FILTER)
 414                return 1;
 415
 416        is_merged = !!(commit->object.flags & UNINTERESTING);
 417        return (is_merged == (merge_filter == SHOW_MERGED));
 418}
 419
 420static void add_verbose_info(struct strbuf *out, struct ref_item *item,
 421                             int verbose, int abbrev)
 422{
 423        struct strbuf subject = STRBUF_INIT, stat = STRBUF_INIT;
 424        const char *sub = " **** invalid ref ****";
 425        struct commit *commit = item->commit;
 426
 427        if (commit && !parse_commit(commit)) {
 428                pp_commit_easy(CMIT_FMT_ONELINE, commit, &subject);
 429                sub = subject.buf;
 430        }
 431
 432        if (item->kind == REF_LOCAL_BRANCH)
 433                fill_tracking_info(&stat, item->name, verbose > 1);
 434
 435        strbuf_addf(out, " %s %s%s",
 436                find_unique_abbrev(item->commit->object.sha1, abbrev),
 437                stat.buf, sub);
 438        strbuf_release(&stat);
 439        strbuf_release(&subject);
 440}
 441
 442static void print_ref_item(struct ref_item *item, int maxwidth, int verbose,
 443                           int abbrev, int current, char *prefix)
 444{
 445        char c;
 446        int color;
 447        struct commit *commit = item->commit;
 448        struct strbuf out = STRBUF_INIT, name = STRBUF_INIT;
 449
 450        if (!matches_merge_filter(commit))
 451                return;
 452
 453        switch (item->kind) {
 454        case REF_LOCAL_BRANCH:
 455                color = BRANCH_COLOR_LOCAL;
 456                break;
 457        case REF_REMOTE_BRANCH:
 458                color = BRANCH_COLOR_REMOTE;
 459                break;
 460        default:
 461                color = BRANCH_COLOR_PLAIN;
 462                break;
 463        }
 464
 465        c = ' ';
 466        if (current) {
 467                c = '*';
 468                color = BRANCH_COLOR_CURRENT;
 469        }
 470
 471        strbuf_addf(&name, "%s%s", prefix, item->name);
 472        if (verbose)
 473                strbuf_addf(&out, "%c %s%-*s%s", c, branch_get_color(color),
 474                            maxwidth, name.buf,
 475                            branch_get_color(BRANCH_COLOR_RESET));
 476        else
 477                strbuf_addf(&out, "%c %s%s%s", c, branch_get_color(color),
 478                            name.buf, branch_get_color(BRANCH_COLOR_RESET));
 479
 480        if (item->dest)
 481                strbuf_addf(&out, " -> %s", item->dest);
 482        else if (verbose)
 483                /* " f7c0c00 [ahead 58, behind 197] vcs-svn: drop obj_pool.h" */
 484                add_verbose_info(&out, item, verbose, abbrev);
 485        printf("%s\n", out.buf);
 486        strbuf_release(&name);
 487        strbuf_release(&out);
 488}
 489
 490static int calc_maxwidth(struct ref_list *refs)
 491{
 492        int i, w = 0;
 493        for (i = 0; i < refs->index; i++) {
 494                if (!matches_merge_filter(refs->list[i].commit))
 495                        continue;
 496                if (refs->list[i].len > w)
 497                        w = refs->list[i].len;
 498        }
 499        return w;
 500}
 501
 502
 503static void show_detached(struct ref_list *ref_list)
 504{
 505        struct commit *head_commit = lookup_commit_reference_gently(head_sha1, 1);
 506
 507        if (head_commit && is_descendant_of(head_commit, ref_list->with_commit)) {
 508                struct ref_item item;
 509                item.name = xstrdup(_("(no branch)"));
 510                item.len = strlen(item.name);
 511                item.kind = REF_LOCAL_BRANCH;
 512                item.dest = NULL;
 513                item.commit = head_commit;
 514                if (item.len > ref_list->maxwidth)
 515                        ref_list->maxwidth = item.len;
 516                print_ref_item(&item, ref_list->maxwidth, ref_list->verbose, ref_list->abbrev, 1, "");
 517                free(item.name);
 518        }
 519}
 520
 521static int print_ref_list(int kinds, int detached, int verbose, int abbrev, struct commit_list *with_commit, const char **pattern)
 522{
 523        int i;
 524        struct append_ref_cb cb;
 525        struct ref_list ref_list;
 526
 527        memset(&ref_list, 0, sizeof(ref_list));
 528        ref_list.kinds = kinds;
 529        ref_list.verbose = verbose;
 530        ref_list.abbrev = abbrev;
 531        ref_list.with_commit = with_commit;
 532        if (merge_filter != NO_FILTER)
 533                init_revisions(&ref_list.revs, NULL);
 534        cb.ref_list = &ref_list;
 535        cb.pattern = pattern;
 536        cb.ret = 0;
 537        for_each_rawref(append_ref, &cb);
 538        if (merge_filter != NO_FILTER) {
 539                struct commit *filter;
 540                filter = lookup_commit_reference_gently(merge_filter_ref, 0);
 541                if (!filter)
 542                        die("object '%s' does not point to a commit",
 543                            sha1_to_hex(merge_filter_ref));
 544
 545                filter->object.flags |= UNINTERESTING;
 546                add_pending_object(&ref_list.revs,
 547                                   (struct object *) filter, "");
 548                ref_list.revs.limited = 1;
 549                prepare_revision_walk(&ref_list.revs);
 550                if (verbose)
 551                        ref_list.maxwidth = calc_maxwidth(&ref_list);
 552        }
 553
 554        qsort(ref_list.list, ref_list.index, sizeof(struct ref_item), ref_cmp);
 555
 556        detached = (detached && (kinds & REF_LOCAL_BRANCH));
 557        if (detached && match_patterns(pattern, "HEAD"))
 558                show_detached(&ref_list);
 559
 560        for (i = 0; i < ref_list.index; i++) {
 561                int current = !detached &&
 562                        (ref_list.list[i].kind == REF_LOCAL_BRANCH) &&
 563                        !strcmp(ref_list.list[i].name, head);
 564                char *prefix = (kinds != REF_REMOTE_BRANCH &&
 565                                ref_list.list[i].kind == REF_REMOTE_BRANCH)
 566                                ? "remotes/" : "";
 567                print_ref_item(&ref_list.list[i], ref_list.maxwidth, verbose,
 568                               abbrev, current, prefix);
 569        }
 570
 571        free_ref_list(&ref_list);
 572
 573        if (cb.ret)
 574                error(_("some refs could not be read"));
 575
 576        return cb.ret;
 577}
 578
 579static void rename_branch(const char *oldname, const char *newname, int force)
 580{
 581        struct strbuf oldref = STRBUF_INIT, newref = STRBUF_INIT, logmsg = STRBUF_INIT;
 582        struct strbuf oldsection = STRBUF_INIT, newsection = STRBUF_INIT;
 583        int recovery = 0;
 584        int clobber_head_ok;
 585
 586        if (!oldname)
 587                die(_("cannot rename the current branch while not on any."));
 588
 589        if (strbuf_check_branch_ref(&oldref, oldname)) {
 590                /*
 591                 * Bad name --- this could be an attempt to rename a
 592                 * ref that we used to allow to be created by accident.
 593                 */
 594                if (ref_exists(oldref.buf))
 595                        recovery = 1;
 596                else
 597                        die(_("Invalid branch name: '%s'"), oldname);
 598        }
 599
 600        /*
 601         * A command like "git branch -M currentbranch currentbranch" cannot
 602         * cause the worktree to become inconsistent with HEAD, so allow it.
 603         */
 604        clobber_head_ok = !strcmp(oldname, newname);
 605
 606        validate_new_branchname(newname, &newref, force, clobber_head_ok);
 607
 608        strbuf_addf(&logmsg, "Branch: renamed %s to %s",
 609                 oldref.buf, newref.buf);
 610
 611        if (rename_ref(oldref.buf, newref.buf, logmsg.buf))
 612                die(_("Branch rename failed"));
 613        strbuf_release(&logmsg);
 614
 615        if (recovery)
 616                warning(_("Renamed a misnamed branch '%s' away"), oldref.buf + 11);
 617
 618        /* no need to pass logmsg here as HEAD didn't really move */
 619        if (!strcmp(oldname, head) && create_symref("HEAD", newref.buf, NULL))
 620                die(_("Branch renamed to %s, but HEAD is not updated!"), newname);
 621
 622        strbuf_addf(&oldsection, "branch.%s", oldref.buf + 11);
 623        strbuf_release(&oldref);
 624        strbuf_addf(&newsection, "branch.%s", newref.buf + 11);
 625        strbuf_release(&newref);
 626        if (git_config_rename_section(oldsection.buf, newsection.buf) < 0)
 627                die(_("Branch is renamed, but update of config-file failed"));
 628        strbuf_release(&oldsection);
 629        strbuf_release(&newsection);
 630}
 631
 632static int opt_parse_merge_filter(const struct option *opt, const char *arg, int unset)
 633{
 634        merge_filter = ((opt->long_name[0] == 'n')
 635                        ? SHOW_NOT_MERGED
 636                        : SHOW_MERGED);
 637        if (unset)
 638                merge_filter = SHOW_NOT_MERGED; /* b/c for --no-merged */
 639        if (!arg)
 640                arg = "HEAD";
 641        if (get_sha1(arg, merge_filter_ref))
 642                die(_("malformed object name %s"), arg);
 643        return 0;
 644}
 645
 646static const char edit_description[] = "BRANCH_DESCRIPTION";
 647
 648static int edit_branch_description(const char *branch_name)
 649{
 650        FILE *fp;
 651        int status;
 652        struct strbuf buf = STRBUF_INIT;
 653        struct strbuf name = STRBUF_INIT;
 654
 655        read_branch_desc(&buf, branch_name);
 656        if (!buf.len || buf.buf[buf.len-1] != '\n')
 657                strbuf_addch(&buf, '\n');
 658        strbuf_addf(&buf,
 659                    "# Please edit the description for the branch\n"
 660                    "#   %s\n"
 661                    "# Lines starting with '#' will be stripped.\n",
 662                    branch_name);
 663        fp = fopen(git_path(edit_description), "w");
 664        if ((fwrite(buf.buf, 1, buf.len, fp) < buf.len) || fclose(fp)) {
 665                strbuf_release(&buf);
 666                return error(_("could not write branch description template: %s\n"),
 667                             strerror(errno));
 668        }
 669        strbuf_reset(&buf);
 670        if (launch_editor(git_path(edit_description), &buf, NULL)) {
 671                strbuf_release(&buf);
 672                return -1;
 673        }
 674        stripspace(&buf, 1);
 675
 676        strbuf_addf(&name, "branch.%s.description", branch_name);
 677        status = git_config_set(name.buf, buf.buf);
 678        strbuf_release(&name);
 679        strbuf_release(&buf);
 680
 681        return status;
 682}
 683
 684int cmd_branch(int argc, const char **argv, const char *prefix)
 685{
 686        int delete = 0, rename = 0, force_create = 0, list = 0;
 687        int verbose = 0, abbrev = -1, detached = 0;
 688        int reflog = 0, edit_description = 0;
 689        int quiet = 0;
 690        enum branch_track track;
 691        int kinds = REF_LOCAL_BRANCH;
 692        struct commit_list *with_commit = NULL;
 693
 694        struct option options[] = {
 695                OPT_GROUP("Generic options"),
 696                OPT__VERBOSE(&verbose,
 697                        "show hash and subject, give twice for upstream branch"),
 698                OPT__QUIET(&quiet, "suppress informational messages"),
 699                OPT_SET_INT('t', "track",  &track, "set up tracking mode (see git-pull(1))",
 700                        BRANCH_TRACK_EXPLICIT),
 701                OPT_SET_INT( 0, "set-upstream",  &track, "change upstream info",
 702                        BRANCH_TRACK_OVERRIDE),
 703                OPT__COLOR(&branch_use_color, "use colored output"),
 704                OPT_SET_INT('r', "remotes",     &kinds, "act on remote-tracking branches",
 705                        REF_REMOTE_BRANCH),
 706                {
 707                        OPTION_CALLBACK, 0, "contains", &with_commit, "commit",
 708                        "print only branches that contain the commit",
 709                        PARSE_OPT_LASTARG_DEFAULT,
 710                        parse_opt_with_commit, (intptr_t)"HEAD",
 711                },
 712                {
 713                        OPTION_CALLBACK, 0, "with", &with_commit, "commit",
 714                        "print only branches that contain the commit",
 715                        PARSE_OPT_HIDDEN | PARSE_OPT_LASTARG_DEFAULT,
 716                        parse_opt_with_commit, (intptr_t) "HEAD",
 717                },
 718                OPT__ABBREV(&abbrev),
 719
 720                OPT_GROUP("Specific git-branch actions:"),
 721                OPT_SET_INT('a', "all", &kinds, "list both remote-tracking and local branches",
 722                        REF_REMOTE_BRANCH | REF_LOCAL_BRANCH),
 723                OPT_BIT('d', "delete", &delete, "delete fully merged branch", 1),
 724                OPT_BIT('D', NULL, &delete, "delete branch (even if not merged)", 2),
 725                OPT_BIT('m', "move", &rename, "move/rename a branch and its reflog", 1),
 726                OPT_BIT('M', NULL, &rename, "move/rename a branch, even if target exists", 2),
 727                OPT_BOOLEAN(0, "list", &list, "list branch names"),
 728                OPT_BOOLEAN('l', "create-reflog", &reflog, "create the branch's reflog"),
 729                OPT_BOOLEAN(0, "edit-description", &edit_description,
 730                            "edit the description for the branch"),
 731                OPT__FORCE(&force_create, "force creation (when already exists)"),
 732                {
 733                        OPTION_CALLBACK, 0, "no-merged", &merge_filter_ref,
 734                        "commit", "print only not merged branches",
 735                        PARSE_OPT_LASTARG_DEFAULT | PARSE_OPT_NONEG,
 736                        opt_parse_merge_filter, (intptr_t) "HEAD",
 737                },
 738                {
 739                        OPTION_CALLBACK, 0, "merged", &merge_filter_ref,
 740                        "commit", "print only merged branches",
 741                        PARSE_OPT_LASTARG_DEFAULT | PARSE_OPT_NONEG,
 742                        opt_parse_merge_filter, (intptr_t) "HEAD",
 743                },
 744                OPT_END(),
 745        };
 746
 747        if (argc == 2 && !strcmp(argv[1], "-h"))
 748                usage_with_options(builtin_branch_usage, options);
 749
 750        git_config(git_branch_config, NULL);
 751
 752        track = git_branch_track;
 753
 754        head = resolve_refdup("HEAD", head_sha1, 0, NULL);
 755        if (!head)
 756                die(_("Failed to resolve HEAD as a valid ref."));
 757        if (!strcmp(head, "HEAD")) {
 758                detached = 1;
 759        } else {
 760                if (prefixcmp(head, "refs/heads/"))
 761                        die(_("HEAD not found below refs/heads!"));
 762                head += 11;
 763        }
 764        hashcpy(merge_filter_ref, head_sha1);
 765
 766        argc = parse_options(argc, argv, prefix, options, builtin_branch_usage,
 767                             0);
 768
 769        if (!delete && !rename && !edit_description && argc == 0)
 770                list = 1;
 771
 772        if (!!delete + !!rename + !!force_create + !!list > 1)
 773                usage_with_options(builtin_branch_usage, options);
 774
 775        if (abbrev == -1)
 776                abbrev = DEFAULT_ABBREV;
 777
 778        if (delete)
 779                return delete_branches(argc, argv, delete > 1, kinds, quiet);
 780        else if (list)
 781                return print_ref_list(kinds, detached, verbose, abbrev,
 782                                      with_commit, argv);
 783        else if (edit_description) {
 784                const char *branch_name;
 785                struct strbuf branch_ref = STRBUF_INIT;
 786
 787                if (detached)
 788                        die("Cannot give description to detached HEAD");
 789                if (!argc)
 790                        branch_name = head;
 791                else if (argc == 1)
 792                        branch_name = argv[0];
 793                else
 794                        usage_with_options(builtin_branch_usage, options);
 795
 796                strbuf_addf(&branch_ref, "refs/heads/%s", branch_name);
 797                if (!ref_exists(branch_ref.buf)) {
 798                        strbuf_release(&branch_ref);
 799
 800                        if (!argc)
 801                                return error("No commit on branch '%s' yet.",
 802                                             branch_name);
 803                        else
 804                                return error("No such branch '%s'.", branch_name);
 805                }
 806                strbuf_release(&branch_ref);
 807
 808                if (edit_branch_description(branch_name))
 809                        return 1;
 810        } else if (rename) {
 811                if (argc == 1)
 812                        rename_branch(head, argv[0], rename > 1);
 813                else if (argc == 2)
 814                        rename_branch(argv[0], argv[1], rename > 1);
 815                else
 816                        usage_with_options(builtin_branch_usage, options);
 817        } else if (argc > 0 && argc <= 2) {
 818                if (kinds != REF_LOCAL_BRANCH)
 819                        die(_("-a and -r options to 'git branch' do not make sense with a branch name"));
 820                create_branch(head, argv[0], (argc == 2) ? argv[1] : head,
 821                              force_create, reflog, 0, quiet, track);
 822        } else
 823                usage_with_options(builtin_branch_usage, options);
 824
 825        return 0;
 826}