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