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