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