graph: reuse `find_new_column_by_commit()`
[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 int graph_find_new_column_by_commit(struct git_graph *graph,
464                                            struct commit *commit)
465 {
466         int i;
467         for (i = 0; i < graph->num_new_columns; i++) {
468                 if (graph->new_columns[i].commit == commit)
469                         return i;
470         }
471         return -1;
472 }
473
474 static void graph_insert_into_new_columns(struct git_graph *graph,
475                                           struct commit *commit,
476                                           int *mapping_index)
477 {
478         int i = graph_find_new_column_by_commit(graph, commit);
479
480         /*
481          * If the commit is already in the new_columns list, we don't need to
482          * add it.  Just update the mapping correctly.
483          */
484         if (i >= 0) {
485                 graph->mapping[*mapping_index] = i;
486                 *mapping_index += 2;
487                 return;
488         }
489
490         /*
491          * This commit isn't already in new_columns.  Add it.
492          */
493         graph->new_columns[graph->num_new_columns].commit = commit;
494         graph->new_columns[graph->num_new_columns].color = graph_find_commit_color(graph, commit);
495         graph->mapping[*mapping_index] = graph->num_new_columns;
496         *mapping_index += 2;
497         graph->num_new_columns++;
498 }
499
500 static void graph_update_width(struct git_graph *graph,
501                                int is_commit_in_existing_columns)
502 {
503         /*
504          * Compute the width needed to display the graph for this commit.
505          * This is the maximum width needed for any row.  All other rows
506          * will be padded to this width.
507          *
508          * Compute the number of columns in the widest row:
509          * Count each existing column (graph->num_columns), and each new
510          * column added by this commit.
511          */
512         int max_cols = graph->num_columns + graph->num_parents;
513
514         /*
515          * Even if the current commit has no parents to be printed, it
516          * still takes up a column for itself.
517          */
518         if (graph->num_parents < 1)
519                 max_cols++;
520
521         /*
522          * We added a column for the current commit as part of
523          * graph->num_parents.  If the current commit was already in
524          * graph->columns, then we have double counted it.
525          */
526         if (is_commit_in_existing_columns)
527                 max_cols--;
528
529         /*
530          * Each column takes up 2 spaces
531          */
532         graph->width = max_cols * 2;
533 }
534
535 static void graph_update_columns(struct git_graph *graph)
536 {
537         struct commit_list *parent;
538         int max_new_columns;
539         int mapping_idx;
540         int i, seen_this, is_commit_in_columns;
541
542         /*
543          * Swap graph->columns with graph->new_columns
544          * graph->columns contains the state for the previous commit,
545          * and new_columns now contains the state for our commit.
546          *
547          * We'll re-use the old columns array as storage to compute the new
548          * columns list for the commit after this one.
549          */
550         SWAP(graph->columns, graph->new_columns);
551         graph->num_columns = graph->num_new_columns;
552         graph->num_new_columns = 0;
553
554         /*
555          * Now update new_columns and mapping with the information for the
556          * commit after this one.
557          *
558          * First, make sure we have enough room.  At most, there will
559          * be graph->num_columns + graph->num_parents columns for the next
560          * commit.
561          */
562         max_new_columns = graph->num_columns + graph->num_parents;
563         graph_ensure_capacity(graph, max_new_columns);
564
565         /*
566          * Clear out graph->mapping
567          */
568         graph->mapping_size = 2 * max_new_columns;
569         for (i = 0; i < graph->mapping_size; i++)
570                 graph->mapping[i] = -1;
571
572         /*
573          * Populate graph->new_columns and graph->mapping
574          *
575          * Some of the parents of this commit may already be in
576          * graph->columns.  If so, graph->new_columns should only contain a
577          * single entry for each such commit.  graph->mapping should
578          * contain information about where each current branch line is
579          * supposed to end up after the collapsing is performed.
580          */
581         seen_this = 0;
582         mapping_idx = 0;
583         is_commit_in_columns = 1;
584         for (i = 0; i <= graph->num_columns; i++) {
585                 struct commit *col_commit;
586                 if (i == graph->num_columns) {
587                         if (seen_this)
588                                 break;
589                         is_commit_in_columns = 0;
590                         col_commit = graph->commit;
591                 } else {
592                         col_commit = graph->columns[i].commit;
593                 }
594
595                 if (col_commit == graph->commit) {
596                         int old_mapping_idx = mapping_idx;
597                         seen_this = 1;
598                         graph->commit_index = i;
599                         for (parent = first_interesting_parent(graph);
600                              parent;
601                              parent = next_interesting_parent(graph, parent)) {
602                                 /*
603                                  * If this is a merge, or the start of a new
604                                  * childless column, increment the current
605                                  * color.
606                                  */
607                                 if (graph->num_parents > 1 ||
608                                     !is_commit_in_columns) {
609                                         graph_increment_column_color(graph);
610                                 }
611                                 graph_insert_into_new_columns(graph,
612                                                               parent->item,
613                                                               &mapping_idx);
614                         }
615                         /*
616                          * We always need to increment mapping_idx by at
617                          * least 2, even if it has no interesting parents.
618                          * The current commit always takes up at least 2
619                          * spaces.
620                          */
621                         if (mapping_idx == old_mapping_idx)
622                                 mapping_idx += 2;
623                 } else {
624                         graph_insert_into_new_columns(graph, col_commit,
625                                                       &mapping_idx);
626                 }
627         }
628
629         /*
630          * Shrink mapping_size to be the minimum necessary
631          */
632         while (graph->mapping_size > 1 &&
633                graph->mapping[graph->mapping_size - 1] < 0)
634                 graph->mapping_size--;
635
636         /*
637          * Compute graph->width for this commit
638          */
639         graph_update_width(graph, is_commit_in_columns);
640 }
641
642 void graph_update(struct git_graph *graph, struct commit *commit)
643 {
644         struct commit_list *parent;
645
646         /*
647          * Set the new commit
648          */
649         graph->commit = commit;
650
651         /*
652          * Count how many interesting parents this commit has
653          */
654         graph->num_parents = 0;
655         for (parent = first_interesting_parent(graph);
656              parent;
657              parent = next_interesting_parent(graph, parent))
658         {
659                 graph->num_parents++;
660         }
661
662         /*
663          * Store the old commit_index in prev_commit_index.
664          * graph_update_columns() will update graph->commit_index for this
665          * commit.
666          */
667         graph->prev_commit_index = graph->commit_index;
668
669         /*
670          * Call graph_update_columns() to update
671          * columns, new_columns, and mapping.
672          */
673         graph_update_columns(graph);
674
675         graph->expansion_row = 0;
676
677         /*
678          * Update graph->state.
679          * Note that we don't call graph_update_state() here, since
680          * we don't want to update graph->prev_state.  No line for
681          * graph->state was ever printed.
682          *
683          * If the previous commit didn't get to the GRAPH_PADDING state,
684          * it never finished its output.  Goto GRAPH_SKIP, to print out
685          * a line to indicate that portion of the graph is missing.
686          *
687          * If there are 3 or more parents, we may need to print extra rows
688          * before the commit, to expand the branch lines around it and make
689          * room for it.  We need to do this only if there is a branch row
690          * (or more) to the right of this commit.
691          *
692          * If there are less than 3 parents, we can immediately print the
693          * commit line.
694          */
695         if (graph->state != GRAPH_PADDING)
696                 graph->state = GRAPH_SKIP;
697         else if (graph->num_parents >= 3 &&
698                  graph->commit_index < (graph->num_columns - 1))
699                 graph->state = GRAPH_PRE_COMMIT;
700         else
701                 graph->state = GRAPH_COMMIT;
702 }
703
704 static int graph_is_mapping_correct(struct git_graph *graph)
705 {
706         int i;
707
708         /*
709          * The mapping is up to date if each entry is at its target,
710          * or is 1 greater than its target.
711          * (If it is 1 greater than the target, '/' will be printed, so it
712          * will look correct on the next row.)
713          */
714         for (i = 0; i < graph->mapping_size; i++) {
715                 int target = graph->mapping[i];
716                 if (target < 0)
717                         continue;
718                 if (target == (i / 2))
719                         continue;
720                 return 0;
721         }
722
723         return 1;
724 }
725
726 static void graph_pad_horizontally(struct git_graph *graph, struct graph_line *line)
727 {
728         /*
729          * Add additional spaces to the end of the strbuf, so that all
730          * lines for a particular commit have the same width.
731          *
732          * This way, fields printed to the right of the graph will remain
733          * aligned for the entire commit.
734          */
735         if (line->width < graph->width)
736                 graph_line_addchars(line, ' ', graph->width - line->width);
737 }
738
739 static void graph_output_padding_line(struct git_graph *graph,
740                                       struct graph_line *line)
741 {
742         int i;
743
744         /*
745          * Output a padding row, that leaves all branch lines unchanged
746          */
747         for (i = 0; i < graph->num_new_columns; i++) {
748                 graph_line_write_column(line, &graph->new_columns[i], '|');
749                 graph_line_addch(line, ' ');
750         }
751 }
752
753
754 int graph_width(struct git_graph *graph)
755 {
756         return graph->width;
757 }
758
759
760 static void graph_output_skip_line(struct git_graph *graph, struct graph_line *line)
761 {
762         /*
763          * Output an ellipsis to indicate that a portion
764          * of the graph is missing.
765          */
766         graph_line_addstr(line, "...");
767
768         if (graph->num_parents >= 3 &&
769             graph->commit_index < (graph->num_columns - 1))
770                 graph_update_state(graph, GRAPH_PRE_COMMIT);
771         else
772                 graph_update_state(graph, GRAPH_COMMIT);
773 }
774
775 static void graph_output_pre_commit_line(struct git_graph *graph,
776                                          struct graph_line *line)
777 {
778         int num_expansion_rows;
779         int i, seen_this;
780
781         /*
782          * This function formats a row that increases the space around a commit
783          * with multiple parents, to make room for it.  It should only be
784          * called when there are 3 or more parents.
785          *
786          * We need 2 extra rows for every parent over 2.
787          */
788         assert(graph->num_parents >= 3);
789         num_expansion_rows = (graph->num_parents - 2) * 2;
790
791         /*
792          * graph->expansion_row tracks the current expansion row we are on.
793          * It should be in the range [0, num_expansion_rows - 1]
794          */
795         assert(0 <= graph->expansion_row &&
796                graph->expansion_row < num_expansion_rows);
797
798         /*
799          * Output the row
800          */
801         seen_this = 0;
802         for (i = 0; i < graph->num_columns; i++) {
803                 struct column *col = &graph->columns[i];
804                 if (col->commit == graph->commit) {
805                         seen_this = 1;
806                         graph_line_write_column(line, col, '|');
807                         graph_line_addchars(line, ' ', graph->expansion_row);
808                 } else if (seen_this && (graph->expansion_row == 0)) {
809                         /*
810                          * This is the first line of the pre-commit output.
811                          * If the previous commit was a merge commit and
812                          * ended in the GRAPH_POST_MERGE state, all branch
813                          * lines after graph->prev_commit_index were
814                          * printed as "\" on the previous line.  Continue
815                          * to print them as "\" on this line.  Otherwise,
816                          * print the branch lines as "|".
817                          */
818                         if (graph->prev_state == GRAPH_POST_MERGE &&
819                             graph->prev_commit_index < i)
820                                 graph_line_write_column(line, col, '\\');
821                         else
822                                 graph_line_write_column(line, col, '|');
823                 } else if (seen_this && (graph->expansion_row > 0)) {
824                         graph_line_write_column(line, col, '\\');
825                 } else {
826                         graph_line_write_column(line, col, '|');
827                 }
828                 graph_line_addch(line, ' ');
829         }
830
831         /*
832          * Increment graph->expansion_row,
833          * and move to state GRAPH_COMMIT if necessary
834          */
835         graph->expansion_row++;
836         if (graph->expansion_row >= num_expansion_rows)
837                 graph_update_state(graph, GRAPH_COMMIT);
838 }
839
840 static void graph_output_commit_char(struct git_graph *graph, struct graph_line *line)
841 {
842         /*
843          * For boundary commits, print 'o'
844          * (We should only see boundary commits when revs->boundary is set.)
845          */
846         if (graph->commit->object.flags & BOUNDARY) {
847                 assert(graph->revs->boundary);
848                 graph_line_addch(line, 'o');
849                 return;
850         }
851
852         /*
853          * get_revision_mark() handles all other cases without assert()
854          */
855         graph_line_addstr(line, get_revision_mark(graph->revs, graph->commit));
856 }
857
858 /*
859  * Draw the horizontal dashes of an octopus merge.
860  */
861 static void graph_draw_octopus_merge(struct git_graph *graph, struct graph_line *line)
862 {
863         /*
864          * Here dashless_parents represents the number of parents which don't
865          * need to have dashes (the edges labeled "0" and "1").  And
866          * dashful_parents are the remaining ones.
867          *
868          * | *---.
869          * | |\ \ \
870          * | | | | |
871          * x 0 1 2 3
872          *
873          */
874         const int dashless_parents = 2;
875         int dashful_parents = graph->num_parents - dashless_parents;
876
877         /*
878          * Usually, we add one new column for each parent (like the diagram
879          * above) but sometimes the first parent goes into an existing column,
880          * like this:
881          *
882          * | *---.
883          * | |\ \ \
884          * |/ / / /
885          * x 0 1 2
886          *
887          * In which case the number of parents will be one greater than the
888          * number of added columns.
889          */
890         int added_cols = (graph->num_new_columns - graph->num_columns);
891         int parent_in_old_cols = graph->num_parents - added_cols;
892
893         /*
894          * In both cases, commit_index corresponds to the edge labeled "0".
895          */
896         int first_col = graph->commit_index + dashless_parents
897             - parent_in_old_cols;
898
899         int i;
900         for (i = 0; i < dashful_parents; i++) {
901                 graph_line_write_column(line, &graph->new_columns[i+first_col], '-');
902                 graph_line_write_column(line, &graph->new_columns[i+first_col],
903                                           i == dashful_parents-1 ? '.' : '-');
904         }
905 }
906
907 static void graph_output_commit_line(struct git_graph *graph, struct graph_line *line)
908 {
909         int seen_this = 0;
910         int i;
911
912         /*
913          * Output the row containing this commit
914          * Iterate up to and including graph->num_columns,
915          * since the current commit may not be in any of the existing
916          * columns.  (This happens when the current commit doesn't have any
917          * children that we have already processed.)
918          */
919         seen_this = 0;
920         for (i = 0; i <= graph->num_columns; i++) {
921                 struct column *col = &graph->columns[i];
922                 struct commit *col_commit;
923                 if (i == graph->num_columns) {
924                         if (seen_this)
925                                 break;
926                         col_commit = graph->commit;
927                 } else {
928                         col_commit = graph->columns[i].commit;
929                 }
930
931                 if (col_commit == graph->commit) {
932                         seen_this = 1;
933                         graph_output_commit_char(graph, line);
934
935                         if (graph->num_parents > 2)
936                                 graph_draw_octopus_merge(graph, line);
937                 } else if (seen_this && (graph->num_parents > 2)) {
938                         graph_line_write_column(line, col, '\\');
939                 } else if (seen_this && (graph->num_parents == 2)) {
940                         /*
941                          * This is a 2-way merge commit.
942                          * There is no GRAPH_PRE_COMMIT stage for 2-way
943                          * merges, so this is the first line of output
944                          * for this commit.  Check to see what the previous
945                          * line of output was.
946                          *
947                          * If it was GRAPH_POST_MERGE, the branch line
948                          * coming into this commit may have been '\',
949                          * and not '|' or '/'.  If so, output the branch
950                          * line as '\' on this line, instead of '|'.  This
951                          * makes the output look nicer.
952                          */
953                         if (graph->prev_state == GRAPH_POST_MERGE &&
954                             graph->prev_commit_index < i)
955                                 graph_line_write_column(line, col, '\\');
956                         else
957                                 graph_line_write_column(line, col, '|');
958                 } else {
959                         graph_line_write_column(line, col, '|');
960                 }
961                 graph_line_addch(line, ' ');
962         }
963
964         /*
965          * Update graph->state
966          */
967         if (graph->num_parents > 1)
968                 graph_update_state(graph, GRAPH_POST_MERGE);
969         else if (graph_is_mapping_correct(graph))
970                 graph_update_state(graph, GRAPH_PADDING);
971         else
972                 graph_update_state(graph, GRAPH_COLLAPSING);
973 }
974
975 static void graph_output_post_merge_line(struct git_graph *graph, struct graph_line *line)
976 {
977         int seen_this = 0;
978         int i, j;
979
980         /*
981          * Output the post-merge row
982          */
983         for (i = 0; i <= graph->num_columns; i++) {
984                 struct column *col = &graph->columns[i];
985                 struct commit *col_commit;
986                 if (i == graph->num_columns) {
987                         if (seen_this)
988                                 break;
989                         col_commit = graph->commit;
990                 } else {
991                         col_commit = col->commit;
992                 }
993
994                 if (col_commit == graph->commit) {
995                         /*
996                          * Since the current commit is a merge find
997                          * the columns for the parent commits in
998                          * new_columns and use those to format the
999                          * edges.
1000                          */
1001                         struct commit_list *parents = NULL;
1002                         int par_column;
1003                         seen_this = 1;
1004                         parents = first_interesting_parent(graph);
1005                         assert(parents);
1006                         par_column = graph_find_new_column_by_commit(graph, parents->item);
1007                         assert(par_column >= 0);
1008
1009                         graph_line_write_column(line, &graph->new_columns[par_column], '|');
1010                         for (j = 0; j < graph->num_parents - 1; j++) {
1011                                 parents = next_interesting_parent(graph, parents);
1012                                 assert(parents);
1013                                 par_column = graph_find_new_column_by_commit(graph, parents->item);
1014                                 assert(par_column >= 0);
1015                                 graph_line_write_column(line, &graph->new_columns[par_column], '\\');
1016                                 graph_line_addch(line, ' ');
1017                         }
1018                 } else if (seen_this) {
1019                         graph_line_write_column(line, col, '\\');
1020                         graph_line_addch(line, ' ');
1021                 } else {
1022                         graph_line_write_column(line, col, '|');
1023                         graph_line_addch(line, ' ');
1024                 }
1025         }
1026
1027         /*
1028          * Update graph->state
1029          */
1030         if (graph_is_mapping_correct(graph))
1031                 graph_update_state(graph, GRAPH_PADDING);
1032         else
1033                 graph_update_state(graph, GRAPH_COLLAPSING);
1034 }
1035
1036 static void graph_output_collapsing_line(struct git_graph *graph, struct graph_line *line)
1037 {
1038         int i;
1039         short used_horizontal = 0;
1040         int horizontal_edge = -1;
1041         int horizontal_edge_target = -1;
1042
1043         /*
1044          * Clear out the new_mapping array
1045          */
1046         for (i = 0; i < graph->mapping_size; i++)
1047                 graph->new_mapping[i] = -1;
1048
1049         for (i = 0; i < graph->mapping_size; i++) {
1050                 int target = graph->mapping[i];
1051                 if (target < 0)
1052                         continue;
1053
1054                 /*
1055                  * Since update_columns() always inserts the leftmost
1056                  * column first, each branch's target location should
1057                  * always be either its current location or to the left of
1058                  * its current location.
1059                  *
1060                  * We never have to move branches to the right.  This makes
1061                  * the graph much more legible, since whenever branches
1062                  * cross, only one is moving directions.
1063                  */
1064                 assert(target * 2 <= i);
1065
1066                 if (target * 2 == i) {
1067                         /*
1068                          * This column is already in the
1069                          * correct place
1070                          */
1071                         assert(graph->new_mapping[i] == -1);
1072                         graph->new_mapping[i] = target;
1073                 } else if (graph->new_mapping[i - 1] < 0) {
1074                         /*
1075                          * Nothing is to the left.
1076                          * Move to the left by one
1077                          */
1078                         graph->new_mapping[i - 1] = target;
1079                         /*
1080                          * If there isn't already an edge moving horizontally
1081                          * select this one.
1082                          */
1083                         if (horizontal_edge == -1) {
1084                                 int j;
1085                                 horizontal_edge = i;
1086                                 horizontal_edge_target = target;
1087                                 /*
1088                                  * The variable target is the index of the graph
1089                                  * column, and therefore target*2+3 is the
1090                                  * actual screen column of the first horizontal
1091                                  * line.
1092                                  */
1093                                 for (j = (target * 2)+3; j < (i - 2); j += 2)
1094                                         graph->new_mapping[j] = target;
1095                         }
1096                 } else if (graph->new_mapping[i - 1] == target) {
1097                         /*
1098                          * There is a branch line to our left
1099                          * already, and it is our target.  We
1100                          * combine with this line, since we share
1101                          * the same parent commit.
1102                          *
1103                          * We don't have to add anything to the
1104                          * output or new_mapping, since the
1105                          * existing branch line has already taken
1106                          * care of it.
1107                          */
1108                 } else {
1109                         /*
1110                          * There is a branch line to our left,
1111                          * but it isn't our target.  We need to
1112                          * cross over it.
1113                          *
1114                          * The space just to the left of this
1115                          * branch should always be empty.
1116                          *
1117                          * The branch to the left of that space
1118                          * should be our eventual target.
1119                          */
1120                         assert(graph->new_mapping[i - 1] > target);
1121                         assert(graph->new_mapping[i - 2] < 0);
1122                         assert(graph->new_mapping[i - 3] == target);
1123                         graph->new_mapping[i - 2] = target;
1124                         /*
1125                          * Mark this branch as the horizontal edge to
1126                          * prevent any other edges from moving
1127                          * horizontally.
1128                          */
1129                         if (horizontal_edge == -1)
1130                                 horizontal_edge = i;
1131                 }
1132         }
1133
1134         /*
1135          * The new mapping may be 1 smaller than the old mapping
1136          */
1137         if (graph->new_mapping[graph->mapping_size - 1] < 0)
1138                 graph->mapping_size--;
1139
1140         /*
1141          * Output out a line based on the new mapping info
1142          */
1143         for (i = 0; i < graph->mapping_size; i++) {
1144                 int target = graph->new_mapping[i];
1145                 if (target < 0)
1146                         graph_line_addch(line, ' ');
1147                 else if (target * 2 == i)
1148                         graph_line_write_column(line, &graph->new_columns[target], '|');
1149                 else if (target == horizontal_edge_target &&
1150                          i != horizontal_edge - 1) {
1151                                 /*
1152                                  * Set the mappings for all but the
1153                                  * first segment to -1 so that they
1154                                  * won't continue into the next line.
1155                                  */
1156                                 if (i != (target * 2)+3)
1157                                         graph->new_mapping[i] = -1;
1158                                 used_horizontal = 1;
1159                         graph_line_write_column(line, &graph->new_columns[target], '_');
1160                 } else {
1161                         if (used_horizontal && i < horizontal_edge)
1162                                 graph->new_mapping[i] = -1;
1163                         graph_line_write_column(line, &graph->new_columns[target], '/');
1164
1165                 }
1166         }
1167
1168         /*
1169          * Swap mapping and new_mapping
1170          */
1171         SWAP(graph->mapping, graph->new_mapping);
1172
1173         /*
1174          * If graph->mapping indicates that all of the branch lines
1175          * are already in the correct positions, we are done.
1176          * Otherwise, we need to collapse some branch lines together.
1177          */
1178         if (graph_is_mapping_correct(graph))
1179                 graph_update_state(graph, GRAPH_PADDING);
1180 }
1181
1182 int graph_next_line(struct git_graph *graph, struct strbuf *sb)
1183 {
1184         int shown_commit_line = 0;
1185         struct graph_line line = { .buf = sb, .width = 0 };
1186
1187         /*
1188          * We could conceivable be called with a NULL commit
1189          * if our caller has a bug, and invokes graph_next_line()
1190          * immediately after graph_init(), without first calling
1191          * graph_update().  Return without outputting anything in this
1192          * case.
1193          */
1194         if (!graph->commit)
1195                 return -1;
1196
1197         switch (graph->state) {
1198         case GRAPH_PADDING:
1199                 graph_output_padding_line(graph, &line);
1200                 break;
1201         case GRAPH_SKIP:
1202                 graph_output_skip_line(graph, &line);
1203                 break;
1204         case GRAPH_PRE_COMMIT:
1205                 graph_output_pre_commit_line(graph, &line);
1206                 break;
1207         case GRAPH_COMMIT:
1208                 graph_output_commit_line(graph, &line);
1209                 shown_commit_line = 1;
1210                 break;
1211         case GRAPH_POST_MERGE:
1212                 graph_output_post_merge_line(graph, &line);
1213                 break;
1214         case GRAPH_COLLAPSING:
1215                 graph_output_collapsing_line(graph, &line);
1216                 break;
1217         }
1218
1219         graph_pad_horizontally(graph, &line);
1220         return shown_commit_line;
1221 }
1222
1223 static void graph_padding_line(struct git_graph *graph, struct strbuf *sb)
1224 {
1225         int i;
1226         struct graph_line line = { .buf = sb, .width = 0 };
1227
1228         if (graph->state != GRAPH_COMMIT) {
1229                 graph_next_line(graph, sb);
1230                 return;
1231         }
1232
1233         /*
1234          * Output the row containing this commit
1235          * Iterate up to and including graph->num_columns,
1236          * since the current commit may not be in any of the existing
1237          * columns.  (This happens when the current commit doesn't have any
1238          * children that we have already processed.)
1239          */
1240         for (i = 0; i < graph->num_columns; i++) {
1241                 struct column *col = &graph->columns[i];
1242
1243                 graph_line_write_column(&line, col, '|');
1244
1245                 if (col->commit == graph->commit && graph->num_parents > 2) {
1246                         int len = (graph->num_parents - 2) * 2;
1247                         graph_line_addchars(&line, ' ', len);
1248                 } else {
1249                         graph_line_addch(&line, ' ');
1250                 }
1251         }
1252
1253         graph_pad_horizontally(graph, &line);
1254
1255         /*
1256          * Update graph->prev_state since we have output a padding line
1257          */
1258         graph->prev_state = GRAPH_PADDING;
1259 }
1260
1261 int graph_is_commit_finished(struct git_graph const *graph)
1262 {
1263         return (graph->state == GRAPH_PADDING);
1264 }
1265
1266 void graph_show_commit(struct git_graph *graph)
1267 {
1268         struct strbuf msgbuf = STRBUF_INIT;
1269         int shown_commit_line = 0;
1270
1271         graph_show_line_prefix(default_diffopt);
1272
1273         if (!graph)
1274                 return;
1275
1276         /*
1277          * When showing a diff of a merge against each of its parents, we
1278          * are called once for each parent without graph_update having been
1279          * called.  In this case, simply output a single padding line.
1280          */
1281         if (graph_is_commit_finished(graph)) {
1282                 graph_show_padding(graph);
1283                 shown_commit_line = 1;
1284         }
1285
1286         while (!shown_commit_line && !graph_is_commit_finished(graph)) {
1287                 shown_commit_line = graph_next_line(graph, &msgbuf);
1288                 fwrite(msgbuf.buf, sizeof(char), msgbuf.len,
1289                         graph->revs->diffopt.file);
1290                 if (!shown_commit_line) {
1291                         putc('\n', graph->revs->diffopt.file);
1292                         graph_show_line_prefix(&graph->revs->diffopt);
1293                 }
1294                 strbuf_setlen(&msgbuf, 0);
1295         }
1296
1297         strbuf_release(&msgbuf);
1298 }
1299
1300 void graph_show_oneline(struct git_graph *graph)
1301 {
1302         struct strbuf msgbuf = STRBUF_INIT;
1303
1304         graph_show_line_prefix(default_diffopt);
1305
1306         if (!graph)
1307                 return;
1308
1309         graph_next_line(graph, &msgbuf);
1310         fwrite(msgbuf.buf, sizeof(char), msgbuf.len, graph->revs->diffopt.file);
1311         strbuf_release(&msgbuf);
1312 }
1313
1314 void graph_show_padding(struct git_graph *graph)
1315 {
1316         struct strbuf msgbuf = STRBUF_INIT;
1317
1318         graph_show_line_prefix(default_diffopt);
1319
1320         if (!graph)
1321                 return;
1322
1323         graph_padding_line(graph, &msgbuf);
1324         fwrite(msgbuf.buf, sizeof(char), msgbuf.len, graph->revs->diffopt.file);
1325         strbuf_release(&msgbuf);
1326 }
1327
1328 int graph_show_remainder(struct git_graph *graph)
1329 {
1330         struct strbuf msgbuf = STRBUF_INIT;
1331         int shown = 0;
1332
1333         graph_show_line_prefix(default_diffopt);
1334
1335         if (!graph)
1336                 return 0;
1337
1338         if (graph_is_commit_finished(graph))
1339                 return 0;
1340
1341         for (;;) {
1342                 graph_next_line(graph, &msgbuf);
1343                 fwrite(msgbuf.buf, sizeof(char), msgbuf.len,
1344                         graph->revs->diffopt.file);
1345                 strbuf_setlen(&msgbuf, 0);
1346                 shown = 1;
1347
1348                 if (!graph_is_commit_finished(graph)) {
1349                         putc('\n', graph->revs->diffopt.file);
1350                         graph_show_line_prefix(&graph->revs->diffopt);
1351                 } else {
1352                         break;
1353                 }
1354         }
1355         strbuf_release(&msgbuf);
1356
1357         return shown;
1358 }
1359
1360 static void graph_show_strbuf(struct git_graph *graph,
1361                               FILE *file,
1362                               struct strbuf const *sb)
1363 {
1364         char *p;
1365
1366         /*
1367          * Print the strbuf line by line,
1368          * and display the graph info before each line but the first.
1369          */
1370         p = sb->buf;
1371         while (p) {
1372                 size_t len;
1373                 char *next_p = strchr(p, '\n');
1374                 if (next_p) {
1375                         next_p++;
1376                         len = next_p - p;
1377                 } else {
1378                         len = (sb->buf + sb->len) - p;
1379                 }
1380                 fwrite(p, sizeof(char), len, file);
1381                 if (next_p && *next_p != '\0')
1382                         graph_show_oneline(graph);
1383                 p = next_p;
1384         }
1385 }
1386
1387 void graph_show_commit_msg(struct git_graph *graph,
1388                            FILE *file,
1389                            struct strbuf const *sb)
1390 {
1391         int newline_terminated;
1392
1393         /*
1394          * Show the commit message
1395          */
1396         graph_show_strbuf(graph, file, sb);
1397
1398         if (!graph)
1399                 return;
1400
1401         newline_terminated = (sb->len && sb->buf[sb->len - 1] == '\n');
1402
1403         /*
1404          * If there is more output needed for this commit, show it now
1405          */
1406         if (!graph_is_commit_finished(graph)) {
1407                 /*
1408                  * If sb doesn't have a terminating newline, print one now,
1409                  * so we can start the remainder of the graph output on a
1410                  * new line.
1411                  */
1412                 if (!newline_terminated)
1413                         putc('\n', file);
1414
1415                 graph_show_remainder(graph);
1416
1417                 /*
1418                  * If sb ends with a newline, our output should too.
1419                  */
1420                 if (newline_terminated)
1421                         putc('\n', file);
1422         }
1423 }