graph: handle line padding in `graph_next_line()`
[git] / graph.c
1 #include "cache.h"
2 #include "config.h"
3 #include "commit.h"
4 #include "color.h"
5 #include "graph.h"
6 #include "revision.h"
7 #include "argv-array.h"
8
9 /* Internal API */
10
11 /*
12  * Output a padding line in the graph.
13  * This is similar to graph_next_line().  However, it is guaranteed to
14  * never print the current commit line.  Instead, if the commit line is
15  * next, it will simply output a line of vertical padding, extending the
16  * branch lines downwards, but leaving them otherwise unchanged.
17  */
18 static void graph_padding_line(struct git_graph *graph, struct strbuf *sb);
19
20 /*
21  * Print a strbuf.  If the graph is non-NULL, all lines but the first will be
22  * prefixed with the graph output.
23  *
24  * If the strbuf ends with a newline, the output will end after this
25  * newline.  A new graph line will not be printed after the final newline.
26  * If the strbuf is empty, no output will be printed.
27  *
28  * Since the first line will not include the graph output, the caller is
29  * responsible for printing this line's graph (perhaps via
30  * graph_show_commit() or graph_show_oneline()) before calling
31  * graph_show_strbuf().
32  *
33  * Note that unlike some other graph display functions, you must pass the file
34  * handle directly. It is assumed that this is the same file handle as the
35  * file specified by the graph diff options. This is necessary so that
36  * graph_show_strbuf can be called even with a NULL graph.
37  */
38 static void graph_show_strbuf(struct git_graph *graph,
39                               FILE *file,
40                               struct strbuf const *sb);
41
42 /*
43  * TODO:
44  * - Limit the number of columns, similar to the way gitk does.
45  *   If we reach more than a specified number of columns, omit
46  *   sections of some columns.
47  */
48
49 struct column {
50         /*
51          * The parent commit of this column.
52          */
53         struct commit *commit;
54         /*
55          * The color to (optionally) print this column in.  This is an
56          * index into column_colors.
57          */
58         unsigned short color;
59 };
60
61 enum graph_state {
62         GRAPH_PADDING,
63         GRAPH_SKIP,
64         GRAPH_PRE_COMMIT,
65         GRAPH_COMMIT,
66         GRAPH_POST_MERGE,
67         GRAPH_COLLAPSING
68 };
69
70 static void graph_show_line_prefix(const struct diff_options *diffopt)
71 {
72         if (!diffopt || !diffopt->line_prefix)
73                 return;
74
75         fwrite(diffopt->line_prefix,
76                sizeof(char),
77                diffopt->line_prefix_length,
78                diffopt->file);
79 }
80
81 static const char **column_colors;
82 static unsigned short column_colors_max;
83
84 static void parse_graph_colors_config(struct argv_array *colors, const char *string)
85 {
86         const char *end, *start;
87
88         start = string;
89         end = string + strlen(string);
90         while (start < end) {
91                 const char *comma = strchrnul(start, ',');
92                 char color[COLOR_MAXLEN];
93
94                 if (!color_parse_mem(start, comma - start, color))
95                         argv_array_push(colors, color);
96                 else
97                         warning(_("ignore invalid color '%.*s' in log.graphColors"),
98                                 (int)(comma - start), start);
99                 start = comma + 1;
100         }
101         argv_array_push(colors, GIT_COLOR_RESET);
102 }
103
104 void graph_set_column_colors(const char **colors, unsigned short colors_max)
105 {
106         column_colors = colors;
107         column_colors_max = colors_max;
108 }
109
110 static const char *column_get_color_code(unsigned short color)
111 {
112         return column_colors[color];
113 }
114
115 struct graph_line {
116         struct strbuf *buf;
117         size_t width;
118 };
119
120 static inline void graph_line_addch(struct graph_line *line, int c)
121 {
122         strbuf_addch(line->buf, c);
123         line->width++;
124 }
125
126 static inline void graph_line_addchars(struct graph_line *line, int c, size_t n)
127 {
128         strbuf_addchars(line->buf, c, n);
129         line->width += n;
130 }
131
132 static inline void graph_line_addstr(struct graph_line *line, const char *s)
133 {
134         strbuf_addstr(line->buf, s);
135         line->width += strlen(s);
136 }
137
138 static inline void graph_line_addcolor(struct graph_line *line, unsigned short color)
139 {
140         strbuf_addstr(line->buf, column_get_color_code(color));
141 }
142
143 static void graph_line_write_column(struct graph_line *line, const struct column *c,
144                                     char col_char)
145 {
146         if (c->color < column_colors_max)
147                 graph_line_addcolor(line, c->color);
148         graph_line_addch(line, col_char);
149         if (c->color < column_colors_max)
150                 graph_line_addcolor(line, column_colors_max);
151 }
152
153 struct git_graph {
154         /*
155          * The commit currently being processed
156          */
157         struct commit *commit;
158         /* The rev-info used for the current traversal */
159         struct rev_info *revs;
160         /*
161          * The number of interesting parents that this commit has.
162          *
163          * Note that this is not the same as the actual number of parents.
164          * This count excludes parents that won't be printed in the graph
165          * output, as determined by graph_is_interesting().
166          */
167         int num_parents;
168         /*
169          * The width of the graph output for this commit.
170          * All rows for this commit are padded to this width, so that
171          * messages printed after the graph output are aligned.
172          */
173         int width;
174         /*
175          * The next expansion row to print
176          * when state is GRAPH_PRE_COMMIT
177          */
178         int expansion_row;
179         /*
180          * The current output state.
181          * This tells us what kind of line graph_next_line() should output.
182          */
183         enum graph_state state;
184         /*
185          * The output state for the previous line of output.
186          * This is primarily used to determine how the first merge line
187          * should appear, based on the last line of the previous commit.
188          */
189         enum graph_state prev_state;
190         /*
191          * The index of the column that refers to this commit.
192          *
193          * If none of the incoming columns refer to this commit,
194          * this will be equal to num_columns.
195          */
196         int commit_index;
197         /*
198          * The commit_index for the previously displayed commit.
199          *
200          * This is used to determine how the first line of a merge
201          * graph output should appear, based on the last line of the
202          * previous commit.
203          */
204         int prev_commit_index;
205         /*
206          * The maximum number of columns that can be stored in the columns
207          * and new_columns arrays.  This is also half the number of entries
208          * that can be stored in the mapping and new_mapping arrays.
209          */
210         int column_capacity;
211         /*
212          * The number of columns (also called "branch lines" in some places)
213          */
214         int num_columns;
215         /*
216          * The number of columns in the new_columns array
217          */
218         int num_new_columns;
219         /*
220          * The number of entries in the mapping array
221          */
222         int mapping_size;
223         /*
224          * The column state before we output the current commit.
225          */
226         struct column *columns;
227         /*
228          * The new column state after we output the current commit.
229          * Only valid when state is GRAPH_COLLAPSING.
230          */
231         struct column *new_columns;
232         /*
233          * An array that tracks the current state of each
234          * character in the output line during state GRAPH_COLLAPSING.
235          * Each entry is -1 if this character is empty, or a non-negative
236          * integer if the character contains a branch line.  The value of
237          * the integer indicates the target position for this branch line.
238          * (I.e., this array maps the current column positions to their
239          * desired positions.)
240          *
241          * The maximum capacity of this array is always
242          * sizeof(int) * 2 * column_capacity.
243          */
244         int *mapping;
245         /*
246          * A temporary array for computing the next mapping state
247          * while we are outputting a mapping line.  This is stored as part
248          * of the git_graph simply so we don't have to allocate a new
249          * temporary array each time we have to output a collapsing line.
250          */
251         int *new_mapping;
252         /*
253          * The current default column color being used.  This is
254          * stored as an index into the array column_colors.
255          */
256         unsigned short default_column_color;
257 };
258
259 static struct strbuf *diff_output_prefix_callback(struct diff_options *opt, void *data)
260 {
261         struct git_graph *graph = data;
262         static struct strbuf msgbuf = STRBUF_INIT;
263
264         assert(opt);
265
266         strbuf_reset(&msgbuf);
267         if (opt->line_prefix)
268                 strbuf_add(&msgbuf, opt->line_prefix,
269                            opt->line_prefix_length);
270         if (graph)
271                 graph_padding_line(graph, &msgbuf);
272         return &msgbuf;
273 }
274
275 static const struct diff_options *default_diffopt;
276
277 void graph_setup_line_prefix(struct diff_options *diffopt)
278 {
279         default_diffopt = diffopt;
280
281         /* setup an output prefix callback if necessary */
282         if (diffopt && !diffopt->output_prefix)
283                 diffopt->output_prefix = diff_output_prefix_callback;
284 }
285
286
287 struct git_graph *graph_init(struct rev_info *opt)
288 {
289         struct git_graph *graph = xmalloc(sizeof(struct git_graph));
290
291         if (!column_colors) {
292                 char *string;
293                 if (git_config_get_string("log.graphcolors", &string)) {
294                         /* not configured -- use default */
295                         graph_set_column_colors(column_colors_ansi,
296                                                 column_colors_ansi_max);
297                 } else {
298                         static struct argv_array custom_colors = ARGV_ARRAY_INIT;
299                         argv_array_clear(&custom_colors);
300                         parse_graph_colors_config(&custom_colors, string);
301                         free(string);
302                         /* graph_set_column_colors takes a max-index, not a count */
303                         graph_set_column_colors(custom_colors.argv,
304                                                 custom_colors.argc - 1);
305                 }
306         }
307
308         graph->commit = NULL;
309         graph->revs = opt;
310         graph->num_parents = 0;
311         graph->expansion_row = 0;
312         graph->state = GRAPH_PADDING;
313         graph->prev_state = GRAPH_PADDING;
314         graph->commit_index = 0;
315         graph->prev_commit_index = 0;
316         graph->num_columns = 0;
317         graph->num_new_columns = 0;
318         graph->mapping_size = 0;
319         /*
320          * Start the column color at the maximum value, since we'll
321          * always increment it for the first commit we output.
322          * This way we start at 0 for the first commit.
323          */
324         graph->default_column_color = column_colors_max - 1;
325
326         /*
327          * Allocate a reasonably large default number of columns
328          * We'll automatically grow columns later if we need more room.
329          */
330         graph->column_capacity = 30;
331         ALLOC_ARRAY(graph->columns, graph->column_capacity);
332         ALLOC_ARRAY(graph->new_columns, graph->column_capacity);
333         ALLOC_ARRAY(graph->mapping, 2 * graph->column_capacity);
334         ALLOC_ARRAY(graph->new_mapping, 2 * graph->column_capacity);
335
336         /*
337          * The diff output prefix callback, with this we can make
338          * all the diff output to align with the graph lines.
339          */
340         opt->diffopt.output_prefix = diff_output_prefix_callback;
341         opt->diffopt.output_prefix_data = graph;
342
343         return graph;
344 }
345
346 static void graph_update_state(struct git_graph *graph, enum graph_state s)
347 {
348         graph->prev_state = graph->state;
349         graph->state = s;
350 }
351
352 static void graph_ensure_capacity(struct git_graph *graph, int num_columns)
353 {
354         if (graph->column_capacity >= num_columns)
355                 return;
356
357         do {
358                 graph->column_capacity *= 2;
359         } while (graph->column_capacity < num_columns);
360
361         REALLOC_ARRAY(graph->columns, graph->column_capacity);
362         REALLOC_ARRAY(graph->new_columns, graph->column_capacity);
363         REALLOC_ARRAY(graph->mapping, graph->column_capacity * 2);
364         REALLOC_ARRAY(graph->new_mapping, graph->column_capacity * 2);
365 }
366
367 /*
368  * Returns 1 if the commit will be printed in the graph output,
369  * and 0 otherwise.
370  */
371 static int graph_is_interesting(struct git_graph *graph, struct commit *commit)
372 {
373         /*
374          * If revs->boundary is set, commits whose children have
375          * been shown are always interesting, even if they have the
376          * UNINTERESTING or TREESAME flags set.
377          */
378         if (graph->revs && graph->revs->boundary) {
379                 if (commit->object.flags & CHILD_SHOWN)
380                         return 1;
381         }
382
383         /*
384          * Otherwise, use get_commit_action() to see if this commit is
385          * interesting
386          */
387         return get_commit_action(graph->revs, commit) == commit_show;
388 }
389
390 static struct commit_list *next_interesting_parent(struct git_graph *graph,
391                                                    struct commit_list *orig)
392 {
393         struct commit_list *list;
394
395         /*
396          * If revs->first_parent_only is set, only the first
397          * parent is interesting.  None of the others are.
398          */
399         if (graph->revs->first_parent_only)
400                 return NULL;
401
402         /*
403          * Return the next interesting commit after orig
404          */
405         for (list = orig->next; list; list = list->next) {
406                 if (graph_is_interesting(graph, list->item))
407                         return list;
408         }
409
410         return NULL;
411 }
412
413 static struct commit_list *first_interesting_parent(struct git_graph *graph)
414 {
415         struct commit_list *parents = graph->commit->parents;
416
417         /*
418          * If this commit has no parents, ignore it
419          */
420         if (!parents)
421                 return NULL;
422
423         /*
424          * If the first parent is interesting, return it
425          */
426         if (graph_is_interesting(graph, parents->item))
427                 return parents;
428
429         /*
430          * Otherwise, call next_interesting_parent() to get
431          * the next interesting parent
432          */
433         return next_interesting_parent(graph, parents);
434 }
435
436 static unsigned short graph_get_current_column_color(const struct git_graph *graph)
437 {
438         if (!want_color(graph->revs->diffopt.use_color))
439                 return column_colors_max;
440         return graph->default_column_color;
441 }
442
443 /*
444  * Update the graph's default column color.
445  */
446 static void graph_increment_column_color(struct git_graph *graph)
447 {
448         graph->default_column_color = (graph->default_column_color + 1) %
449                 column_colors_max;
450 }
451
452 static unsigned short graph_find_commit_color(const struct git_graph *graph,
453                                               const struct commit *commit)
454 {
455         int i;
456         for (i = 0; i < graph->num_columns; i++) {
457                 if (graph->columns[i].commit == commit)
458                         return graph->columns[i].color;
459         }
460         return graph_get_current_column_color(graph);
461 }
462
463 static void graph_insert_into_new_columns(struct git_graph *graph,
464                                           struct commit *commit,
465                                           int *mapping_index)
466 {
467         int i;
468
469         /*
470          * If the commit is already in the new_columns list, we don't need to
471          * add it.  Just update the mapping correctly.
472          */
473         for (i = 0; i < graph->num_new_columns; i++) {
474                 if (graph->new_columns[i].commit == commit) {
475                         graph->mapping[*mapping_index] = i;
476                         *mapping_index += 2;
477                         return;
478                 }
479         }
480
481         /*
482          * This commit isn't already in new_columns.  Add it.
483          */
484         graph->new_columns[graph->num_new_columns].commit = commit;
485         graph->new_columns[graph->num_new_columns].color = graph_find_commit_color(graph, commit);
486         graph->mapping[*mapping_index] = graph->num_new_columns;
487         *mapping_index += 2;
488         graph->num_new_columns++;
489 }
490
491 static void graph_update_width(struct git_graph *graph,
492                                int is_commit_in_existing_columns)
493 {
494         /*
495          * Compute the width needed to display the graph for this commit.
496          * This is the maximum width needed for any row.  All other rows
497          * will be padded to this width.
498          *
499          * Compute the number of columns in the widest row:
500          * Count each existing column (graph->num_columns), and each new
501          * column added by this commit.
502          */
503         int max_cols = graph->num_columns + graph->num_parents;
504
505         /*
506          * Even if the current commit has no parents to be printed, it
507          * still takes up a column for itself.
508          */
509         if (graph->num_parents < 1)
510                 max_cols++;
511
512         /*
513          * We added a column for the current commit as part of
514          * graph->num_parents.  If the current commit was already in
515          * graph->columns, then we have double counted it.
516          */
517         if (is_commit_in_existing_columns)
518                 max_cols--;
519
520         /*
521          * Each column takes up 2 spaces
522          */
523         graph->width = max_cols * 2;
524 }
525
526 static void graph_update_columns(struct git_graph *graph)
527 {
528         struct commit_list *parent;
529         int max_new_columns;
530         int mapping_idx;
531         int i, seen_this, is_commit_in_columns;
532
533         /*
534          * Swap graph->columns with graph->new_columns
535          * graph->columns contains the state for the previous commit,
536          * and new_columns now contains the state for our commit.
537          *
538          * We'll re-use the old columns array as storage to compute the new
539          * columns list for the commit after this one.
540          */
541         SWAP(graph->columns, graph->new_columns);
542         graph->num_columns = graph->num_new_columns;
543         graph->num_new_columns = 0;
544
545         /*
546          * Now update new_columns and mapping with the information for the
547          * commit after this one.
548          *
549          * First, make sure we have enough room.  At most, there will
550          * be graph->num_columns + graph->num_parents columns for the next
551          * commit.
552          */
553         max_new_columns = graph->num_columns + graph->num_parents;
554         graph_ensure_capacity(graph, max_new_columns);
555
556         /*
557          * Clear out graph->mapping
558          */
559         graph->mapping_size = 2 * max_new_columns;
560         for (i = 0; i < graph->mapping_size; i++)
561                 graph->mapping[i] = -1;
562
563         /*
564          * Populate graph->new_columns and graph->mapping
565          *
566          * Some of the parents of this commit may already be in
567          * graph->columns.  If so, graph->new_columns should only contain a
568          * single entry for each such commit.  graph->mapping should
569          * contain information about where each current branch line is
570          * supposed to end up after the collapsing is performed.
571          */
572         seen_this = 0;
573         mapping_idx = 0;
574         is_commit_in_columns = 1;
575         for (i = 0; i <= graph->num_columns; i++) {
576                 struct commit *col_commit;
577                 if (i == graph->num_columns) {
578                         if (seen_this)
579                                 break;
580                         is_commit_in_columns = 0;
581                         col_commit = graph->commit;
582                 } else {
583                         col_commit = graph->columns[i].commit;
584                 }
585
586                 if (col_commit == graph->commit) {
587                         int old_mapping_idx = mapping_idx;
588                         seen_this = 1;
589                         graph->commit_index = i;
590                         for (parent = first_interesting_parent(graph);
591                              parent;
592                              parent = next_interesting_parent(graph, parent)) {
593                                 /*
594                                  * If this is a merge, or the start of a new
595                                  * childless column, increment the current
596                                  * color.
597                                  */
598                                 if (graph->num_parents > 1 ||
599                                     !is_commit_in_columns) {
600                                         graph_increment_column_color(graph);
601                                 }
602                                 graph_insert_into_new_columns(graph,
603                                                               parent->item,
604                                                               &mapping_idx);
605                         }
606                         /*
607                          * We always need to increment mapping_idx by at
608                          * least 2, even if it has no interesting parents.
609                          * The current commit always takes up at least 2
610                          * spaces.
611                          */
612                         if (mapping_idx == old_mapping_idx)
613                                 mapping_idx += 2;
614                 } else {
615                         graph_insert_into_new_columns(graph, col_commit,
616                                                       &mapping_idx);
617                 }
618         }
619
620         /*
621          * Shrink mapping_size to be the minimum necessary
622          */
623         while (graph->mapping_size > 1 &&
624                graph->mapping[graph->mapping_size - 1] < 0)
625                 graph->mapping_size--;
626
627         /*
628          * Compute graph->width for this commit
629          */
630         graph_update_width(graph, is_commit_in_columns);
631 }
632
633 void graph_update(struct git_graph *graph, struct commit *commit)
634 {
635         struct commit_list *parent;
636
637         /*
638          * Set the new commit
639          */
640         graph->commit = commit;
641
642         /*
643          * Count how many interesting parents this commit has
644          */
645         graph->num_parents = 0;
646         for (parent = first_interesting_parent(graph);
647              parent;
648              parent = next_interesting_parent(graph, parent))
649         {
650                 graph->num_parents++;
651         }
652
653         /*
654          * Store the old commit_index in prev_commit_index.
655          * graph_update_columns() will update graph->commit_index for this
656          * commit.
657          */
658         graph->prev_commit_index = graph->commit_index;
659
660         /*
661          * Call graph_update_columns() to update
662          * columns, new_columns, and mapping.
663          */
664         graph_update_columns(graph);
665
666         graph->expansion_row = 0;
667
668         /*
669          * Update graph->state.
670          * Note that we don't call graph_update_state() here, since
671          * we don't want to update graph->prev_state.  No line for
672          * graph->state was ever printed.
673          *
674          * If the previous commit didn't get to the GRAPH_PADDING state,
675          * it never finished its output.  Goto GRAPH_SKIP, to print out
676          * a line to indicate that portion of the graph is missing.
677          *
678          * If there are 3 or more parents, we may need to print extra rows
679          * before the commit, to expand the branch lines around it and make
680          * room for it.  We need to do this only if there is a branch row
681          * (or more) to the right of this commit.
682          *
683          * If there are less than 3 parents, we can immediately print the
684          * commit line.
685          */
686         if (graph->state != GRAPH_PADDING)
687                 graph->state = GRAPH_SKIP;
688         else if (graph->num_parents >= 3 &&
689                  graph->commit_index < (graph->num_columns - 1))
690                 graph->state = GRAPH_PRE_COMMIT;
691         else
692                 graph->state = GRAPH_COMMIT;
693 }
694
695 static int graph_is_mapping_correct(struct git_graph *graph)
696 {
697         int i;
698
699         /*
700          * The mapping is up to date if each entry is at its target,
701          * or is 1 greater than its target.
702          * (If it is 1 greater than the target, '/' will be printed, so it
703          * will look correct on the next row.)
704          */
705         for (i = 0; i < graph->mapping_size; i++) {
706                 int target = graph->mapping[i];
707                 if (target < 0)
708                         continue;
709                 if (target == (i / 2))
710                         continue;
711                 return 0;
712         }
713
714         return 1;
715 }
716
717 static void graph_pad_horizontally(struct git_graph *graph, struct graph_line *line)
718 {
719         /*
720          * Add additional spaces to the end of the strbuf, so that all
721          * lines for a particular commit have the same width.
722          *
723          * This way, fields printed to the right of the graph will remain
724          * aligned for the entire commit.
725          */
726         if (line->width < graph->width)
727                 graph_line_addchars(line, ' ', graph->width - line->width);
728 }
729
730 static void graph_output_padding_line(struct git_graph *graph,
731                                       struct graph_line *line)
732 {
733         int i;
734
735         /*
736          * Output a padding row, that leaves all branch lines unchanged
737          */
738         for (i = 0; i < graph->num_new_columns; i++) {
739                 graph_line_write_column(line, &graph->new_columns[i], '|');
740                 graph_line_addch(line, ' ');
741         }
742 }
743
744
745 int graph_width(struct git_graph *graph)
746 {
747         return graph->width;
748 }
749
750
751 static void graph_output_skip_line(struct git_graph *graph, struct graph_line *line)
752 {
753         /*
754          * Output an ellipsis to indicate that a portion
755          * of the graph is missing.
756          */
757         graph_line_addstr(line, "...");
758
759         if (graph->num_parents >= 3 &&
760             graph->commit_index < (graph->num_columns - 1))
761                 graph_update_state(graph, GRAPH_PRE_COMMIT);
762         else
763                 graph_update_state(graph, GRAPH_COMMIT);
764 }
765
766 static void graph_output_pre_commit_line(struct git_graph *graph,
767                                          struct graph_line *line)
768 {
769         int num_expansion_rows;
770         int i, seen_this;
771
772         /*
773          * This function formats a row that increases the space around a commit
774          * with multiple parents, to make room for it.  It should only be
775          * called when there are 3 or more parents.
776          *
777          * We need 2 extra rows for every parent over 2.
778          */
779         assert(graph->num_parents >= 3);
780         num_expansion_rows = (graph->num_parents - 2) * 2;
781
782         /*
783          * graph->expansion_row tracks the current expansion row we are on.
784          * It should be in the range [0, num_expansion_rows - 1]
785          */
786         assert(0 <= graph->expansion_row &&
787                graph->expansion_row < num_expansion_rows);
788
789         /*
790          * Output the row
791          */
792         seen_this = 0;
793         for (i = 0; i < graph->num_columns; i++) {
794                 struct column *col = &graph->columns[i];
795                 if (col->commit == graph->commit) {
796                         seen_this = 1;
797                         graph_line_write_column(line, col, '|');
798                         graph_line_addchars(line, ' ', graph->expansion_row);
799                 } else if (seen_this && (graph->expansion_row == 0)) {
800                         /*
801                          * This is the first line of the pre-commit output.
802                          * If the previous commit was a merge commit and
803                          * ended in the GRAPH_POST_MERGE state, all branch
804                          * lines after graph->prev_commit_index were
805                          * printed as "\" on the previous line.  Continue
806                          * to print them as "\" on this line.  Otherwise,
807                          * print the branch lines as "|".
808                          */
809                         if (graph->prev_state == GRAPH_POST_MERGE &&
810                             graph->prev_commit_index < i)
811                                 graph_line_write_column(line, col, '\\');
812                         else
813                                 graph_line_write_column(line, col, '|');
814                 } else if (seen_this && (graph->expansion_row > 0)) {
815                         graph_line_write_column(line, col, '\\');
816                 } else {
817                         graph_line_write_column(line, col, '|');
818                 }
819                 graph_line_addch(line, ' ');
820         }
821
822         /*
823          * Increment graph->expansion_row,
824          * and move to state GRAPH_COMMIT if necessary
825          */
826         graph->expansion_row++;
827         if (graph->expansion_row >= num_expansion_rows)
828                 graph_update_state(graph, GRAPH_COMMIT);
829 }
830
831 static void graph_output_commit_char(struct git_graph *graph, struct graph_line *line)
832 {
833         /*
834          * For boundary commits, print 'o'
835          * (We should only see boundary commits when revs->boundary is set.)
836          */
837         if (graph->commit->object.flags & BOUNDARY) {
838                 assert(graph->revs->boundary);
839                 graph_line_addch(line, 'o');
840                 return;
841         }
842
843         /*
844          * get_revision_mark() handles all other cases without assert()
845          */
846         graph_line_addstr(line, get_revision_mark(graph->revs, graph->commit));
847 }
848
849 /*
850  * Draw the horizontal dashes of an octopus merge.
851  */
852 static void graph_draw_octopus_merge(struct git_graph *graph, struct graph_line *line)
853 {
854         /*
855          * Here dashless_parents represents the number of parents which don't
856          * need to have dashes (the edges labeled "0" and "1").  And
857          * dashful_parents are the remaining ones.
858          *
859          * | *---.
860          * | |\ \ \
861          * | | | | |
862          * x 0 1 2 3
863          *
864          */
865         const int dashless_parents = 2;
866         int dashful_parents = graph->num_parents - dashless_parents;
867
868         /*
869          * Usually, we add one new column for each parent (like the diagram
870          * above) but sometimes the first parent goes into an existing column,
871          * like this:
872          *
873          * | *---.
874          * | |\ \ \
875          * |/ / / /
876          * x 0 1 2
877          *
878          * In which case the number of parents will be one greater than the
879          * number of added columns.
880          */
881         int added_cols = (graph->num_new_columns - graph->num_columns);
882         int parent_in_old_cols = graph->num_parents - added_cols;
883
884         /*
885          * In both cases, commit_index corresponds to the edge labeled "0".
886          */
887         int first_col = graph->commit_index + dashless_parents
888             - parent_in_old_cols;
889
890         int i;
891         for (i = 0; i < dashful_parents; i++) {
892                 graph_line_write_column(line, &graph->new_columns[i+first_col], '-');
893                 graph_line_write_column(line, &graph->new_columns[i+first_col],
894                                           i == dashful_parents-1 ? '.' : '-');
895         }
896 }
897
898 static void graph_output_commit_line(struct git_graph *graph, struct graph_line *line)
899 {
900         int seen_this = 0;
901         int i;
902
903         /*
904          * Output the row containing this commit
905          * Iterate up to and including graph->num_columns,
906          * since the current commit may not be in any of the existing
907          * columns.  (This happens when the current commit doesn't have any
908          * children that we have already processed.)
909          */
910         seen_this = 0;
911         for (i = 0; i <= graph->num_columns; i++) {
912                 struct column *col = &graph->columns[i];
913                 struct commit *col_commit;
914                 if (i == graph->num_columns) {
915                         if (seen_this)
916                                 break;
917                         col_commit = graph->commit;
918                 } else {
919                         col_commit = graph->columns[i].commit;
920                 }
921
922                 if (col_commit == graph->commit) {
923                         seen_this = 1;
924                         graph_output_commit_char(graph, line);
925
926                         if (graph->num_parents > 2)
927                                 graph_draw_octopus_merge(graph, line);
928                 } else if (seen_this && (graph->num_parents > 2)) {
929                         graph_line_write_column(line, col, '\\');
930                 } else if (seen_this && (graph->num_parents == 2)) {
931                         /*
932                          * This is a 2-way merge commit.
933                          * There is no GRAPH_PRE_COMMIT stage for 2-way
934                          * merges, so this is the first line of output
935                          * for this commit.  Check to see what the previous
936                          * line of output was.
937                          *
938                          * If it was GRAPH_POST_MERGE, the branch line
939                          * coming into this commit may have been '\',
940                          * and not '|' or '/'.  If so, output the branch
941                          * line as '\' on this line, instead of '|'.  This
942                          * makes the output look nicer.
943                          */
944                         if (graph->prev_state == GRAPH_POST_MERGE &&
945                             graph->prev_commit_index < i)
946                                 graph_line_write_column(line, col, '\\');
947                         else
948                                 graph_line_write_column(line, col, '|');
949                 } else {
950                         graph_line_write_column(line, col, '|');
951                 }
952                 graph_line_addch(line, ' ');
953         }
954
955         /*
956          * Update graph->state
957          */
958         if (graph->num_parents > 1)
959                 graph_update_state(graph, GRAPH_POST_MERGE);
960         else if (graph_is_mapping_correct(graph))
961                 graph_update_state(graph, GRAPH_PADDING);
962         else
963                 graph_update_state(graph, GRAPH_COLLAPSING);
964 }
965
966 static struct column *find_new_column_by_commit(struct git_graph *graph,
967                                                 struct commit *commit)
968 {
969         int i;
970         for (i = 0; i < graph->num_new_columns; i++) {
971                 if (graph->new_columns[i].commit == commit)
972                         return &graph->new_columns[i];
973         }
974         return NULL;
975 }
976
977 static void graph_output_post_merge_line(struct git_graph *graph, struct graph_line *line)
978 {
979         int seen_this = 0;
980         int i, j;
981
982         /*
983          * Output the post-merge row
984          */
985         for (i = 0; i <= graph->num_columns; i++) {
986                 struct column *col = &graph->columns[i];
987                 struct commit *col_commit;
988                 if (i == graph->num_columns) {
989                         if (seen_this)
990                                 break;
991                         col_commit = graph->commit;
992                 } else {
993                         col_commit = col->commit;
994                 }
995
996                 if (col_commit == graph->commit) {
997                         /*
998                          * Since the current commit is a merge find
999                          * the columns for the parent commits in
1000                          * new_columns and use those to format the
1001                          * edges.
1002                          */
1003                         struct commit_list *parents = NULL;
1004                         struct column *par_column;
1005                         seen_this = 1;
1006                         parents = first_interesting_parent(graph);
1007                         assert(parents);
1008                         par_column = find_new_column_by_commit(graph, parents->item);
1009                         assert(par_column);
1010
1011                         graph_line_write_column(line, par_column, '|');
1012                         for (j = 0; j < graph->num_parents - 1; j++) {
1013                                 parents = next_interesting_parent(graph, parents);
1014                                 assert(parents);
1015                                 par_column = find_new_column_by_commit(graph, parents->item);
1016                                 assert(par_column);
1017                                 graph_line_write_column(line, par_column, '\\');
1018                                 graph_line_addch(line, ' ');
1019                         }
1020                 } else if (seen_this) {
1021                         graph_line_write_column(line, col, '\\');
1022                         graph_line_addch(line, ' ');
1023                 } else {
1024                         graph_line_write_column(line, col, '|');
1025                         graph_line_addch(line, ' ');
1026                 }
1027         }
1028
1029         /*
1030          * Update graph->state
1031          */
1032         if (graph_is_mapping_correct(graph))
1033                 graph_update_state(graph, GRAPH_PADDING);
1034         else
1035                 graph_update_state(graph, GRAPH_COLLAPSING);
1036 }
1037
1038 static void graph_output_collapsing_line(struct git_graph *graph, struct graph_line *line)
1039 {
1040         int i;
1041         short used_horizontal = 0;
1042         int horizontal_edge = -1;
1043         int horizontal_edge_target = -1;
1044
1045         /*
1046          * Clear out the new_mapping array
1047          */
1048         for (i = 0; i < graph->mapping_size; i++)
1049                 graph->new_mapping[i] = -1;
1050
1051         for (i = 0; i < graph->mapping_size; i++) {
1052                 int target = graph->mapping[i];
1053                 if (target < 0)
1054                         continue;
1055
1056                 /*
1057                  * Since update_columns() always inserts the leftmost
1058                  * column first, each branch's target location should
1059                  * always be either its current location or to the left of
1060                  * its current location.
1061                  *
1062                  * We never have to move branches to the right.  This makes
1063                  * the graph much more legible, since whenever branches
1064                  * cross, only one is moving directions.
1065                  */
1066                 assert(target * 2 <= i);
1067
1068                 if (target * 2 == i) {
1069                         /*
1070                          * This column is already in the
1071                          * correct place
1072                          */
1073                         assert(graph->new_mapping[i] == -1);
1074                         graph->new_mapping[i] = target;
1075                 } else if (graph->new_mapping[i - 1] < 0) {
1076                         /*
1077                          * Nothing is to the left.
1078                          * Move to the left by one
1079                          */
1080                         graph->new_mapping[i - 1] = target;
1081                         /*
1082                          * If there isn't already an edge moving horizontally
1083                          * select this one.
1084                          */
1085                         if (horizontal_edge == -1) {
1086                                 int j;
1087                                 horizontal_edge = i;
1088                                 horizontal_edge_target = target;
1089                                 /*
1090                                  * The variable target is the index of the graph
1091                                  * column, and therefore target*2+3 is the
1092                                  * actual screen column of the first horizontal
1093                                  * line.
1094                                  */
1095                                 for (j = (target * 2)+3; j < (i - 2); j += 2)
1096                                         graph->new_mapping[j] = target;
1097                         }
1098                 } else if (graph->new_mapping[i - 1] == target) {
1099                         /*
1100                          * There is a branch line to our left
1101                          * already, and it is our target.  We
1102                          * combine with this line, since we share
1103                          * the same parent commit.
1104                          *
1105                          * We don't have to add anything to the
1106                          * output or new_mapping, since the
1107                          * existing branch line has already taken
1108                          * care of it.
1109                          */
1110                 } else {
1111                         /*
1112                          * There is a branch line to our left,
1113                          * but it isn't our target.  We need to
1114                          * cross over it.
1115                          *
1116                          * The space just to the left of this
1117                          * branch should always be empty.
1118                          *
1119                          * The branch to the left of that space
1120                          * should be our eventual target.
1121                          */
1122                         assert(graph->new_mapping[i - 1] > target);
1123                         assert(graph->new_mapping[i - 2] < 0);
1124                         assert(graph->new_mapping[i - 3] == target);
1125                         graph->new_mapping[i - 2] = target;
1126                         /*
1127                          * Mark this branch as the horizontal edge to
1128                          * prevent any other edges from moving
1129                          * horizontally.
1130                          */
1131                         if (horizontal_edge == -1)
1132                                 horizontal_edge = i;
1133                 }
1134         }
1135
1136         /*
1137          * The new mapping may be 1 smaller than the old mapping
1138          */
1139         if (graph->new_mapping[graph->mapping_size - 1] < 0)
1140                 graph->mapping_size--;
1141
1142         /*
1143          * Output out a line based on the new mapping info
1144          */
1145         for (i = 0; i < graph->mapping_size; i++) {
1146                 int target = graph->new_mapping[i];
1147                 if (target < 0)
1148                         graph_line_addch(line, ' ');
1149                 else if (target * 2 == i)
1150                         graph_line_write_column(line, &graph->new_columns[target], '|');
1151                 else if (target == horizontal_edge_target &&
1152                          i != horizontal_edge - 1) {
1153                                 /*
1154                                  * Set the mappings for all but the
1155                                  * first segment to -1 so that they
1156                                  * won't continue into the next line.
1157                                  */
1158                                 if (i != (target * 2)+3)
1159                                         graph->new_mapping[i] = -1;
1160                                 used_horizontal = 1;
1161                         graph_line_write_column(line, &graph->new_columns[target], '_');
1162                 } else {
1163                         if (used_horizontal && i < horizontal_edge)
1164                                 graph->new_mapping[i] = -1;
1165                         graph_line_write_column(line, &graph->new_columns[target], '/');
1166
1167                 }
1168         }
1169
1170         /*
1171          * Swap mapping and new_mapping
1172          */
1173         SWAP(graph->mapping, graph->new_mapping);
1174
1175         /*
1176          * If graph->mapping indicates that all of the branch lines
1177          * are already in the correct positions, we are done.
1178          * Otherwise, we need to collapse some branch lines together.
1179          */
1180         if (graph_is_mapping_correct(graph))
1181                 graph_update_state(graph, GRAPH_PADDING);
1182 }
1183
1184 int graph_next_line(struct git_graph *graph, struct strbuf *sb)
1185 {
1186         int shown_commit_line = 0;
1187         struct graph_line line = { .buf = sb, .width = 0 };
1188
1189         /*
1190          * We could conceivable be called with a NULL commit
1191          * if our caller has a bug, and invokes graph_next_line()
1192          * immediately after graph_init(), without first calling
1193          * graph_update().  Return without outputting anything in this
1194          * case.
1195          */
1196         if (!graph->commit)
1197                 return -1;
1198
1199         switch (graph->state) {
1200         case GRAPH_PADDING:
1201                 graph_output_padding_line(graph, &line);
1202                 break;
1203         case GRAPH_SKIP:
1204                 graph_output_skip_line(graph, &line);
1205                 break;
1206         case GRAPH_PRE_COMMIT:
1207                 graph_output_pre_commit_line(graph, &line);
1208                 break;
1209         case GRAPH_COMMIT:
1210                 graph_output_commit_line(graph, &line);
1211                 shown_commit_line = 1;
1212                 break;
1213         case GRAPH_POST_MERGE:
1214                 graph_output_post_merge_line(graph, &line);
1215                 break;
1216         case GRAPH_COLLAPSING:
1217                 graph_output_collapsing_line(graph, &line);
1218                 break;
1219         }
1220
1221         graph_pad_horizontally(graph, &line);
1222         return shown_commit_line;
1223 }
1224
1225 static void graph_padding_line(struct git_graph *graph, struct strbuf *sb)
1226 {
1227         int i;
1228         struct graph_line line = { .buf = sb, .width = 0 };
1229
1230         if (graph->state != GRAPH_COMMIT) {
1231                 graph_next_line(graph, sb);
1232                 return;
1233         }
1234
1235         /*
1236          * Output the row containing this commit
1237          * Iterate up to and including graph->num_columns,
1238          * since the current commit may not be in any of the existing
1239          * columns.  (This happens when the current commit doesn't have any
1240          * children that we have already processed.)
1241          */
1242         for (i = 0; i < graph->num_columns; i++) {
1243                 struct column *col = &graph->columns[i];
1244
1245                 graph_line_write_column(&line, col, '|');
1246
1247                 if (col->commit == graph->commit && graph->num_parents > 2) {
1248                         int len = (graph->num_parents - 2) * 2;
1249                         graph_line_addchars(&line, ' ', len);
1250                 } else {
1251                         graph_line_addch(&line, ' ');
1252                 }
1253         }
1254
1255         graph_pad_horizontally(graph, &line);
1256
1257         /*
1258          * Update graph->prev_state since we have output a padding line
1259          */
1260         graph->prev_state = GRAPH_PADDING;
1261 }
1262
1263 int graph_is_commit_finished(struct git_graph const *graph)
1264 {
1265         return (graph->state == GRAPH_PADDING);
1266 }
1267
1268 void graph_show_commit(struct git_graph *graph)
1269 {
1270         struct strbuf msgbuf = STRBUF_INIT;
1271         int shown_commit_line = 0;
1272
1273         graph_show_line_prefix(default_diffopt);
1274
1275         if (!graph)
1276                 return;
1277
1278         /*
1279          * When showing a diff of a merge against each of its parents, we
1280          * are called once for each parent without graph_update having been
1281          * called.  In this case, simply output a single padding line.
1282          */
1283         if (graph_is_commit_finished(graph)) {
1284                 graph_show_padding(graph);
1285                 shown_commit_line = 1;
1286         }
1287
1288         while (!shown_commit_line && !graph_is_commit_finished(graph)) {
1289                 shown_commit_line = graph_next_line(graph, &msgbuf);
1290                 fwrite(msgbuf.buf, sizeof(char), msgbuf.len,
1291                         graph->revs->diffopt.file);
1292                 if (!shown_commit_line) {
1293                         putc('\n', graph->revs->diffopt.file);
1294                         graph_show_line_prefix(&graph->revs->diffopt);
1295                 }
1296                 strbuf_setlen(&msgbuf, 0);
1297         }
1298
1299         strbuf_release(&msgbuf);
1300 }
1301
1302 void graph_show_oneline(struct git_graph *graph)
1303 {
1304         struct strbuf msgbuf = STRBUF_INIT;
1305
1306         graph_show_line_prefix(default_diffopt);
1307
1308         if (!graph)
1309                 return;
1310
1311         graph_next_line(graph, &msgbuf);
1312         fwrite(msgbuf.buf, sizeof(char), msgbuf.len, graph->revs->diffopt.file);
1313         strbuf_release(&msgbuf);
1314 }
1315
1316 void graph_show_padding(struct git_graph *graph)
1317 {
1318         struct strbuf msgbuf = STRBUF_INIT;
1319
1320         graph_show_line_prefix(default_diffopt);
1321
1322         if (!graph)
1323                 return;
1324
1325         graph_padding_line(graph, &msgbuf);
1326         fwrite(msgbuf.buf, sizeof(char), msgbuf.len, graph->revs->diffopt.file);
1327         strbuf_release(&msgbuf);
1328 }
1329
1330 int graph_show_remainder(struct git_graph *graph)
1331 {
1332         struct strbuf msgbuf = STRBUF_INIT;
1333         int shown = 0;
1334
1335         graph_show_line_prefix(default_diffopt);
1336
1337         if (!graph)
1338                 return 0;
1339
1340         if (graph_is_commit_finished(graph))
1341                 return 0;
1342
1343         for (;;) {
1344                 graph_next_line(graph, &msgbuf);
1345                 fwrite(msgbuf.buf, sizeof(char), msgbuf.len,
1346                         graph->revs->diffopt.file);
1347                 strbuf_setlen(&msgbuf, 0);
1348                 shown = 1;
1349
1350                 if (!graph_is_commit_finished(graph)) {
1351                         putc('\n', graph->revs->diffopt.file);
1352                         graph_show_line_prefix(&graph->revs->diffopt);
1353                 } else {
1354                         break;
1355                 }
1356         }
1357         strbuf_release(&msgbuf);
1358
1359         return shown;
1360 }
1361
1362 static void graph_show_strbuf(struct git_graph *graph,
1363                               FILE *file,
1364                               struct strbuf const *sb)
1365 {
1366         char *p;
1367
1368         /*
1369          * Print the strbuf line by line,
1370          * and display the graph info before each line but the first.
1371          */
1372         p = sb->buf;
1373         while (p) {
1374                 size_t len;
1375                 char *next_p = strchr(p, '\n');
1376                 if (next_p) {
1377                         next_p++;
1378                         len = next_p - p;
1379                 } else {
1380                         len = (sb->buf + sb->len) - p;
1381                 }
1382                 fwrite(p, sizeof(char), len, file);
1383                 if (next_p && *next_p != '\0')
1384                         graph_show_oneline(graph);
1385                 p = next_p;
1386         }
1387 }
1388
1389 void graph_show_commit_msg(struct git_graph *graph,
1390                            FILE *file,
1391                            struct strbuf const *sb)
1392 {
1393         int newline_terminated;
1394
1395         /*
1396          * Show the commit message
1397          */
1398         graph_show_strbuf(graph, file, sb);
1399
1400         if (!graph)
1401                 return;
1402
1403         newline_terminated = (sb->len && sb->buf[sb->len - 1] == '\n');
1404
1405         /*
1406          * If there is more output needed for this commit, show it now
1407          */
1408         if (!graph_is_commit_finished(graph)) {
1409                 /*
1410                  * If sb doesn't have a terminating newline, print one now,
1411                  * so we can start the remainder of the graph output on a
1412                  * new line.
1413                  */
1414                 if (!newline_terminated)
1415                         putc('\n', file);
1416
1417                 graph_show_remainder(graph);
1418
1419                 /*
1420                  * If sb ends with a newline, our output should too.
1421                  */
1422                 if (newline_terminated)
1423                         putc('\n', file);
1424         }
1425 }