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