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