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