wt-status.con commit Merge branch 'dr/ref-filter-push-track-fix' (f560a4d)
   1#include "cache.h"
   2#include "wt-status.h"
   3#include "object.h"
   4#include "dir.h"
   5#include "commit.h"
   6#include "diff.h"
   7#include "revision.h"
   8#include "diffcore.h"
   9#include "quote.h"
  10#include "run-command.h"
  11#include "argv-array.h"
  12#include "remote.h"
  13#include "refs.h"
  14#include "submodule.h"
  15#include "column.h"
  16#include "strbuf.h"
  17#include "utf8.h"
  18#include "worktree.h"
  19#include "lockfile.h"
  20
  21static const char cut_line[] =
  22"------------------------ >8 ------------------------\n";
  23
  24static char default_wt_status_colors[][COLOR_MAXLEN] = {
  25        GIT_COLOR_NORMAL, /* WT_STATUS_HEADER */
  26        GIT_COLOR_GREEN,  /* WT_STATUS_UPDATED */
  27        GIT_COLOR_RED,    /* WT_STATUS_CHANGED */
  28        GIT_COLOR_RED,    /* WT_STATUS_UNTRACKED */
  29        GIT_COLOR_RED,    /* WT_STATUS_NOBRANCH */
  30        GIT_COLOR_RED,    /* WT_STATUS_UNMERGED */
  31        GIT_COLOR_GREEN,  /* WT_STATUS_LOCAL_BRANCH */
  32        GIT_COLOR_RED,    /* WT_STATUS_REMOTE_BRANCH */
  33        GIT_COLOR_NIL,    /* WT_STATUS_ONBRANCH */
  34};
  35
  36static const char *color(int slot, struct wt_status *s)
  37{
  38        const char *c = "";
  39        if (want_color(s->use_color))
  40                c = s->color_palette[slot];
  41        if (slot == WT_STATUS_ONBRANCH && color_is_nil(c))
  42                c = s->color_palette[WT_STATUS_HEADER];
  43        return c;
  44}
  45
  46static void status_vprintf(struct wt_status *s, int at_bol, const char *color,
  47                const char *fmt, va_list ap, const char *trail)
  48{
  49        struct strbuf sb = STRBUF_INIT;
  50        struct strbuf linebuf = STRBUF_INIT;
  51        const char *line, *eol;
  52
  53        strbuf_vaddf(&sb, fmt, ap);
  54        if (!sb.len) {
  55                if (s->display_comment_prefix) {
  56                        strbuf_addch(&sb, comment_line_char);
  57                        if (!trail)
  58                                strbuf_addch(&sb, ' ');
  59                }
  60                color_print_strbuf(s->fp, color, &sb);
  61                if (trail)
  62                        fprintf(s->fp, "%s", trail);
  63                strbuf_release(&sb);
  64                return;
  65        }
  66        for (line = sb.buf; *line; line = eol + 1) {
  67                eol = strchr(line, '\n');
  68
  69                strbuf_reset(&linebuf);
  70                if (at_bol && s->display_comment_prefix) {
  71                        strbuf_addch(&linebuf, comment_line_char);
  72                        if (*line != '\n' && *line != '\t')
  73                                strbuf_addch(&linebuf, ' ');
  74                }
  75                if (eol)
  76                        strbuf_add(&linebuf, line, eol - line);
  77                else
  78                        strbuf_addstr(&linebuf, line);
  79                color_print_strbuf(s->fp, color, &linebuf);
  80                if (eol)
  81                        fprintf(s->fp, "\n");
  82                else
  83                        break;
  84                at_bol = 1;
  85        }
  86        if (trail)
  87                fprintf(s->fp, "%s", trail);
  88        strbuf_release(&linebuf);
  89        strbuf_release(&sb);
  90}
  91
  92void status_printf_ln(struct wt_status *s, const char *color,
  93                        const char *fmt, ...)
  94{
  95        va_list ap;
  96
  97        va_start(ap, fmt);
  98        status_vprintf(s, 1, color, fmt, ap, "\n");
  99        va_end(ap);
 100}
 101
 102void status_printf(struct wt_status *s, const char *color,
 103                        const char *fmt, ...)
 104{
 105        va_list ap;
 106
 107        va_start(ap, fmt);
 108        status_vprintf(s, 1, color, fmt, ap, NULL);
 109        va_end(ap);
 110}
 111
 112static void status_printf_more(struct wt_status *s, const char *color,
 113                               const char *fmt, ...)
 114{
 115        va_list ap;
 116
 117        va_start(ap, fmt);
 118        status_vprintf(s, 0, color, fmt, ap, NULL);
 119        va_end(ap);
 120}
 121
 122void wt_status_prepare(struct repository *r, struct wt_status *s)
 123{
 124        memset(s, 0, sizeof(*s));
 125        s->repo = r;
 126        memcpy(s->color_palette, default_wt_status_colors,
 127               sizeof(default_wt_status_colors));
 128        s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
 129        s->use_color = -1;
 130        s->relative_paths = 1;
 131        s->branch = resolve_refdup("HEAD", 0, NULL, NULL);
 132        s->reference = "HEAD";
 133        s->fp = stdout;
 134        s->index_file = get_index_file();
 135        s->change.strdup_strings = 1;
 136        s->untracked.strdup_strings = 1;
 137        s->ignored.strdup_strings = 1;
 138        s->show_branch = -1;  /* unspecified */
 139        s->show_stash = 0;
 140        s->ahead_behind_flags = AHEAD_BEHIND_UNSPECIFIED;
 141        s->display_comment_prefix = 0;
 142        s->detect_rename = -1;
 143        s->rename_score = -1;
 144        s->rename_limit = -1;
 145}
 146
 147static void wt_longstatus_print_unmerged_header(struct wt_status *s)
 148{
 149        int i;
 150        int del_mod_conflict = 0;
 151        int both_deleted = 0;
 152        int not_deleted = 0;
 153        const char *c = color(WT_STATUS_HEADER, s);
 154
 155        status_printf_ln(s, c, _("Unmerged paths:"));
 156
 157        for (i = 0; i < s->change.nr; i++) {
 158                struct string_list_item *it = &(s->change.items[i]);
 159                struct wt_status_change_data *d = it->util;
 160
 161                switch (d->stagemask) {
 162                case 0:
 163                        break;
 164                case 1:
 165                        both_deleted = 1;
 166                        break;
 167                case 3:
 168                case 5:
 169                        del_mod_conflict = 1;
 170                        break;
 171                default:
 172                        not_deleted = 1;
 173                        break;
 174                }
 175        }
 176
 177        if (!s->hints)
 178                return;
 179        if (s->whence != FROM_COMMIT)
 180                ;
 181        else if (!s->is_initial)
 182                status_printf_ln(s, c, _("  (use \"git reset %s <file>...\" to unstage)"), s->reference);
 183        else
 184                status_printf_ln(s, c, _("  (use \"git rm --cached <file>...\" to unstage)"));
 185
 186        if (!both_deleted) {
 187                if (!del_mod_conflict)
 188                        status_printf_ln(s, c, _("  (use \"git add <file>...\" to mark resolution)"));
 189                else
 190                        status_printf_ln(s, c, _("  (use \"git add/rm <file>...\" as appropriate to mark resolution)"));
 191        } else if (!del_mod_conflict && !not_deleted) {
 192                status_printf_ln(s, c, _("  (use \"git rm <file>...\" to mark resolution)"));
 193        } else {
 194                status_printf_ln(s, c, _("  (use \"git add/rm <file>...\" as appropriate to mark resolution)"));
 195        }
 196        status_printf_ln(s, c, "%s", "");
 197}
 198
 199static void wt_longstatus_print_cached_header(struct wt_status *s)
 200{
 201        const char *c = color(WT_STATUS_HEADER, s);
 202
 203        status_printf_ln(s, c, _("Changes to be committed:"));
 204        if (!s->hints)
 205                return;
 206        if (s->whence != FROM_COMMIT)
 207                ; /* NEEDSWORK: use "git reset --unresolve"??? */
 208        else if (!s->is_initial)
 209                status_printf_ln(s, c, _("  (use \"git reset %s <file>...\" to unstage)"), s->reference);
 210        else
 211                status_printf_ln(s, c, _("  (use \"git rm --cached <file>...\" to unstage)"));
 212        status_printf_ln(s, c, "%s", "");
 213}
 214
 215static void wt_longstatus_print_dirty_header(struct wt_status *s,
 216                                             int has_deleted,
 217                                             int has_dirty_submodules)
 218{
 219        const char *c = color(WT_STATUS_HEADER, s);
 220
 221        status_printf_ln(s, c, _("Changes not staged for commit:"));
 222        if (!s->hints)
 223                return;
 224        if (!has_deleted)
 225                status_printf_ln(s, c, _("  (use \"git add <file>...\" to update what will be committed)"));
 226        else
 227                status_printf_ln(s, c, _("  (use \"git add/rm <file>...\" to update what will be committed)"));
 228        status_printf_ln(s, c, _("  (use \"git checkout -- <file>...\" to discard changes in working directory)"));
 229        if (has_dirty_submodules)
 230                status_printf_ln(s, c, _("  (commit or discard the untracked or modified content in submodules)"));
 231        status_printf_ln(s, c, "%s", "");
 232}
 233
 234static void wt_longstatus_print_other_header(struct wt_status *s,
 235                                             const char *what,
 236                                             const char *how)
 237{
 238        const char *c = color(WT_STATUS_HEADER, s);
 239        status_printf_ln(s, c, "%s:", what);
 240        if (!s->hints)
 241                return;
 242        status_printf_ln(s, c, _("  (use \"git %s <file>...\" to include in what will be committed)"), how);
 243        status_printf_ln(s, c, "%s", "");
 244}
 245
 246static void wt_longstatus_print_trailer(struct wt_status *s)
 247{
 248        status_printf_ln(s, color(WT_STATUS_HEADER, s), "%s", "");
 249}
 250
 251#define quote_path quote_path_relative
 252
 253static const char *wt_status_unmerged_status_string(int stagemask)
 254{
 255        switch (stagemask) {
 256        case 1:
 257                return _("both deleted:");
 258        case 2:
 259                return _("added by us:");
 260        case 3:
 261                return _("deleted by them:");
 262        case 4:
 263                return _("added by them:");
 264        case 5:
 265                return _("deleted by us:");
 266        case 6:
 267                return _("both added:");
 268        case 7:
 269                return _("both modified:");
 270        default:
 271                BUG("unhandled unmerged status %x", stagemask);
 272        }
 273}
 274
 275static const char *wt_status_diff_status_string(int status)
 276{
 277        switch (status) {
 278        case DIFF_STATUS_ADDED:
 279                return _("new file:");
 280        case DIFF_STATUS_COPIED:
 281                return _("copied:");
 282        case DIFF_STATUS_DELETED:
 283                return _("deleted:");
 284        case DIFF_STATUS_MODIFIED:
 285                return _("modified:");
 286        case DIFF_STATUS_RENAMED:
 287                return _("renamed:");
 288        case DIFF_STATUS_TYPE_CHANGED:
 289                return _("typechange:");
 290        case DIFF_STATUS_UNKNOWN:
 291                return _("unknown:");
 292        case DIFF_STATUS_UNMERGED:
 293                return _("unmerged:");
 294        default:
 295                return NULL;
 296        }
 297}
 298
 299static int maxwidth(const char *(*label)(int), int minval, int maxval)
 300{
 301        int result = 0, i;
 302
 303        for (i = minval; i <= maxval; i++) {
 304                const char *s = label(i);
 305                int len = s ? utf8_strwidth(s) : 0;
 306                if (len > result)
 307                        result = len;
 308        }
 309        return result;
 310}
 311
 312static void wt_longstatus_print_unmerged_data(struct wt_status *s,
 313                                              struct string_list_item *it)
 314{
 315        const char *c = color(WT_STATUS_UNMERGED, s);
 316        struct wt_status_change_data *d = it->util;
 317        struct strbuf onebuf = STRBUF_INIT;
 318        static char *padding;
 319        static int label_width;
 320        const char *one, *how;
 321        int len;
 322
 323        if (!padding) {
 324                label_width = maxwidth(wt_status_unmerged_status_string, 1, 7);
 325                label_width += strlen(" ");
 326                padding = xmallocz(label_width);
 327                memset(padding, ' ', label_width);
 328        }
 329
 330        one = quote_path(it->string, s->prefix, &onebuf);
 331        status_printf(s, color(WT_STATUS_HEADER, s), "\t");
 332
 333        how = wt_status_unmerged_status_string(d->stagemask);
 334        len = label_width - utf8_strwidth(how);
 335        status_printf_more(s, c, "%s%.*s%s\n", how, len, padding, one);
 336        strbuf_release(&onebuf);
 337}
 338
 339static void wt_longstatus_print_change_data(struct wt_status *s,
 340                                            int change_type,
 341                                            struct string_list_item *it)
 342{
 343        struct wt_status_change_data *d = it->util;
 344        const char *c = color(change_type, s);
 345        int status;
 346        char *one_name;
 347        char *two_name;
 348        const char *one, *two;
 349        struct strbuf onebuf = STRBUF_INIT, twobuf = STRBUF_INIT;
 350        struct strbuf extra = STRBUF_INIT;
 351        static char *padding;
 352        static int label_width;
 353        const char *what;
 354        int len;
 355
 356        if (!padding) {
 357                /* If DIFF_STATUS_* uses outside the range [A..Z], we're in trouble */
 358                label_width = maxwidth(wt_status_diff_status_string, 'A', 'Z');
 359                label_width += strlen(" ");
 360                padding = xmallocz(label_width);
 361                memset(padding, ' ', label_width);
 362        }
 363
 364        one_name = two_name = it->string;
 365        switch (change_type) {
 366        case WT_STATUS_UPDATED:
 367                status = d->index_status;
 368                break;
 369        case WT_STATUS_CHANGED:
 370                if (d->new_submodule_commits || d->dirty_submodule) {
 371                        strbuf_addstr(&extra, " (");
 372                        if (d->new_submodule_commits)
 373                                strbuf_addstr(&extra, _("new commits, "));
 374                        if (d->dirty_submodule & DIRTY_SUBMODULE_MODIFIED)
 375                                strbuf_addstr(&extra, _("modified content, "));
 376                        if (d->dirty_submodule & DIRTY_SUBMODULE_UNTRACKED)
 377                                strbuf_addstr(&extra, _("untracked content, "));
 378                        strbuf_setlen(&extra, extra.len - 2);
 379                        strbuf_addch(&extra, ')');
 380                }
 381                status = d->worktree_status;
 382                break;
 383        default:
 384                BUG("unhandled change_type %d in wt_longstatus_print_change_data",
 385                    change_type);
 386        }
 387
 388        /*
 389         * Only pick up the rename it's relevant. If the rename is for
 390         * the changed section and we're printing the updated section,
 391         * ignore it.
 392         */
 393        if (d->rename_status == status)
 394                one_name = d->rename_source;
 395
 396        one = quote_path(one_name, s->prefix, &onebuf);
 397        two = quote_path(two_name, s->prefix, &twobuf);
 398
 399        status_printf(s, color(WT_STATUS_HEADER, s), "\t");
 400        what = wt_status_diff_status_string(status);
 401        if (!what)
 402                BUG("unhandled diff status %c", status);
 403        len = label_width - utf8_strwidth(what);
 404        assert(len >= 0);
 405        if (one_name != two_name)
 406                status_printf_more(s, c, "%s%.*s%s -> %s",
 407                                   what, len, padding, one, two);
 408        else
 409                status_printf_more(s, c, "%s%.*s%s",
 410                                   what, len, padding, one);
 411        if (extra.len) {
 412                status_printf_more(s, color(WT_STATUS_HEADER, s), "%s", extra.buf);
 413                strbuf_release(&extra);
 414        }
 415        status_printf_more(s, GIT_COLOR_NORMAL, "\n");
 416        strbuf_release(&onebuf);
 417        strbuf_release(&twobuf);
 418}
 419
 420static char short_submodule_status(struct wt_status_change_data *d)
 421{
 422        if (d->new_submodule_commits)
 423                return 'M';
 424        if (d->dirty_submodule & DIRTY_SUBMODULE_MODIFIED)
 425                return 'm';
 426        if (d->dirty_submodule & DIRTY_SUBMODULE_UNTRACKED)
 427                return '?';
 428        return d->worktree_status;
 429}
 430
 431static void wt_status_collect_changed_cb(struct diff_queue_struct *q,
 432                                         struct diff_options *options,
 433                                         void *data)
 434{
 435        struct wt_status *s = data;
 436        int i;
 437
 438        if (!q->nr)
 439                return;
 440        s->workdir_dirty = 1;
 441        for (i = 0; i < q->nr; i++) {
 442                struct diff_filepair *p;
 443                struct string_list_item *it;
 444                struct wt_status_change_data *d;
 445
 446                p = q->queue[i];
 447                it = string_list_insert(&s->change, p->two->path);
 448                d = it->util;
 449                if (!d) {
 450                        d = xcalloc(1, sizeof(*d));
 451                        it->util = d;
 452                }
 453                if (!d->worktree_status)
 454                        d->worktree_status = p->status;
 455                if (S_ISGITLINK(p->two->mode)) {
 456                        d->dirty_submodule = p->two->dirty_submodule;
 457                        d->new_submodule_commits = !oideq(&p->one->oid,
 458                                                          &p->two->oid);
 459                        if (s->status_format == STATUS_FORMAT_SHORT)
 460                                d->worktree_status = short_submodule_status(d);
 461                }
 462
 463                switch (p->status) {
 464                case DIFF_STATUS_ADDED:
 465                        d->mode_worktree = p->two->mode;
 466                        break;
 467
 468                case DIFF_STATUS_DELETED:
 469                        d->mode_index = p->one->mode;
 470                        oidcpy(&d->oid_index, &p->one->oid);
 471                        /* mode_worktree is zero for a delete. */
 472                        break;
 473
 474                case DIFF_STATUS_COPIED:
 475                case DIFF_STATUS_RENAMED:
 476                        if (d->rename_status)
 477                                BUG("multiple renames on the same target? how?");
 478                        d->rename_source = xstrdup(p->one->path);
 479                        d->rename_score = p->score * 100 / MAX_SCORE;
 480                        d->rename_status = p->status;
 481                        /* fallthru */
 482                case DIFF_STATUS_MODIFIED:
 483                case DIFF_STATUS_TYPE_CHANGED:
 484                case DIFF_STATUS_UNMERGED:
 485                        d->mode_index = p->one->mode;
 486                        d->mode_worktree = p->two->mode;
 487                        oidcpy(&d->oid_index, &p->one->oid);
 488                        break;
 489
 490                default:
 491                        BUG("unhandled diff-files status '%c'", p->status);
 492                        break;
 493                }
 494
 495        }
 496}
 497
 498static int unmerged_mask(struct index_state *istate, const char *path)
 499{
 500        int pos, mask;
 501        const struct cache_entry *ce;
 502
 503        pos = index_name_pos(istate, path, strlen(path));
 504        if (0 <= pos)
 505                return 0;
 506
 507        mask = 0;
 508        pos = -pos-1;
 509        while (pos < istate->cache_nr) {
 510                ce = istate->cache[pos++];
 511                if (strcmp(ce->name, path) || !ce_stage(ce))
 512                        break;
 513                mask |= (1 << (ce_stage(ce) - 1));
 514        }
 515        return mask;
 516}
 517
 518static void wt_status_collect_updated_cb(struct diff_queue_struct *q,
 519                                         struct diff_options *options,
 520                                         void *data)
 521{
 522        struct wt_status *s = data;
 523        int i;
 524
 525        for (i = 0; i < q->nr; i++) {
 526                struct diff_filepair *p;
 527                struct string_list_item *it;
 528                struct wt_status_change_data *d;
 529
 530                p = q->queue[i];
 531                it = string_list_insert(&s->change, p->two->path);
 532                d = it->util;
 533                if (!d) {
 534                        d = xcalloc(1, sizeof(*d));
 535                        it->util = d;
 536                }
 537                if (!d->index_status)
 538                        d->index_status = p->status;
 539                switch (p->status) {
 540                case DIFF_STATUS_ADDED:
 541                        /* Leave {mode,oid}_head zero for an add. */
 542                        d->mode_index = p->two->mode;
 543                        oidcpy(&d->oid_index, &p->two->oid);
 544                        s->committable = 1;
 545                        break;
 546                case DIFF_STATUS_DELETED:
 547                        d->mode_head = p->one->mode;
 548                        oidcpy(&d->oid_head, &p->one->oid);
 549                        s->committable = 1;
 550                        /* Leave {mode,oid}_index zero for a delete. */
 551                        break;
 552
 553                case DIFF_STATUS_COPIED:
 554                case DIFF_STATUS_RENAMED:
 555                        if (d->rename_status)
 556                                BUG("multiple renames on the same target? how?");
 557                        d->rename_source = xstrdup(p->one->path);
 558                        d->rename_score = p->score * 100 / MAX_SCORE;
 559                        d->rename_status = p->status;
 560                        /* fallthru */
 561                case DIFF_STATUS_MODIFIED:
 562                case DIFF_STATUS_TYPE_CHANGED:
 563                        d->mode_head = p->one->mode;
 564                        d->mode_index = p->two->mode;
 565                        oidcpy(&d->oid_head, &p->one->oid);
 566                        oidcpy(&d->oid_index, &p->two->oid);
 567                        s->committable = 1;
 568                        break;
 569                case DIFF_STATUS_UNMERGED:
 570                        d->stagemask = unmerged_mask(s->repo->index,
 571                                                     p->two->path);
 572                        /*
 573                         * Don't bother setting {mode,oid}_{head,index} since the print
 574                         * code will output the stage values directly and not use the
 575                         * values in these fields.
 576                         */
 577                        break;
 578
 579                default:
 580                        BUG("unhandled diff-index status '%c'", p->status);
 581                        break;
 582                }
 583        }
 584}
 585
 586static void wt_status_collect_changes_worktree(struct wt_status *s)
 587{
 588        struct rev_info rev;
 589
 590        repo_init_revisions(s->repo, &rev, NULL);
 591        setup_revisions(0, NULL, &rev, NULL);
 592        rev.diffopt.output_format |= DIFF_FORMAT_CALLBACK;
 593        rev.diffopt.flags.dirty_submodules = 1;
 594        rev.diffopt.ita_invisible_in_index = 1;
 595        if (!s->show_untracked_files)
 596                rev.diffopt.flags.ignore_untracked_in_submodules = 1;
 597        if (s->ignore_submodule_arg) {
 598                rev.diffopt.flags.override_submodule_config = 1;
 599                handle_ignore_submodules_arg(&rev.diffopt, s->ignore_submodule_arg);
 600        }
 601        rev.diffopt.format_callback = wt_status_collect_changed_cb;
 602        rev.diffopt.format_callback_data = s;
 603        rev.diffopt.detect_rename = s->detect_rename >= 0 ? s->detect_rename : rev.diffopt.detect_rename;
 604        rev.diffopt.rename_limit = s->rename_limit >= 0 ? s->rename_limit : rev.diffopt.rename_limit;
 605        rev.diffopt.rename_score = s->rename_score >= 0 ? s->rename_score : rev.diffopt.rename_score;
 606        copy_pathspec(&rev.prune_data, &s->pathspec);
 607        run_diff_files(&rev, 0);
 608}
 609
 610static void wt_status_collect_changes_index(struct wt_status *s)
 611{
 612        struct rev_info rev;
 613        struct setup_revision_opt opt;
 614
 615        repo_init_revisions(s->repo, &rev, NULL);
 616        memset(&opt, 0, sizeof(opt));
 617        opt.def = s->is_initial ? empty_tree_oid_hex() : s->reference;
 618        setup_revisions(0, NULL, &rev, &opt);
 619
 620        rev.diffopt.flags.override_submodule_config = 1;
 621        rev.diffopt.ita_invisible_in_index = 1;
 622        if (s->ignore_submodule_arg) {
 623                handle_ignore_submodules_arg(&rev.diffopt, s->ignore_submodule_arg);
 624        } else {
 625                /*
 626                 * Unless the user did explicitly request a submodule ignore
 627                 * mode by passing a command line option we do not ignore any
 628                 * changed submodule SHA-1s when comparing index and HEAD, no
 629                 * matter what is configured. Otherwise the user won't be
 630                 * shown any submodules she manually added (and which are
 631                 * staged to be committed), which would be really confusing.
 632                 */
 633                handle_ignore_submodules_arg(&rev.diffopt, "dirty");
 634        }
 635
 636        rev.diffopt.output_format |= DIFF_FORMAT_CALLBACK;
 637        rev.diffopt.format_callback = wt_status_collect_updated_cb;
 638        rev.diffopt.format_callback_data = s;
 639        rev.diffopt.detect_rename = s->detect_rename >= 0 ? s->detect_rename : rev.diffopt.detect_rename;
 640        rev.diffopt.rename_limit = s->rename_limit >= 0 ? s->rename_limit : rev.diffopt.rename_limit;
 641        rev.diffopt.rename_score = s->rename_score >= 0 ? s->rename_score : rev.diffopt.rename_score;
 642        copy_pathspec(&rev.prune_data, &s->pathspec);
 643        run_diff_index(&rev, 1);
 644}
 645
 646static void wt_status_collect_changes_initial(struct wt_status *s)
 647{
 648        struct index_state *istate = s->repo->index;
 649        int i;
 650
 651        for (i = 0; i < istate->cache_nr; i++) {
 652                struct string_list_item *it;
 653                struct wt_status_change_data *d;
 654                const struct cache_entry *ce = istate->cache[i];
 655
 656                if (!ce_path_match(istate, ce, &s->pathspec, NULL))
 657                        continue;
 658                if (ce_intent_to_add(ce))
 659                        continue;
 660                it = string_list_insert(&s->change, ce->name);
 661                d = it->util;
 662                if (!d) {
 663                        d = xcalloc(1, sizeof(*d));
 664                        it->util = d;
 665                }
 666                if (ce_stage(ce)) {
 667                        d->index_status = DIFF_STATUS_UNMERGED;
 668                        d->stagemask |= (1 << (ce_stage(ce) - 1));
 669                        /*
 670                         * Don't bother setting {mode,oid}_{head,index} since the print
 671                         * code will output the stage values directly and not use the
 672                         * values in these fields.
 673                         */
 674                        s->committable = 1;
 675                } else {
 676                        d->index_status = DIFF_STATUS_ADDED;
 677                        /* Leave {mode,oid}_head zero for adds. */
 678                        d->mode_index = ce->ce_mode;
 679                        oidcpy(&d->oid_index, &ce->oid);
 680                        s->committable = 1;
 681                }
 682        }
 683}
 684
 685static void wt_status_collect_untracked(struct wt_status *s)
 686{
 687        int i;
 688        struct dir_struct dir;
 689        uint64_t t_begin = getnanotime();
 690        struct index_state *istate = s->repo->index;
 691
 692        if (!s->show_untracked_files)
 693                return;
 694
 695        memset(&dir, 0, sizeof(dir));
 696        if (s->show_untracked_files != SHOW_ALL_UNTRACKED_FILES)
 697                dir.flags |=
 698                        DIR_SHOW_OTHER_DIRECTORIES | DIR_HIDE_EMPTY_DIRECTORIES;
 699        if (s->show_ignored_mode) {
 700                dir.flags |= DIR_SHOW_IGNORED_TOO;
 701
 702                if (s->show_ignored_mode == SHOW_MATCHING_IGNORED)
 703                        dir.flags |= DIR_SHOW_IGNORED_TOO_MODE_MATCHING;
 704        } else {
 705                dir.untracked = istate->untracked;
 706        }
 707
 708        setup_standard_excludes(&dir);
 709
 710        fill_directory(&dir, istate, &s->pathspec);
 711
 712        for (i = 0; i < dir.nr; i++) {
 713                struct dir_entry *ent = dir.entries[i];
 714                if (index_name_is_other(istate, ent->name, ent->len) &&
 715                    dir_path_match(istate, ent, &s->pathspec, 0, NULL))
 716                        string_list_insert(&s->untracked, ent->name);
 717                free(ent);
 718        }
 719
 720        for (i = 0; i < dir.ignored_nr; i++) {
 721                struct dir_entry *ent = dir.ignored[i];
 722                if (index_name_is_other(istate, ent->name, ent->len) &&
 723                    dir_path_match(istate, ent, &s->pathspec, 0, NULL))
 724                        string_list_insert(&s->ignored, ent->name);
 725                free(ent);
 726        }
 727
 728        free(dir.entries);
 729        free(dir.ignored);
 730        clear_directory(&dir);
 731
 732        if (advice_status_u_option)
 733                s->untracked_in_ms = (getnanotime() - t_begin) / 1000000;
 734}
 735
 736static int has_unmerged(struct wt_status *s)
 737{
 738        int i;
 739
 740        for (i = 0; i < s->change.nr; i++) {
 741                struct wt_status_change_data *d;
 742                d = s->change.items[i].util;
 743                if (d->stagemask)
 744                        return 1;
 745        }
 746        return 0;
 747}
 748
 749void wt_status_collect(struct wt_status *s)
 750{
 751        trace2_region_enter("status", "worktrees", s->repo);
 752        wt_status_collect_changes_worktree(s);
 753        trace2_region_leave("status", "worktrees", s->repo);
 754
 755        if (s->is_initial) {
 756                trace2_region_enter("status", "initial", s->repo);
 757                wt_status_collect_changes_initial(s);
 758                trace2_region_leave("status", "initial", s->repo);
 759        } else {
 760                trace2_region_enter("status", "index", s->repo);
 761                wt_status_collect_changes_index(s);
 762                trace2_region_leave("status", "index", s->repo);
 763        }
 764
 765        trace2_region_enter("status", "untracked", s->repo);
 766        wt_status_collect_untracked(s);
 767        trace2_region_leave("status", "untracked", s->repo);
 768
 769        wt_status_get_state(s->repo, &s->state, s->branch && !strcmp(s->branch, "HEAD"));
 770        if (s->state.merge_in_progress && !has_unmerged(s))
 771                s->committable = 1;
 772}
 773
 774void wt_status_collect_free_buffers(struct wt_status *s)
 775{
 776        free(s->state.branch);
 777        free(s->state.onto);
 778        free(s->state.detached_from);
 779}
 780
 781static void wt_longstatus_print_unmerged(struct wt_status *s)
 782{
 783        int shown_header = 0;
 784        int i;
 785
 786        for (i = 0; i < s->change.nr; i++) {
 787                struct wt_status_change_data *d;
 788                struct string_list_item *it;
 789                it = &(s->change.items[i]);
 790                d = it->util;
 791                if (!d->stagemask)
 792                        continue;
 793                if (!shown_header) {
 794                        wt_longstatus_print_unmerged_header(s);
 795                        shown_header = 1;
 796                }
 797                wt_longstatus_print_unmerged_data(s, it);
 798        }
 799        if (shown_header)
 800                wt_longstatus_print_trailer(s);
 801
 802}
 803
 804static void wt_longstatus_print_updated(struct wt_status *s)
 805{
 806        int shown_header = 0;
 807        int i;
 808
 809        for (i = 0; i < s->change.nr; i++) {
 810                struct wt_status_change_data *d;
 811                struct string_list_item *it;
 812                it = &(s->change.items[i]);
 813                d = it->util;
 814                if (!d->index_status ||
 815                    d->index_status == DIFF_STATUS_UNMERGED)
 816                        continue;
 817                if (!shown_header) {
 818                        wt_longstatus_print_cached_header(s);
 819                        shown_header = 1;
 820                }
 821                wt_longstatus_print_change_data(s, WT_STATUS_UPDATED, it);
 822        }
 823        if (shown_header)
 824                wt_longstatus_print_trailer(s);
 825}
 826
 827/*
 828 * -1 : has delete
 829 *  0 : no change
 830 *  1 : some change but no delete
 831 */
 832static int wt_status_check_worktree_changes(struct wt_status *s,
 833                                             int *dirty_submodules)
 834{
 835        int i;
 836        int changes = 0;
 837
 838        *dirty_submodules = 0;
 839
 840        for (i = 0; i < s->change.nr; i++) {
 841                struct wt_status_change_data *d;
 842                d = s->change.items[i].util;
 843                if (!d->worktree_status ||
 844                    d->worktree_status == DIFF_STATUS_UNMERGED)
 845                        continue;
 846                if (!changes)
 847                        changes = 1;
 848                if (d->dirty_submodule)
 849                        *dirty_submodules = 1;
 850                if (d->worktree_status == DIFF_STATUS_DELETED)
 851                        changes = -1;
 852        }
 853        return changes;
 854}
 855
 856static void wt_longstatus_print_changed(struct wt_status *s)
 857{
 858        int i, dirty_submodules;
 859        int worktree_changes = wt_status_check_worktree_changes(s, &dirty_submodules);
 860
 861        if (!worktree_changes)
 862                return;
 863
 864        wt_longstatus_print_dirty_header(s, worktree_changes < 0, dirty_submodules);
 865
 866        for (i = 0; i < s->change.nr; i++) {
 867                struct wt_status_change_data *d;
 868                struct string_list_item *it;
 869                it = &(s->change.items[i]);
 870                d = it->util;
 871                if (!d->worktree_status ||
 872                    d->worktree_status == DIFF_STATUS_UNMERGED)
 873                        continue;
 874                wt_longstatus_print_change_data(s, WT_STATUS_CHANGED, it);
 875        }
 876        wt_longstatus_print_trailer(s);
 877}
 878
 879static int stash_count_refs(struct object_id *ooid, struct object_id *noid,
 880                            const char *email, timestamp_t timestamp, int tz,
 881                            const char *message, void *cb_data)
 882{
 883        int *c = cb_data;
 884        (*c)++;
 885        return 0;
 886}
 887
 888static void wt_longstatus_print_stash_summary(struct wt_status *s)
 889{
 890        int stash_count = 0;
 891
 892        for_each_reflog_ent("refs/stash", stash_count_refs, &stash_count);
 893        if (stash_count > 0)
 894                status_printf_ln(s, GIT_COLOR_NORMAL,
 895                                 Q_("Your stash currently has %d entry",
 896                                    "Your stash currently has %d entries", stash_count),
 897                                 stash_count);
 898}
 899
 900static void wt_longstatus_print_submodule_summary(struct wt_status *s, int uncommitted)
 901{
 902        struct child_process sm_summary = CHILD_PROCESS_INIT;
 903        struct strbuf cmd_stdout = STRBUF_INIT;
 904        struct strbuf summary = STRBUF_INIT;
 905        char *summary_content;
 906
 907        argv_array_pushf(&sm_summary.env_array, "GIT_INDEX_FILE=%s",
 908                         s->index_file);
 909
 910        argv_array_push(&sm_summary.args, "submodule");
 911        argv_array_push(&sm_summary.args, "summary");
 912        argv_array_push(&sm_summary.args, uncommitted ? "--files" : "--cached");
 913        argv_array_push(&sm_summary.args, "--for-status");
 914        argv_array_push(&sm_summary.args, "--summary-limit");
 915        argv_array_pushf(&sm_summary.args, "%d", s->submodule_summary);
 916        if (!uncommitted)
 917                argv_array_push(&sm_summary.args, s->amend ? "HEAD^" : "HEAD");
 918
 919        sm_summary.git_cmd = 1;
 920        sm_summary.no_stdin = 1;
 921
 922        capture_command(&sm_summary, &cmd_stdout, 1024);
 923
 924        /* prepend header, only if there's an actual output */
 925        if (cmd_stdout.len) {
 926                if (uncommitted)
 927                        strbuf_addstr(&summary, _("Submodules changed but not updated:"));
 928                else
 929                        strbuf_addstr(&summary, _("Submodule changes to be committed:"));
 930                strbuf_addstr(&summary, "\n\n");
 931        }
 932        strbuf_addbuf(&summary, &cmd_stdout);
 933        strbuf_release(&cmd_stdout);
 934
 935        if (s->display_comment_prefix) {
 936                size_t len;
 937                summary_content = strbuf_detach(&summary, &len);
 938                strbuf_add_commented_lines(&summary, summary_content, len);
 939                free(summary_content);
 940        }
 941
 942        fputs(summary.buf, s->fp);
 943        strbuf_release(&summary);
 944}
 945
 946static void wt_longstatus_print_other(struct wt_status *s,
 947                                      struct string_list *l,
 948                                      const char *what,
 949                                      const char *how)
 950{
 951        int i;
 952        struct strbuf buf = STRBUF_INIT;
 953        static struct string_list output = STRING_LIST_INIT_DUP;
 954        struct column_options copts;
 955
 956        if (!l->nr)
 957                return;
 958
 959        wt_longstatus_print_other_header(s, what, how);
 960
 961        for (i = 0; i < l->nr; i++) {
 962                struct string_list_item *it;
 963                const char *path;
 964                it = &(l->items[i]);
 965                path = quote_path(it->string, s->prefix, &buf);
 966                if (column_active(s->colopts)) {
 967                        string_list_append(&output, path);
 968                        continue;
 969                }
 970                status_printf(s, color(WT_STATUS_HEADER, s), "\t");
 971                status_printf_more(s, color(WT_STATUS_UNTRACKED, s),
 972                                   "%s\n", path);
 973        }
 974
 975        strbuf_release(&buf);
 976        if (!column_active(s->colopts))
 977                goto conclude;
 978
 979        strbuf_addf(&buf, "%s%s\t%s",
 980                    color(WT_STATUS_HEADER, s),
 981                    s->display_comment_prefix ? "#" : "",
 982                    color(WT_STATUS_UNTRACKED, s));
 983        memset(&copts, 0, sizeof(copts));
 984        copts.padding = 1;
 985        copts.indent = buf.buf;
 986        if (want_color(s->use_color))
 987                copts.nl = GIT_COLOR_RESET "\n";
 988        print_columns(&output, s->colopts, &copts);
 989        string_list_clear(&output, 0);
 990        strbuf_release(&buf);
 991conclude:
 992        status_printf_ln(s, GIT_COLOR_NORMAL, "%s", "");
 993}
 994
 995size_t wt_status_locate_end(const char *s, size_t len)
 996{
 997        const char *p;
 998        struct strbuf pattern = STRBUF_INIT;
 999
1000        strbuf_addf(&pattern, "\n%c %s", comment_line_char, cut_line);
1001        if (starts_with(s, pattern.buf + 1))
1002                len = 0;
1003        else if ((p = strstr(s, pattern.buf)))
1004                len = p - s + 1;
1005        strbuf_release(&pattern);
1006        return len;
1007}
1008
1009void wt_status_append_cut_line(struct strbuf *buf)
1010{
1011        const char *explanation = _("Do not modify or remove the line above.\nEverything below it will be ignored.");
1012
1013        strbuf_commented_addf(buf, "%s", cut_line);
1014        strbuf_add_commented_lines(buf, explanation, strlen(explanation));
1015}
1016
1017void wt_status_add_cut_line(FILE *fp)
1018{
1019        struct strbuf buf = STRBUF_INIT;
1020
1021        wt_status_append_cut_line(&buf);
1022        fputs(buf.buf, fp);
1023        strbuf_release(&buf);
1024}
1025
1026static void wt_longstatus_print_verbose(struct wt_status *s)
1027{
1028        struct rev_info rev;
1029        struct setup_revision_opt opt;
1030        int dirty_submodules;
1031        const char *c = color(WT_STATUS_HEADER, s);
1032
1033        repo_init_revisions(s->repo, &rev, NULL);
1034        rev.diffopt.flags.allow_textconv = 1;
1035        rev.diffopt.ita_invisible_in_index = 1;
1036
1037        memset(&opt, 0, sizeof(opt));
1038        opt.def = s->is_initial ? empty_tree_oid_hex() : s->reference;
1039        setup_revisions(0, NULL, &rev, &opt);
1040
1041        rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
1042        rev.diffopt.detect_rename = s->detect_rename >= 0 ? s->detect_rename : rev.diffopt.detect_rename;
1043        rev.diffopt.rename_limit = s->rename_limit >= 0 ? s->rename_limit : rev.diffopt.rename_limit;
1044        rev.diffopt.rename_score = s->rename_score >= 0 ? s->rename_score : rev.diffopt.rename_score;
1045        rev.diffopt.file = s->fp;
1046        rev.diffopt.close_file = 0;
1047        /*
1048         * If we're not going to stdout, then we definitely don't
1049         * want color, since we are going to the commit message
1050         * file (and even the "auto" setting won't work, since it
1051         * will have checked isatty on stdout). But we then do want
1052         * to insert the scissor line here to reliably remove the
1053         * diff before committing.
1054         */
1055        if (s->fp != stdout) {
1056                rev.diffopt.use_color = 0;
1057                wt_status_add_cut_line(s->fp);
1058        }
1059        if (s->verbose > 1 && s->committable) {
1060                /* print_updated() printed a header, so do we */
1061                if (s->fp != stdout)
1062                        wt_longstatus_print_trailer(s);
1063                status_printf_ln(s, c, _("Changes to be committed:"));
1064                rev.diffopt.a_prefix = "c/";
1065                rev.diffopt.b_prefix = "i/";
1066        } /* else use prefix as per user config */
1067        run_diff_index(&rev, 1);
1068        if (s->verbose > 1 &&
1069            wt_status_check_worktree_changes(s, &dirty_submodules)) {
1070                status_printf_ln(s, c,
1071                        "--------------------------------------------------");
1072                status_printf_ln(s, c, _("Changes not staged for commit:"));
1073                setup_work_tree();
1074                rev.diffopt.a_prefix = "i/";
1075                rev.diffopt.b_prefix = "w/";
1076                run_diff_files(&rev, 0);
1077        }
1078}
1079
1080static void wt_longstatus_print_tracking(struct wt_status *s)
1081{
1082        struct strbuf sb = STRBUF_INIT;
1083        const char *cp, *ep, *branch_name;
1084        struct branch *branch;
1085        char comment_line_string[3];
1086        int i;
1087
1088        assert(s->branch && !s->is_initial);
1089        if (!skip_prefix(s->branch, "refs/heads/", &branch_name))
1090                return;
1091        branch = branch_get(branch_name);
1092        if (!format_tracking_info(branch, &sb, s->ahead_behind_flags))
1093                return;
1094
1095        i = 0;
1096        if (s->display_comment_prefix) {
1097                comment_line_string[i++] = comment_line_char;
1098                comment_line_string[i++] = ' ';
1099        }
1100        comment_line_string[i] = '\0';
1101
1102        for (cp = sb.buf; (ep = strchr(cp, '\n')) != NULL; cp = ep + 1)
1103                color_fprintf_ln(s->fp, color(WT_STATUS_HEADER, s),
1104                                 "%s%.*s", comment_line_string,
1105                                 (int)(ep - cp), cp);
1106        if (s->display_comment_prefix)
1107                color_fprintf_ln(s->fp, color(WT_STATUS_HEADER, s), "%c",
1108                                 comment_line_char);
1109        else
1110                fputs("\n", s->fp);
1111        strbuf_release(&sb);
1112}
1113
1114static void show_merge_in_progress(struct wt_status *s,
1115                                   const char *color)
1116{
1117        if (has_unmerged(s)) {
1118                status_printf_ln(s, color, _("You have unmerged paths."));
1119                if (s->hints) {
1120                        status_printf_ln(s, color,
1121                                         _("  (fix conflicts and run \"git commit\")"));
1122                        status_printf_ln(s, color,
1123                                         _("  (use \"git merge --abort\" to abort the merge)"));
1124                }
1125        } else {
1126                status_printf_ln(s, color,
1127                        _("All conflicts fixed but you are still merging."));
1128                if (s->hints)
1129                        status_printf_ln(s, color,
1130                                _("  (use \"git commit\" to conclude merge)"));
1131        }
1132        wt_longstatus_print_trailer(s);
1133}
1134
1135static void show_am_in_progress(struct wt_status *s,
1136                                const char *color)
1137{
1138        status_printf_ln(s, color,
1139                _("You are in the middle of an am session."));
1140        if (s->state.am_empty_patch)
1141                status_printf_ln(s, color,
1142                        _("The current patch is empty."));
1143        if (s->hints) {
1144                if (!s->state.am_empty_patch)
1145                        status_printf_ln(s, color,
1146                                _("  (fix conflicts and then run \"git am --continue\")"));
1147                status_printf_ln(s, color,
1148                        _("  (use \"git am --skip\" to skip this patch)"));
1149                status_printf_ln(s, color,
1150                        _("  (use \"git am --abort\" to restore the original branch)"));
1151        }
1152        wt_longstatus_print_trailer(s);
1153}
1154
1155static char *read_line_from_git_path(const char *filename)
1156{
1157        struct strbuf buf = STRBUF_INIT;
1158        FILE *fp = fopen_or_warn(git_path("%s", filename), "r");
1159
1160        if (!fp) {
1161                strbuf_release(&buf);
1162                return NULL;
1163        }
1164        strbuf_getline_lf(&buf, fp);
1165        if (!fclose(fp)) {
1166                return strbuf_detach(&buf, NULL);
1167        } else {
1168                strbuf_release(&buf);
1169                return NULL;
1170        }
1171}
1172
1173static int split_commit_in_progress(struct wt_status *s)
1174{
1175        int split_in_progress = 0;
1176        char *head, *orig_head, *rebase_amend, *rebase_orig_head;
1177
1178        if ((!s->amend && !s->nowarn && !s->workdir_dirty) ||
1179            !s->branch || strcmp(s->branch, "HEAD"))
1180                return 0;
1181
1182        head = read_line_from_git_path("HEAD");
1183        orig_head = read_line_from_git_path("ORIG_HEAD");
1184        rebase_amend = read_line_from_git_path("rebase-merge/amend");
1185        rebase_orig_head = read_line_from_git_path("rebase-merge/orig-head");
1186
1187        if (!head || !orig_head || !rebase_amend || !rebase_orig_head)
1188                ; /* fall through, no split in progress */
1189        else if (!strcmp(rebase_amend, rebase_orig_head))
1190                split_in_progress = !!strcmp(head, rebase_amend);
1191        else if (strcmp(orig_head, rebase_orig_head))
1192                split_in_progress = 1;
1193
1194        free(head);
1195        free(orig_head);
1196        free(rebase_amend);
1197        free(rebase_orig_head);
1198
1199        return split_in_progress;
1200}
1201
1202/*
1203 * Turn
1204 * "pick d6a2f0303e897ec257dd0e0a39a5ccb709bc2047 some message"
1205 * into
1206 * "pick d6a2f03 some message"
1207 *
1208 * The function assumes that the line does not contain useless spaces
1209 * before or after the command.
1210 */
1211static void abbrev_sha1_in_line(struct strbuf *line)
1212{
1213        struct strbuf **split;
1214        int i;
1215
1216        if (starts_with(line->buf, "exec ") ||
1217            starts_with(line->buf, "x "))
1218                return;
1219
1220        split = strbuf_split_max(line, ' ', 3);
1221        if (split[0] && split[1]) {
1222                struct object_id oid;
1223
1224                /*
1225                 * strbuf_split_max left a space. Trim it and re-add
1226                 * it after abbreviation.
1227                 */
1228                strbuf_trim(split[1]);
1229                if (!get_oid(split[1]->buf, &oid)) {
1230                        strbuf_reset(split[1]);
1231                        strbuf_add_unique_abbrev(split[1], &oid,
1232                                                 DEFAULT_ABBREV);
1233                        strbuf_addch(split[1], ' ');
1234                        strbuf_reset(line);
1235                        for (i = 0; split[i]; i++)
1236                                strbuf_addbuf(line, split[i]);
1237                }
1238        }
1239        strbuf_list_free(split);
1240}
1241
1242static int read_rebase_todolist(const char *fname, struct string_list *lines)
1243{
1244        struct strbuf line = STRBUF_INIT;
1245        FILE *f = fopen(git_path("%s", fname), "r");
1246
1247        if (!f) {
1248                if (errno == ENOENT)
1249                        return -1;
1250                die_errno("Could not open file %s for reading",
1251                          git_path("%s", fname));
1252        }
1253        while (!strbuf_getline_lf(&line, f)) {
1254                if (line.len && line.buf[0] == comment_line_char)
1255                        continue;
1256                strbuf_trim(&line);
1257                if (!line.len)
1258                        continue;
1259                abbrev_sha1_in_line(&line);
1260                string_list_append(lines, line.buf);
1261        }
1262        fclose(f);
1263        strbuf_release(&line);
1264        return 0;
1265}
1266
1267static void show_rebase_information(struct wt_status *s,
1268                                    const char *color)
1269{
1270        if (s->state.rebase_interactive_in_progress) {
1271                int i;
1272                int nr_lines_to_show = 2;
1273
1274                struct string_list have_done = STRING_LIST_INIT_DUP;
1275                struct string_list yet_to_do = STRING_LIST_INIT_DUP;
1276
1277                read_rebase_todolist("rebase-merge/done", &have_done);
1278                if (read_rebase_todolist("rebase-merge/git-rebase-todo",
1279                                         &yet_to_do))
1280                        status_printf_ln(s, color,
1281                                _("git-rebase-todo is missing."));
1282                if (have_done.nr == 0)
1283                        status_printf_ln(s, color, _("No commands done."));
1284                else {
1285                        status_printf_ln(s, color,
1286                                Q_("Last command done (%d command done):",
1287                                        "Last commands done (%d commands done):",
1288                                        have_done.nr),
1289                                have_done.nr);
1290                        for (i = (have_done.nr > nr_lines_to_show)
1291                                ? have_done.nr - nr_lines_to_show : 0;
1292                                i < have_done.nr;
1293                                i++)
1294                                status_printf_ln(s, color, "   %s", have_done.items[i].string);
1295                        if (have_done.nr > nr_lines_to_show && s->hints)
1296                                status_printf_ln(s, color,
1297                                        _("  (see more in file %s)"), git_path("rebase-merge/done"));
1298                }
1299
1300                if (yet_to_do.nr == 0)
1301                        status_printf_ln(s, color,
1302                                         _("No commands remaining."));
1303                else {
1304                        status_printf_ln(s, color,
1305                                Q_("Next command to do (%d remaining command):",
1306                                        "Next commands to do (%d remaining commands):",
1307                                        yet_to_do.nr),
1308                                yet_to_do.nr);
1309                        for (i = 0; i < nr_lines_to_show && i < yet_to_do.nr; i++)
1310                                status_printf_ln(s, color, "   %s", yet_to_do.items[i].string);
1311                        if (s->hints)
1312                                status_printf_ln(s, color,
1313                                        _("  (use \"git rebase --edit-todo\" to view and edit)"));
1314                }
1315                string_list_clear(&yet_to_do, 0);
1316                string_list_clear(&have_done, 0);
1317        }
1318}
1319
1320static void print_rebase_state(struct wt_status *s,
1321                               const char *color)
1322{
1323        if (s->state.branch)
1324                status_printf_ln(s, color,
1325                                 _("You are currently rebasing branch '%s' on '%s'."),
1326                                 s->state.branch,
1327                                 s->state.onto);
1328        else
1329                status_printf_ln(s, color,
1330                                 _("You are currently rebasing."));
1331}
1332
1333static void show_rebase_in_progress(struct wt_status *s,
1334                                    const char *color)
1335{
1336        struct stat st;
1337
1338        show_rebase_information(s, color);
1339        if (has_unmerged(s)) {
1340                print_rebase_state(s, color);
1341                if (s->hints) {
1342                        status_printf_ln(s, color,
1343                                _("  (fix conflicts and then run \"git rebase --continue\")"));
1344                        status_printf_ln(s, color,
1345                                _("  (use \"git rebase --skip\" to skip this patch)"));
1346                        status_printf_ln(s, color,
1347                                _("  (use \"git rebase --abort\" to check out the original branch)"));
1348                }
1349        } else if (s->state.rebase_in_progress ||
1350                   !stat(git_path_merge_msg(s->repo), &st)) {
1351                print_rebase_state(s, color);
1352                if (s->hints)
1353                        status_printf_ln(s, color,
1354                                _("  (all conflicts fixed: run \"git rebase --continue\")"));
1355        } else if (split_commit_in_progress(s)) {
1356                if (s->state.branch)
1357                        status_printf_ln(s, color,
1358                                         _("You are currently splitting a commit while rebasing branch '%s' on '%s'."),
1359                                         s->state.branch,
1360                                         s->state.onto);
1361                else
1362                        status_printf_ln(s, color,
1363                                         _("You are currently splitting a commit during a rebase."));
1364                if (s->hints)
1365                        status_printf_ln(s, color,
1366                                _("  (Once your working directory is clean, run \"git rebase --continue\")"));
1367        } else {
1368                if (s->state.branch)
1369                        status_printf_ln(s, color,
1370                                         _("You are currently editing a commit while rebasing branch '%s' on '%s'."),
1371                                         s->state.branch,
1372                                         s->state.onto);
1373                else
1374                        status_printf_ln(s, color,
1375                                         _("You are currently editing a commit during a rebase."));
1376                if (s->hints && !s->amend) {
1377                        status_printf_ln(s, color,
1378                                _("  (use \"git commit --amend\" to amend the current commit)"));
1379                        status_printf_ln(s, color,
1380                                _("  (use \"git rebase --continue\" once you are satisfied with your changes)"));
1381                }
1382        }
1383        wt_longstatus_print_trailer(s);
1384}
1385
1386static void show_cherry_pick_in_progress(struct wt_status *s,
1387                                         const char *color)
1388{
1389        status_printf_ln(s, color, _("You are currently cherry-picking commit %s."),
1390                        find_unique_abbrev(&s->state.cherry_pick_head_oid, DEFAULT_ABBREV));
1391        if (s->hints) {
1392                if (has_unmerged(s))
1393                        status_printf_ln(s, color,
1394                                _("  (fix conflicts and run \"git cherry-pick --continue\")"));
1395                else
1396                        status_printf_ln(s, color,
1397                                _("  (all conflicts fixed: run \"git cherry-pick --continue\")"));
1398                status_printf_ln(s, color,
1399                        _("  (use \"git cherry-pick --abort\" to cancel the cherry-pick operation)"));
1400        }
1401        wt_longstatus_print_trailer(s);
1402}
1403
1404static void show_revert_in_progress(struct wt_status *s,
1405                                    const char *color)
1406{
1407        status_printf_ln(s, color, _("You are currently reverting commit %s."),
1408                         find_unique_abbrev(&s->state.revert_head_oid, DEFAULT_ABBREV));
1409        if (s->hints) {
1410                if (has_unmerged(s))
1411                        status_printf_ln(s, color,
1412                                _("  (fix conflicts and run \"git revert --continue\")"));
1413                else
1414                        status_printf_ln(s, color,
1415                                _("  (all conflicts fixed: run \"git revert --continue\")"));
1416                status_printf_ln(s, color,
1417                        _("  (use \"git revert --abort\" to cancel the revert operation)"));
1418        }
1419        wt_longstatus_print_trailer(s);
1420}
1421
1422static void show_bisect_in_progress(struct wt_status *s,
1423                                    const char *color)
1424{
1425        if (s->state.branch)
1426                status_printf_ln(s, color,
1427                                 _("You are currently bisecting, started from branch '%s'."),
1428                                 s->state.branch);
1429        else
1430                status_printf_ln(s, color,
1431                                 _("You are currently bisecting."));
1432        if (s->hints)
1433                status_printf_ln(s, color,
1434                        _("  (use \"git bisect reset\" to get back to the original branch)"));
1435        wt_longstatus_print_trailer(s);
1436}
1437
1438/*
1439 * Extract branch information from rebase/bisect
1440 */
1441static char *get_branch(const struct worktree *wt, const char *path)
1442{
1443        struct strbuf sb = STRBUF_INIT;
1444        struct object_id oid;
1445        const char *branch_name;
1446
1447        if (strbuf_read_file(&sb, worktree_git_path(wt, "%s", path), 0) <= 0)
1448                goto got_nothing;
1449
1450        while (sb.len && sb.buf[sb.len - 1] == '\n')
1451                strbuf_setlen(&sb, sb.len - 1);
1452        if (!sb.len)
1453                goto got_nothing;
1454        if (skip_prefix(sb.buf, "refs/heads/", &branch_name))
1455                strbuf_remove(&sb, 0, branch_name - sb.buf);
1456        else if (starts_with(sb.buf, "refs/"))
1457                ;
1458        else if (!get_oid_hex(sb.buf, &oid)) {
1459                strbuf_reset(&sb);
1460                strbuf_add_unique_abbrev(&sb, &oid, DEFAULT_ABBREV);
1461        } else if (!strcmp(sb.buf, "detached HEAD")) /* rebase */
1462                goto got_nothing;
1463        else                    /* bisect */
1464                ;
1465        return strbuf_detach(&sb, NULL);
1466
1467got_nothing:
1468        strbuf_release(&sb);
1469        return NULL;
1470}
1471
1472struct grab_1st_switch_cbdata {
1473        struct strbuf buf;
1474        struct object_id noid;
1475};
1476
1477static int grab_1st_switch(struct object_id *ooid, struct object_id *noid,
1478                           const char *email, timestamp_t timestamp, int tz,
1479                           const char *message, void *cb_data)
1480{
1481        struct grab_1st_switch_cbdata *cb = cb_data;
1482        const char *target = NULL, *end;
1483
1484        if (!skip_prefix(message, "checkout: moving from ", &message))
1485                return 0;
1486        target = strstr(message, " to ");
1487        if (!target)
1488                return 0;
1489        target += strlen(" to ");
1490        strbuf_reset(&cb->buf);
1491        oidcpy(&cb->noid, noid);
1492        end = strchrnul(target, '\n');
1493        strbuf_add(&cb->buf, target, end - target);
1494        if (!strcmp(cb->buf.buf, "HEAD")) {
1495                /* HEAD is relative. Resolve it to the right reflog entry. */
1496                strbuf_reset(&cb->buf);
1497                strbuf_add_unique_abbrev(&cb->buf, noid, DEFAULT_ABBREV);
1498        }
1499        return 1;
1500}
1501
1502static void wt_status_get_detached_from(struct repository *r,
1503                                        struct wt_status_state *state)
1504{
1505        struct grab_1st_switch_cbdata cb;
1506        struct commit *commit;
1507        struct object_id oid;
1508        char *ref = NULL;
1509
1510        strbuf_init(&cb.buf, 0);
1511        if (for_each_reflog_ent_reverse("HEAD", grab_1st_switch, &cb) <= 0) {
1512                strbuf_release(&cb.buf);
1513                return;
1514        }
1515
1516        if (dwim_ref(cb.buf.buf, cb.buf.len, &oid, &ref) == 1 &&
1517            /* sha1 is a commit? match without further lookup */
1518            (oideq(&cb.noid, &oid) ||
1519             /* perhaps sha1 is a tag, try to dereference to a commit */
1520             ((commit = lookup_commit_reference_gently(r, &oid, 1)) != NULL &&
1521              oideq(&cb.noid, &commit->object.oid)))) {
1522                const char *from = ref;
1523                if (!skip_prefix(from, "refs/tags/", &from))
1524                        skip_prefix(from, "refs/remotes/", &from);
1525                state->detached_from = xstrdup(from);
1526        } else
1527                state->detached_from =
1528                        xstrdup(find_unique_abbrev(&cb.noid, DEFAULT_ABBREV));
1529        oidcpy(&state->detached_oid, &cb.noid);
1530        state->detached_at = !get_oid("HEAD", &oid) &&
1531                             oideq(&oid, &state->detached_oid);
1532
1533        free(ref);
1534        strbuf_release(&cb.buf);
1535}
1536
1537int wt_status_check_rebase(const struct worktree *wt,
1538                           struct wt_status_state *state)
1539{
1540        struct stat st;
1541
1542        if (!stat(worktree_git_path(wt, "rebase-apply"), &st)) {
1543                if (!stat(worktree_git_path(wt, "rebase-apply/applying"), &st)) {
1544                        state->am_in_progress = 1;
1545                        if (!stat(worktree_git_path(wt, "rebase-apply/patch"), &st) && !st.st_size)
1546                                state->am_empty_patch = 1;
1547                } else {
1548                        state->rebase_in_progress = 1;
1549                        state->branch = get_branch(wt, "rebase-apply/head-name");
1550                        state->onto = get_branch(wt, "rebase-apply/onto");
1551                }
1552        } else if (!stat(worktree_git_path(wt, "rebase-merge"), &st)) {
1553                if (!stat(worktree_git_path(wt, "rebase-merge/interactive"), &st))
1554                        state->rebase_interactive_in_progress = 1;
1555                else
1556                        state->rebase_in_progress = 1;
1557                state->branch = get_branch(wt, "rebase-merge/head-name");
1558                state->onto = get_branch(wt, "rebase-merge/onto");
1559        } else
1560                return 0;
1561        return 1;
1562}
1563
1564int wt_status_check_bisect(const struct worktree *wt,
1565                           struct wt_status_state *state)
1566{
1567        struct stat st;
1568
1569        if (!stat(worktree_git_path(wt, "BISECT_LOG"), &st)) {
1570                state->bisect_in_progress = 1;
1571                state->branch = get_branch(wt, "BISECT_START");
1572                return 1;
1573        }
1574        return 0;
1575}
1576
1577void wt_status_get_state(struct repository *r,
1578                         struct wt_status_state *state,
1579                         int get_detached_from)
1580{
1581        struct stat st;
1582        struct object_id oid;
1583
1584        if (!stat(git_path_merge_head(r), &st)) {
1585                wt_status_check_rebase(NULL, state);
1586                state->merge_in_progress = 1;
1587        } else if (wt_status_check_rebase(NULL, state)) {
1588                ;               /* all set */
1589        } else if (!stat(git_path_cherry_pick_head(r), &st) &&
1590                        !get_oid("CHERRY_PICK_HEAD", &oid)) {
1591                state->cherry_pick_in_progress = 1;
1592                oidcpy(&state->cherry_pick_head_oid, &oid);
1593        }
1594        wt_status_check_bisect(NULL, state);
1595        if (!stat(git_path_revert_head(r), &st) &&
1596            !get_oid("REVERT_HEAD", &oid)) {
1597                state->revert_in_progress = 1;
1598                oidcpy(&state->revert_head_oid, &oid);
1599        }
1600
1601        if (get_detached_from)
1602                wt_status_get_detached_from(r, state);
1603}
1604
1605static void wt_longstatus_print_state(struct wt_status *s)
1606{
1607        const char *state_color = color(WT_STATUS_HEADER, s);
1608        struct wt_status_state *state = &s->state;
1609
1610        if (state->merge_in_progress) {
1611                if (state->rebase_interactive_in_progress) {
1612                        show_rebase_information(s, state_color);
1613                        fputs("\n", s->fp);
1614                }
1615                show_merge_in_progress(s, state_color);
1616        } else if (state->am_in_progress)
1617                show_am_in_progress(s, state_color);
1618        else if (state->rebase_in_progress || state->rebase_interactive_in_progress)
1619                show_rebase_in_progress(s, state_color);
1620        else if (state->cherry_pick_in_progress)
1621                show_cherry_pick_in_progress(s, state_color);
1622        else if (state->revert_in_progress)
1623                show_revert_in_progress(s, state_color);
1624        if (state->bisect_in_progress)
1625                show_bisect_in_progress(s, state_color);
1626}
1627
1628static void wt_longstatus_print(struct wt_status *s)
1629{
1630        const char *branch_color = color(WT_STATUS_ONBRANCH, s);
1631        const char *branch_status_color = color(WT_STATUS_HEADER, s);
1632
1633        if (s->branch) {
1634                const char *on_what = _("On branch ");
1635                const char *branch_name = s->branch;
1636                if (!strcmp(branch_name, "HEAD")) {
1637                        branch_status_color = color(WT_STATUS_NOBRANCH, s);
1638                        if (s->state.rebase_in_progress ||
1639                            s->state.rebase_interactive_in_progress) {
1640                                if (s->state.rebase_interactive_in_progress)
1641                                        on_what = _("interactive rebase in progress; onto ");
1642                                else
1643                                        on_what = _("rebase in progress; onto ");
1644                                branch_name = s->state.onto;
1645                        } else if (s->state.detached_from) {
1646                                branch_name = s->state.detached_from;
1647                                if (s->state.detached_at)
1648                                        on_what = _("HEAD detached at ");
1649                                else
1650                                        on_what = _("HEAD detached from ");
1651                        } else {
1652                                branch_name = "";
1653                                on_what = _("Not currently on any branch.");
1654                        }
1655                } else
1656                        skip_prefix(branch_name, "refs/heads/", &branch_name);
1657                status_printf(s, color(WT_STATUS_HEADER, s), "%s", "");
1658                status_printf_more(s, branch_status_color, "%s", on_what);
1659                status_printf_more(s, branch_color, "%s\n", branch_name);
1660                if (!s->is_initial)
1661                        wt_longstatus_print_tracking(s);
1662        }
1663
1664        wt_longstatus_print_state(s);
1665
1666        if (s->is_initial) {
1667                status_printf_ln(s, color(WT_STATUS_HEADER, s), "%s", "");
1668                status_printf_ln(s, color(WT_STATUS_HEADER, s),
1669                                 s->commit_template
1670                                 ? _("Initial commit")
1671                                 : _("No commits yet"));
1672                status_printf_ln(s, color(WT_STATUS_HEADER, s), "%s", "");
1673        }
1674
1675        wt_longstatus_print_updated(s);
1676        wt_longstatus_print_unmerged(s);
1677        wt_longstatus_print_changed(s);
1678        if (s->submodule_summary &&
1679            (!s->ignore_submodule_arg ||
1680             strcmp(s->ignore_submodule_arg, "all"))) {
1681                wt_longstatus_print_submodule_summary(s, 0);  /* staged */
1682                wt_longstatus_print_submodule_summary(s, 1);  /* unstaged */
1683        }
1684        if (s->show_untracked_files) {
1685                wt_longstatus_print_other(s, &s->untracked, _("Untracked files"), "add");
1686                if (s->show_ignored_mode)
1687                        wt_longstatus_print_other(s, &s->ignored, _("Ignored files"), "add -f");
1688                if (advice_status_u_option && 2000 < s->untracked_in_ms) {
1689                        status_printf_ln(s, GIT_COLOR_NORMAL, "%s", "");
1690                        status_printf_ln(s, GIT_COLOR_NORMAL,
1691                                         _("It took %.2f seconds to enumerate untracked files. 'status -uno'\n"
1692                                           "may speed it up, but you have to be careful not to forget to add\n"
1693                                           "new files yourself (see 'git help status')."),
1694                                         s->untracked_in_ms / 1000.0);
1695                }
1696        } else if (s->committable)
1697                status_printf_ln(s, GIT_COLOR_NORMAL, _("Untracked files not listed%s"),
1698                        s->hints
1699                        ? _(" (use -u option to show untracked files)") : "");
1700
1701        if (s->verbose)
1702                wt_longstatus_print_verbose(s);
1703        if (!s->committable) {
1704                if (s->amend)
1705                        status_printf_ln(s, GIT_COLOR_NORMAL, _("No changes"));
1706                else if (s->nowarn)
1707                        ; /* nothing */
1708                else if (s->workdir_dirty) {
1709                        if (s->hints)
1710                                printf(_("no changes added to commit "
1711                                         "(use \"git add\" and/or \"git commit -a\")\n"));
1712                        else
1713                                printf(_("no changes added to commit\n"));
1714                } else if (s->untracked.nr) {
1715                        if (s->hints)
1716                                printf(_("nothing added to commit but untracked files "
1717                                         "present (use \"git add\" to track)\n"));
1718                        else
1719                                printf(_("nothing added to commit but untracked files present\n"));
1720                } else if (s->is_initial) {
1721                        if (s->hints)
1722                                printf(_("nothing to commit (create/copy files "
1723                                         "and use \"git add\" to track)\n"));
1724                        else
1725                                printf(_("nothing to commit\n"));
1726                } else if (!s->show_untracked_files) {
1727                        if (s->hints)
1728                                printf(_("nothing to commit (use -u to show untracked files)\n"));
1729                        else
1730                                printf(_("nothing to commit\n"));
1731                } else
1732                        printf(_("nothing to commit, working tree clean\n"));
1733        }
1734        if(s->show_stash)
1735                wt_longstatus_print_stash_summary(s);
1736}
1737
1738static void wt_shortstatus_unmerged(struct string_list_item *it,
1739                           struct wt_status *s)
1740{
1741        struct wt_status_change_data *d = it->util;
1742        const char *how = "??";
1743
1744        switch (d->stagemask) {
1745        case 1: how = "DD"; break; /* both deleted */
1746        case 2: how = "AU"; break; /* added by us */
1747        case 3: how = "UD"; break; /* deleted by them */
1748        case 4: how = "UA"; break; /* added by them */
1749        case 5: how = "DU"; break; /* deleted by us */
1750        case 6: how = "AA"; break; /* both added */
1751        case 7: how = "UU"; break; /* both modified */
1752        }
1753        color_fprintf(s->fp, color(WT_STATUS_UNMERGED, s), "%s", how);
1754        if (s->null_termination) {
1755                fprintf(stdout, " %s%c", it->string, 0);
1756        } else {
1757                struct strbuf onebuf = STRBUF_INIT;
1758                const char *one;
1759                one = quote_path(it->string, s->prefix, &onebuf);
1760                printf(" %s\n", one);
1761                strbuf_release(&onebuf);
1762        }
1763}
1764
1765static void wt_shortstatus_status(struct string_list_item *it,
1766                         struct wt_status *s)
1767{
1768        struct wt_status_change_data *d = it->util;
1769
1770        if (d->index_status)
1771                color_fprintf(s->fp, color(WT_STATUS_UPDATED, s), "%c", d->index_status);
1772        else
1773                putchar(' ');
1774        if (d->worktree_status)
1775                color_fprintf(s->fp, color(WT_STATUS_CHANGED, s), "%c", d->worktree_status);
1776        else
1777                putchar(' ');
1778        putchar(' ');
1779        if (s->null_termination) {
1780                fprintf(stdout, "%s%c", it->string, 0);
1781                if (d->rename_source)
1782                        fprintf(stdout, "%s%c", d->rename_source, 0);
1783        } else {
1784                struct strbuf onebuf = STRBUF_INIT;
1785                const char *one;
1786
1787                if (d->rename_source) {
1788                        one = quote_path(d->rename_source, s->prefix, &onebuf);
1789                        if (*one != '"' && strchr(one, ' ') != NULL) {
1790                                putchar('"');
1791                                strbuf_addch(&onebuf, '"');
1792                                one = onebuf.buf;
1793                        }
1794                        printf("%s -> ", one);
1795                        strbuf_release(&onebuf);
1796                }
1797                one = quote_path(it->string, s->prefix, &onebuf);
1798                if (*one != '"' && strchr(one, ' ') != NULL) {
1799                        putchar('"');
1800                        strbuf_addch(&onebuf, '"');
1801                        one = onebuf.buf;
1802                }
1803                printf("%s\n", one);
1804                strbuf_release(&onebuf);
1805        }
1806}
1807
1808static void wt_shortstatus_other(struct string_list_item *it,
1809                                 struct wt_status *s, const char *sign)
1810{
1811        if (s->null_termination) {
1812                fprintf(stdout, "%s %s%c", sign, it->string, 0);
1813        } else {
1814                struct strbuf onebuf = STRBUF_INIT;
1815                const char *one;
1816                one = quote_path(it->string, s->prefix, &onebuf);
1817                color_fprintf(s->fp, color(WT_STATUS_UNTRACKED, s), "%s", sign);
1818                printf(" %s\n", one);
1819                strbuf_release(&onebuf);
1820        }
1821}
1822
1823static void wt_shortstatus_print_tracking(struct wt_status *s)
1824{
1825        struct branch *branch;
1826        const char *header_color = color(WT_STATUS_HEADER, s);
1827        const char *branch_color_local = color(WT_STATUS_LOCAL_BRANCH, s);
1828        const char *branch_color_remote = color(WT_STATUS_REMOTE_BRANCH, s);
1829
1830        const char *base;
1831        char *short_base;
1832        const char *branch_name;
1833        int num_ours, num_theirs, sti;
1834        int upstream_is_gone = 0;
1835
1836        color_fprintf(s->fp, color(WT_STATUS_HEADER, s), "## ");
1837
1838        if (!s->branch)
1839                return;
1840        branch_name = s->branch;
1841
1842#define LABEL(string) (s->no_gettext ? (string) : _(string))
1843
1844        if (s->is_initial)
1845                color_fprintf(s->fp, header_color, LABEL(N_("No commits yet on ")));
1846
1847        if (!strcmp(s->branch, "HEAD")) {
1848                color_fprintf(s->fp, color(WT_STATUS_NOBRANCH, s), "%s",
1849                              LABEL(N_("HEAD (no branch)")));
1850                goto conclude;
1851        }
1852
1853        skip_prefix(branch_name, "refs/heads/", &branch_name);
1854
1855        branch = branch_get(branch_name);
1856
1857        color_fprintf(s->fp, branch_color_local, "%s", branch_name);
1858
1859        sti = stat_tracking_info(branch, &num_ours, &num_theirs, &base,
1860                                 0, s->ahead_behind_flags);
1861        if (sti < 0) {
1862                if (!base)
1863                        goto conclude;
1864
1865                upstream_is_gone = 1;
1866        }
1867
1868        short_base = shorten_unambiguous_ref(base, 0);
1869        color_fprintf(s->fp, header_color, "...");
1870        color_fprintf(s->fp, branch_color_remote, "%s", short_base);
1871        free(short_base);
1872
1873        if (!upstream_is_gone && !sti)
1874                goto conclude;
1875
1876        color_fprintf(s->fp, header_color, " [");
1877        if (upstream_is_gone) {
1878                color_fprintf(s->fp, header_color, LABEL(N_("gone")));
1879        } else if (s->ahead_behind_flags == AHEAD_BEHIND_QUICK) {
1880                color_fprintf(s->fp, header_color, LABEL(N_("different")));
1881        } else if (!num_ours) {
1882                color_fprintf(s->fp, header_color, LABEL(N_("behind ")));
1883                color_fprintf(s->fp, branch_color_remote, "%d", num_theirs);
1884        } else if (!num_theirs) {
1885                color_fprintf(s->fp, header_color, LABEL(N_("ahead ")));
1886                color_fprintf(s->fp, branch_color_local, "%d", num_ours);
1887        } else {
1888                color_fprintf(s->fp, header_color, LABEL(N_("ahead ")));
1889                color_fprintf(s->fp, branch_color_local, "%d", num_ours);
1890                color_fprintf(s->fp, header_color, ", %s", LABEL(N_("behind ")));
1891                color_fprintf(s->fp, branch_color_remote, "%d", num_theirs);
1892        }
1893
1894        color_fprintf(s->fp, header_color, "]");
1895 conclude:
1896        fputc(s->null_termination ? '\0' : '\n', s->fp);
1897}
1898
1899static void wt_shortstatus_print(struct wt_status *s)
1900{
1901        struct string_list_item *it;
1902
1903        if (s->show_branch)
1904                wt_shortstatus_print_tracking(s);
1905
1906        for_each_string_list_item(it, &s->change) {
1907                struct wt_status_change_data *d = it->util;
1908
1909                if (d->stagemask)
1910                        wt_shortstatus_unmerged(it, s);
1911                else
1912                        wt_shortstatus_status(it, s);
1913        }
1914        for_each_string_list_item(it, &s->untracked)
1915                wt_shortstatus_other(it, s, "??");
1916
1917        for_each_string_list_item(it, &s->ignored)
1918                wt_shortstatus_other(it, s, "!!");
1919}
1920
1921static void wt_porcelain_print(struct wt_status *s)
1922{
1923        s->use_color = 0;
1924        s->relative_paths = 0;
1925        s->prefix = NULL;
1926        s->no_gettext = 1;
1927        wt_shortstatus_print(s);
1928}
1929
1930/*
1931 * Print branch information for porcelain v2 output.  These lines
1932 * are printed when the '--branch' parameter is given.
1933 *
1934 *    # branch.oid <commit><eol>
1935 *    # branch.head <head><eol>
1936 *   [# branch.upstream <upstream><eol>
1937 *   [# branch.ab +<ahead> -<behind><eol>]]
1938 *
1939 *      <commit> ::= the current commit hash or the the literal
1940 *                   "(initial)" to indicate an initialized repo
1941 *                   with no commits.
1942 *
1943 *        <head> ::= <branch_name> the current branch name or
1944 *                   "(detached)" literal when detached head or
1945 *                   "(unknown)" when something is wrong.
1946 *
1947 *    <upstream> ::= the upstream branch name, when set.
1948 *
1949 *       <ahead> ::= integer ahead value or '?'.
1950 *
1951 *      <behind> ::= integer behind value or '?'.
1952 *
1953 * The end-of-line is defined by the -z flag.
1954 *
1955 *                 <eol> ::= NUL when -z,
1956 *                           LF when NOT -z.
1957 *
1958 * When an upstream is set and present, the 'branch.ab' line will
1959 * be printed with the ahead/behind counts for the branch and the
1960 * upstream.  When AHEAD_BEHIND_QUICK is requested and the branches
1961 * are different, '?' will be substituted for the actual count.
1962 */
1963static void wt_porcelain_v2_print_tracking(struct wt_status *s)
1964{
1965        struct branch *branch;
1966        const char *base;
1967        const char *branch_name;
1968        int ab_info, nr_ahead, nr_behind;
1969        char eol = s->null_termination ? '\0' : '\n';
1970
1971        fprintf(s->fp, "# branch.oid %s%c",
1972                        (s->is_initial ? "(initial)" : sha1_to_hex(s->sha1_commit)),
1973                        eol);
1974
1975        if (!s->branch)
1976                fprintf(s->fp, "# branch.head %s%c", "(unknown)", eol);
1977        else {
1978                if (!strcmp(s->branch, "HEAD")) {
1979                        fprintf(s->fp, "# branch.head %s%c", "(detached)", eol);
1980
1981                        if (s->state.rebase_in_progress ||
1982                            s->state.rebase_interactive_in_progress)
1983                                branch_name = s->state.onto;
1984                        else if (s->state.detached_from)
1985                                branch_name = s->state.detached_from;
1986                        else
1987                                branch_name = "";
1988                } else {
1989                        branch_name = NULL;
1990                        skip_prefix(s->branch, "refs/heads/", &branch_name);
1991
1992                        fprintf(s->fp, "# branch.head %s%c", branch_name, eol);
1993                }
1994
1995                /* Lookup stats on the upstream tracking branch, if set. */
1996                branch = branch_get(branch_name);
1997                base = NULL;
1998                ab_info = stat_tracking_info(branch, &nr_ahead, &nr_behind,
1999                                             &base, 0, s->ahead_behind_flags);
2000                if (base) {
2001                        base = shorten_unambiguous_ref(base, 0);
2002                        fprintf(s->fp, "# branch.upstream %s%c", base, eol);
2003                        free((char *)base);
2004
2005                        if (ab_info > 0) {
2006                                /* different */
2007                                if (nr_ahead || nr_behind)
2008                                        fprintf(s->fp, "# branch.ab +%d -%d%c",
2009                                                nr_ahead, nr_behind, eol);
2010                                else
2011                                        fprintf(s->fp, "# branch.ab +? -?%c",
2012                                                eol);
2013                        } else if (!ab_info) {
2014                                /* same */
2015                                fprintf(s->fp, "# branch.ab +0 -0%c", eol);
2016                        }
2017                }
2018        }
2019}
2020
2021/*
2022 * Convert various submodule status values into a
2023 * fixed-length string of characters in the buffer provided.
2024 */
2025static void wt_porcelain_v2_submodule_state(
2026        struct wt_status_change_data *d,
2027        char sub[5])
2028{
2029        if (S_ISGITLINK(d->mode_head) ||
2030                S_ISGITLINK(d->mode_index) ||
2031                S_ISGITLINK(d->mode_worktree)) {
2032                sub[0] = 'S';
2033                sub[1] = d->new_submodule_commits ? 'C' : '.';
2034                sub[2] = (d->dirty_submodule & DIRTY_SUBMODULE_MODIFIED) ? 'M' : '.';
2035                sub[3] = (d->dirty_submodule & DIRTY_SUBMODULE_UNTRACKED) ? 'U' : '.';
2036        } else {
2037                sub[0] = 'N';
2038                sub[1] = '.';
2039                sub[2] = '.';
2040                sub[3] = '.';
2041        }
2042        sub[4] = 0;
2043}
2044
2045/*
2046 * Fix-up changed entries before we print them.
2047 */
2048static void wt_porcelain_v2_fix_up_changed(
2049        struct string_list_item *it,
2050        struct wt_status *s)
2051{
2052        struct wt_status_change_data *d = it->util;
2053
2054        if (!d->index_status) {
2055                /*
2056                 * This entry is unchanged in the index (relative to the head).
2057                 * Therefore, the collect_updated_cb was never called for this
2058                 * entry (during the head-vs-index scan) and so the head column
2059                 * fields were never set.
2060                 *
2061                 * We must have data for the index column (from the
2062                 * index-vs-worktree scan (otherwise, this entry should not be
2063                 * in the list of changes)).
2064                 *
2065                 * Copy index column fields to the head column, so that our
2066                 * output looks complete.
2067                 */
2068                assert(d->mode_head == 0);
2069                d->mode_head = d->mode_index;
2070                oidcpy(&d->oid_head, &d->oid_index);
2071        }
2072
2073        if (!d->worktree_status) {
2074                /*
2075                 * This entry is unchanged in the worktree (relative to the index).
2076                 * Therefore, the collect_changed_cb was never called for this entry
2077                 * (during the index-vs-worktree scan) and so the worktree column
2078                 * fields were never set.
2079                 *
2080                 * We must have data for the index column (from the head-vs-index
2081                 * scan).
2082                 *
2083                 * Copy the index column fields to the worktree column so that
2084                 * our output looks complete.
2085                 *
2086                 * Note that we only have a mode field in the worktree column
2087                 * because the scan code tries really hard to not have to compute it.
2088                 */
2089                assert(d->mode_worktree == 0);
2090                d->mode_worktree = d->mode_index;
2091        }
2092}
2093
2094/*
2095 * Print porcelain v2 info for tracked entries with changes.
2096 */
2097static void wt_porcelain_v2_print_changed_entry(
2098        struct string_list_item *it,
2099        struct wt_status *s)
2100{
2101        struct wt_status_change_data *d = it->util;
2102        struct strbuf buf = STRBUF_INIT;
2103        struct strbuf buf_from = STRBUF_INIT;
2104        const char *path = NULL;
2105        const char *path_from = NULL;
2106        char key[3];
2107        char submodule_token[5];
2108        char sep_char, eol_char;
2109
2110        wt_porcelain_v2_fix_up_changed(it, s);
2111        wt_porcelain_v2_submodule_state(d, submodule_token);
2112
2113        key[0] = d->index_status ? d->index_status : '.';
2114        key[1] = d->worktree_status ? d->worktree_status : '.';
2115        key[2] = 0;
2116
2117        if (s->null_termination) {
2118                /*
2119                 * In -z mode, we DO NOT C-quote pathnames.  Current path is ALWAYS first.
2120                 * A single NUL character separates them.
2121                 */
2122                sep_char = '\0';
2123                eol_char = '\0';
2124                path = it->string;
2125                path_from = d->rename_source;
2126        } else {
2127                /*
2128                 * Path(s) are C-quoted if necessary. Current path is ALWAYS first.
2129                 * The source path is only present when necessary.
2130                 * A single TAB separates them (because paths can contain spaces
2131                 * which are not escaped and C-quoting does escape TAB characters).
2132                 */
2133                sep_char = '\t';
2134                eol_char = '\n';
2135                path = quote_path(it->string, s->prefix, &buf);
2136                if (d->rename_source)
2137                        path_from = quote_path(d->rename_source, s->prefix, &buf_from);
2138        }
2139
2140        if (path_from)
2141                fprintf(s->fp, "2 %s %s %06o %06o %06o %s %s %c%d %s%c%s%c",
2142                                key, submodule_token,
2143                                d->mode_head, d->mode_index, d->mode_worktree,
2144                                oid_to_hex(&d->oid_head), oid_to_hex(&d->oid_index),
2145                                d->rename_status, d->rename_score,
2146                                path, sep_char, path_from, eol_char);
2147        else
2148                fprintf(s->fp, "1 %s %s %06o %06o %06o %s %s %s%c",
2149                                key, submodule_token,
2150                                d->mode_head, d->mode_index, d->mode_worktree,
2151                                oid_to_hex(&d->oid_head), oid_to_hex(&d->oid_index),
2152                                path, eol_char);
2153
2154        strbuf_release(&buf);
2155        strbuf_release(&buf_from);
2156}
2157
2158/*
2159 * Print porcelain v2 status info for unmerged entries.
2160 */
2161static void wt_porcelain_v2_print_unmerged_entry(
2162        struct string_list_item *it,
2163        struct wt_status *s)
2164{
2165        struct wt_status_change_data *d = it->util;
2166        struct index_state *istate = s->repo->index;
2167        const struct cache_entry *ce;
2168        struct strbuf buf_index = STRBUF_INIT;
2169        const char *path_index = NULL;
2170        int pos, stage, sum;
2171        struct {
2172                int mode;
2173                struct object_id oid;
2174        } stages[3];
2175        char *key;
2176        char submodule_token[5];
2177        char unmerged_prefix = 'u';
2178        char eol_char = s->null_termination ? '\0' : '\n';
2179
2180        wt_porcelain_v2_submodule_state(d, submodule_token);
2181
2182        switch (d->stagemask) {
2183        case 1: key = "DD"; break; /* both deleted */
2184        case 2: key = "AU"; break; /* added by us */
2185        case 3: key = "UD"; break; /* deleted by them */
2186        case 4: key = "UA"; break; /* added by them */
2187        case 5: key = "DU"; break; /* deleted by us */
2188        case 6: key = "AA"; break; /* both added */
2189        case 7: key = "UU"; break; /* both modified */
2190        default:
2191                BUG("unhandled unmerged status %x", d->stagemask);
2192        }
2193
2194        /*
2195         * Disregard d.aux.porcelain_v2 data that we accumulated
2196         * for the head and index columns during the scans and
2197         * replace with the actual stage data.
2198         *
2199         * Note that this is a last-one-wins for each the individual
2200         * stage [123] columns in the event of multiple cache entries
2201         * for same stage.
2202         */
2203        memset(stages, 0, sizeof(stages));
2204        sum = 0;
2205        pos = index_name_pos(istate, it->string, strlen(it->string));
2206        assert(pos < 0);
2207        pos = -pos-1;
2208        while (pos < istate->cache_nr) {
2209                ce = istate->cache[pos++];
2210                stage = ce_stage(ce);
2211                if (strcmp(ce->name, it->string) || !stage)
2212                        break;
2213                stages[stage - 1].mode = ce->ce_mode;
2214                oidcpy(&stages[stage - 1].oid, &ce->oid);
2215                sum |= (1 << (stage - 1));
2216        }
2217        if (sum != d->stagemask)
2218                BUG("observed stagemask 0x%x != expected stagemask 0x%x", sum, d->stagemask);
2219
2220        if (s->null_termination)
2221                path_index = it->string;
2222        else
2223                path_index = quote_path(it->string, s->prefix, &buf_index);
2224
2225        fprintf(s->fp, "%c %s %s %06o %06o %06o %06o %s %s %s %s%c",
2226                        unmerged_prefix, key, submodule_token,
2227                        stages[0].mode, /* stage 1 */
2228                        stages[1].mode, /* stage 2 */
2229                        stages[2].mode, /* stage 3 */
2230                        d->mode_worktree,
2231                        oid_to_hex(&stages[0].oid), /* stage 1 */
2232                        oid_to_hex(&stages[1].oid), /* stage 2 */
2233                        oid_to_hex(&stages[2].oid), /* stage 3 */
2234                        path_index,
2235                        eol_char);
2236
2237        strbuf_release(&buf_index);
2238}
2239
2240/*
2241 * Print porcelain V2 status info for untracked and ignored entries.
2242 */
2243static void wt_porcelain_v2_print_other(
2244        struct string_list_item *it,
2245        struct wt_status *s,
2246        char prefix)
2247{
2248        struct strbuf buf = STRBUF_INIT;
2249        const char *path;
2250        char eol_char;
2251
2252        if (s->null_termination) {
2253                path = it->string;
2254                eol_char = '\0';
2255        } else {
2256                path = quote_path(it->string, s->prefix, &buf);
2257                eol_char = '\n';
2258        }
2259
2260        fprintf(s->fp, "%c %s%c", prefix, path, eol_char);
2261
2262        strbuf_release(&buf);
2263}
2264
2265/*
2266 * Print porcelain V2 status.
2267 *
2268 * [<v2_branch>]
2269 * [<v2_changed_items>]*
2270 * [<v2_unmerged_items>]*
2271 * [<v2_untracked_items>]*
2272 * [<v2_ignored_items>]*
2273 *
2274 */
2275static void wt_porcelain_v2_print(struct wt_status *s)
2276{
2277        struct wt_status_change_data *d;
2278        struct string_list_item *it;
2279        int i;
2280
2281        if (s->show_branch)
2282                wt_porcelain_v2_print_tracking(s);
2283
2284        for (i = 0; i < s->change.nr; i++) {
2285                it = &(s->change.items[i]);
2286                d = it->util;
2287                if (!d->stagemask)
2288                        wt_porcelain_v2_print_changed_entry(it, s);
2289        }
2290
2291        for (i = 0; i < s->change.nr; i++) {
2292                it = &(s->change.items[i]);
2293                d = it->util;
2294                if (d->stagemask)
2295                        wt_porcelain_v2_print_unmerged_entry(it, s);
2296        }
2297
2298        for (i = 0; i < s->untracked.nr; i++) {
2299                it = &(s->untracked.items[i]);
2300                wt_porcelain_v2_print_other(it, s, '?');
2301        }
2302
2303        for (i = 0; i < s->ignored.nr; i++) {
2304                it = &(s->ignored.items[i]);
2305                wt_porcelain_v2_print_other(it, s, '!');
2306        }
2307}
2308
2309void wt_status_print(struct wt_status *s)
2310{
2311        trace2_data_intmax("status", s->repo, "count/changed", s->change.nr);
2312        trace2_data_intmax("status", s->repo, "count/untracked",
2313                           s->untracked.nr);
2314        trace2_data_intmax("status", s->repo, "count/ignored", s->ignored.nr);
2315
2316        trace2_region_enter("status", "print", s->repo);
2317
2318        switch (s->status_format) {
2319        case STATUS_FORMAT_SHORT:
2320                wt_shortstatus_print(s);
2321                break;
2322        case STATUS_FORMAT_PORCELAIN:
2323                wt_porcelain_print(s);
2324                break;
2325        case STATUS_FORMAT_PORCELAIN_V2:
2326                wt_porcelain_v2_print(s);
2327                break;
2328        case STATUS_FORMAT_UNSPECIFIED:
2329                BUG("finalize_deferred_config() should have been called");
2330                break;
2331        case STATUS_FORMAT_NONE:
2332        case STATUS_FORMAT_LONG:
2333                wt_longstatus_print(s);
2334                break;
2335        }
2336
2337        trace2_region_leave("status", "print", s->repo);
2338}
2339
2340/**
2341 * Returns 1 if there are unstaged changes, 0 otherwise.
2342 */
2343int has_unstaged_changes(struct repository *r, int ignore_submodules)
2344{
2345        struct rev_info rev_info;
2346        int result;
2347
2348        repo_init_revisions(r, &rev_info, NULL);
2349        if (ignore_submodules) {
2350                rev_info.diffopt.flags.ignore_submodules = 1;
2351                rev_info.diffopt.flags.override_submodule_config = 1;
2352        }
2353        rev_info.diffopt.flags.quick = 1;
2354        diff_setup_done(&rev_info.diffopt);
2355        result = run_diff_files(&rev_info, 0);
2356        return diff_result_code(&rev_info.diffopt, result);
2357}
2358
2359/**
2360 * Returns 1 if there are uncommitted changes, 0 otherwise.
2361 */
2362int has_uncommitted_changes(struct repository *r,
2363                            int ignore_submodules)
2364{
2365        struct rev_info rev_info;
2366        int result;
2367
2368        if (is_index_unborn(r->index))
2369                return 0;
2370
2371        repo_init_revisions(r, &rev_info, NULL);
2372        if (ignore_submodules)
2373                rev_info.diffopt.flags.ignore_submodules = 1;
2374        rev_info.diffopt.flags.quick = 1;
2375
2376        add_head_to_pending(&rev_info);
2377        if (!rev_info.pending.nr) {
2378                /*
2379                 * We have no head (or it's corrupt); use the empty tree,
2380                 * which will complain if the index is non-empty.
2381                 */
2382                struct tree *tree = lookup_tree(r, the_hash_algo->empty_tree);
2383                add_pending_object(&rev_info, &tree->object, "");
2384        }
2385
2386        diff_setup_done(&rev_info.diffopt);
2387        result = run_diff_index(&rev_info, 1);
2388        return diff_result_code(&rev_info.diffopt, result);
2389}
2390
2391/**
2392 * If the work tree has unstaged or uncommitted changes, dies with the
2393 * appropriate message.
2394 */
2395int require_clean_work_tree(struct repository *r,
2396                            const char *action,
2397                            const char *hint,
2398                            int ignore_submodules,
2399                            int gently)
2400{
2401        struct lock_file lock_file = LOCK_INIT;
2402        int err = 0, fd;
2403
2404        fd = repo_hold_locked_index(r, &lock_file, 0);
2405        refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
2406        if (0 <= fd)
2407                repo_update_index_if_able(r, &lock_file);
2408        rollback_lock_file(&lock_file);
2409
2410        if (has_unstaged_changes(r, ignore_submodules)) {
2411                /* TRANSLATORS: the action is e.g. "pull with rebase" */
2412                error(_("cannot %s: You have unstaged changes."), _(action));
2413                err = 1;
2414        }
2415
2416        if (has_uncommitted_changes(r, ignore_submodules)) {
2417                if (err)
2418                        error(_("additionally, your index contains uncommitted changes."));
2419                else
2420                        error(_("cannot %s: Your index contains uncommitted changes."),
2421                              _(action));
2422                err = 1;
2423        }
2424
2425        if (err) {
2426                if (hint)
2427                        error("%s", hint);
2428                if (!gently)
2429                        exit(128);
2430        }
2431
2432        return err;
2433}