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