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