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