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