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