OSDN Git Service

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