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