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