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