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