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