Merge branch 'po/remote-set-head-usage'
[git] / line-log.c
1 #include "git-compat-util.h"
2 #include "line-range.h"
3 #include "cache.h"
4 #include "tag.h"
5 #include "blob.h"
6 #include "tree.h"
7 #include "diff.h"
8 #include "commit.h"
9 #include "decorate.h"
10 #include "revision.h"
11 #include "xdiff-interface.h"
12 #include "strbuf.h"
13 #include "log-tree.h"
14 #include "graph.h"
15 #include "userdiff.h"
16 #include "line-log.h"
17
18 static void range_set_grow(struct range_set *rs, size_t extra)
19 {
20         ALLOC_GROW(rs->ranges, rs->nr + extra, rs->alloc);
21 }
22
23 /* Either initialization would be fine */
24 #define RANGE_SET_INIT {0}
25
26 void range_set_init(struct range_set *rs, size_t prealloc)
27 {
28         rs->alloc = rs->nr = 0;
29         rs->ranges = NULL;
30         if (prealloc)
31                 range_set_grow(rs, prealloc);
32 }
33
34 void range_set_release(struct range_set *rs)
35 {
36         free(rs->ranges);
37         rs->alloc = rs->nr = 0;
38         rs->ranges = NULL;
39 }
40
41 /* dst must be uninitialized! */
42 static void range_set_copy(struct range_set *dst, struct range_set *src)
43 {
44         range_set_init(dst, src->nr);
45         memcpy(dst->ranges, src->ranges, src->nr*sizeof(struct range_set));
46         dst->nr = src->nr;
47 }
48 static void range_set_move(struct range_set *dst, struct range_set *src)
49 {
50         range_set_release(dst);
51         dst->ranges = src->ranges;
52         dst->nr = src->nr;
53         dst->alloc = src->alloc;
54         src->ranges = NULL;
55         src->alloc = src->nr = 0;
56 }
57
58 /* tack on a _new_ range _at the end_ */
59 void range_set_append_unsafe(struct range_set *rs, long a, long b)
60 {
61         assert(a <= b);
62         range_set_grow(rs, 1);
63         rs->ranges[rs->nr].start = a;
64         rs->ranges[rs->nr].end = b;
65         rs->nr++;
66 }
67
68 void range_set_append(struct range_set *rs, long a, long b)
69 {
70         assert(rs->nr == 0 || rs->ranges[rs->nr-1].end <= a);
71         range_set_append_unsafe(rs, a, b);
72 }
73
74 static int range_cmp(const void *_r, const void *_s)
75 {
76         const struct range *r = _r;
77         const struct range *s = _s;
78
79         /* this could be simply 'return r.start-s.start', but for the types */
80         if (r->start == s->start)
81                 return 0;
82         if (r->start < s->start)
83                 return -1;
84         return 1;
85 }
86
87 /*
88  * Check that the ranges are non-empty, sorted and non-overlapping
89  */
90 static void range_set_check_invariants(struct range_set *rs)
91 {
92         int i;
93
94         if (!rs)
95                 return;
96
97         if (rs->nr)
98                 assert(rs->ranges[0].start < rs->ranges[0].end);
99
100         for (i = 1; i < rs->nr; i++) {
101                 assert(rs->ranges[i-1].end < rs->ranges[i].start);
102                 assert(rs->ranges[i].start < rs->ranges[i].end);
103         }
104 }
105
106 /*
107  * In-place pass of sorting and merging the ranges in the range set,
108  * to establish the invariants when we get the ranges from the user
109  */
110 void sort_and_merge_range_set(struct range_set *rs)
111 {
112         int i;
113         int o = 0; /* output cursor */
114
115         qsort(rs->ranges, rs->nr, sizeof(struct range), range_cmp);
116
117         for (i = 0; i < rs->nr; i++) {
118                 if (rs->ranges[i].start == rs->ranges[i].end)
119                         continue;
120                 if (o > 0 && rs->ranges[i].start <= rs->ranges[o-1].end) {
121                         if (rs->ranges[o-1].end < rs->ranges[i].end)
122                                 rs->ranges[o-1].end = rs->ranges[i].end;
123                 } else {
124                         rs->ranges[o].start = rs->ranges[i].start;
125                         rs->ranges[o].end = rs->ranges[i].end;
126                         o++;
127                 }
128         }
129         assert(o <= rs->nr);
130         rs->nr = o;
131
132         range_set_check_invariants(rs);
133 }
134
135 /*
136  * Union of range sets (i.e., sets of line numbers).  Used to merge
137  * them when searches meet at a common ancestor.
138  *
139  * This is also where the ranges are consolidated into canonical form:
140  * overlapping and adjacent ranges are merged, and empty ranges are
141  * removed.
142  */
143 static void range_set_union(struct range_set *out,
144                              struct range_set *a, struct range_set *b)
145 {
146         int i = 0, j = 0, o = 0;
147         struct range *ra = a->ranges;
148         struct range *rb = b->ranges;
149         /* cannot make an alias of out->ranges: it may change during grow */
150
151         assert(out->nr == 0);
152         while (i < a->nr || j < b->nr) {
153                 struct range *new;
154                 if (i < a->nr && j < b->nr) {
155                         if (ra[i].start < rb[j].start)
156                                 new = &ra[i++];
157                         else if (ra[i].start > rb[j].start)
158                                 new = &rb[j++];
159                         else if (ra[i].end < rb[j].end)
160                                 new = &ra[i++];
161                         else
162                                 new = &rb[j++];
163                 } else if (i < a->nr)      /* b exhausted */
164                         new = &ra[i++];
165                 else                       /* a exhausted */
166                         new = &rb[j++];
167                 if (new->start == new->end)
168                         ; /* empty range */
169                 else if (!o || out->ranges[o-1].end < new->start) {
170                         range_set_grow(out, 1);
171                         out->ranges[o].start = new->start;
172                         out->ranges[o].end = new->end;
173                         o++;
174                 } else if (out->ranges[o-1].end < new->end) {
175                         out->ranges[o-1].end = new->end;
176                 }
177         }
178         out->nr = o;
179 }
180
181 /*
182  * Difference of range sets (out = a \ b).  Pass the "interesting"
183  * ranges as 'a' and the target side of the diff as 'b': it removes
184  * the ranges for which the commit is responsible.
185  */
186 static void range_set_difference(struct range_set *out,
187                                   struct range_set *a, struct range_set *b)
188 {
189         int i, j =  0;
190         for (i = 0; i < a->nr; i++) {
191                 long start = a->ranges[i].start;
192                 long end = a->ranges[i].end;
193                 while (start < end) {
194                         while (j < b->nr && start >= b->ranges[j].end)
195                                 /*
196                                  * a:         |-------
197                                  * b: ------|
198                                  */
199                                 j++;
200                         if (j >= b->nr || end < b->ranges[j].start) {
201                                 /*
202                                  * b exhausted, or
203                                  * a:  ----|
204                                  * b:         |----
205                                  */
206                                 range_set_append(out, start, end);
207                                 break;
208                         }
209                         if (start >= b->ranges[j].start) {
210                                 /*
211                                  * a:     |--????
212                                  * b: |------|
213                                  */
214                                 start = b->ranges[j].end;
215                         } else if (end > b->ranges[j].start) {
216                                 /*
217                                  * a: |-----|
218                                  * b:    |--?????
219                                  */
220                                 if (start < b->ranges[j].start)
221                                         range_set_append(out, start, b->ranges[j].start);
222                                 start = b->ranges[j].end;
223                         }
224                 }
225         }
226 }
227
228 static void diff_ranges_init(struct diff_ranges *diff)
229 {
230         range_set_init(&diff->parent, 0);
231         range_set_init(&diff->target, 0);
232 }
233
234 static void diff_ranges_release(struct diff_ranges *diff)
235 {
236         range_set_release(&diff->parent);
237         range_set_release(&diff->target);
238 }
239
240 void line_log_data_init(struct line_log_data *r)
241 {
242         memset(r, 0, sizeof(struct line_log_data));
243         range_set_init(&r->ranges, 0);
244 }
245
246 static void line_log_data_clear(struct line_log_data *r)
247 {
248         range_set_release(&r->ranges);
249         if (r->pair)
250                 diff_free_filepair(r->pair);
251 }
252
253 static void free_line_log_data(struct line_log_data *r)
254 {
255         while (r) {
256                 struct line_log_data *next = r->next;
257                 line_log_data_clear(r);
258                 free(r);
259                 r = next;
260         }
261 }
262
263 static struct line_log_data *
264 search_line_log_data(struct line_log_data *list, const char *path,
265                      struct line_log_data **insertion_point)
266 {
267         struct line_log_data *p = list;
268         if (insertion_point)
269                 *insertion_point = NULL;
270         while (p) {
271                 int cmp = strcmp(p->path, path);
272                 if (!cmp)
273                         return p;
274                 if (insertion_point && cmp < 0)
275                         *insertion_point = p;
276                 p = p->next;
277         }
278         return NULL;
279 }
280
281 /*
282  * Note: takes ownership of 'path', which happens to be what the only
283  * caller needs.
284  */
285 static void line_log_data_insert(struct line_log_data **list,
286                                  char *path,
287                                  long begin, long end)
288 {
289         struct line_log_data *ip;
290         struct line_log_data *p = search_line_log_data(*list, path, &ip);
291
292         if (p) {
293                 range_set_append_unsafe(&p->ranges, begin, end);
294                 free(path);
295                 return;
296         }
297
298         p = xcalloc(1, sizeof(struct line_log_data));
299         p->path = path;
300         range_set_append(&p->ranges, begin, end);
301         if (ip) {
302                 p->next = ip->next;
303                 ip->next = p;
304         } else {
305                 p->next = *list;
306                 *list = p;
307         }
308 }
309
310 struct collect_diff_cbdata {
311         struct diff_ranges *diff;
312 };
313
314 static int collect_diff_cb(long start_a, long count_a,
315                            long start_b, long count_b,
316                            void *data)
317 {
318         struct collect_diff_cbdata *d = data;
319
320         if (count_a >= 0)
321                 range_set_append(&d->diff->parent, start_a, start_a + count_a);
322         if (count_b >= 0)
323                 range_set_append(&d->diff->target, start_b, start_b + count_b);
324
325         return 0;
326 }
327
328 static void collect_diff(mmfile_t *parent, mmfile_t *target, struct diff_ranges *out)
329 {
330         struct collect_diff_cbdata cbdata = {NULL};
331         xpparam_t xpp;
332         xdemitconf_t xecfg;
333         xdemitcb_t ecb;
334
335         memset(&xpp, 0, sizeof(xpp));
336         memset(&xecfg, 0, sizeof(xecfg));
337         xecfg.ctxlen = xecfg.interhunkctxlen = 0;
338
339         cbdata.diff = out;
340         xecfg.hunk_func = collect_diff_cb;
341         memset(&ecb, 0, sizeof(ecb));
342         ecb.priv = &cbdata;
343         xdi_diff(parent, target, &xpp, &xecfg, &ecb);
344 }
345
346 /*
347  * These are handy for debugging.  Removing them with #if 0 silences
348  * the "unused function" warning.
349  */
350 #if 0
351 static void dump_range_set(struct range_set *rs, const char *desc)
352 {
353         int i;
354         printf("range set %s (%d items):\n", desc, rs->nr);
355         for (i = 0; i < rs->nr; i++)
356                 printf("\t[%ld,%ld]\n", rs->ranges[i].start, rs->ranges[i].end);
357 }
358
359 static void dump_line_log_data(struct line_log_data *r)
360 {
361         char buf[4096];
362         while (r) {
363                 snprintf(buf, 4096, "file %s\n", r->path);
364                 dump_range_set(&r->ranges, buf);
365                 r = r->next;
366         }
367 }
368
369 static void dump_diff_ranges(struct diff_ranges *diff, const char *desc)
370 {
371         int i;
372         assert(diff->parent.nr == diff->target.nr);
373         printf("diff ranges %s (%d items):\n", desc, diff->parent.nr);
374         printf("\tparent\ttarget\n");
375         for (i = 0; i < diff->parent.nr; i++) {
376                 printf("\t[%ld,%ld]\t[%ld,%ld]\n",
377                        diff->parent.ranges[i].start,
378                        diff->parent.ranges[i].end,
379                        diff->target.ranges[i].start,
380                        diff->target.ranges[i].end);
381         }
382 }
383 #endif
384
385
386 static int ranges_overlap(struct range *a, struct range *b)
387 {
388         return !(a->end <= b->start || b->end <= a->start);
389 }
390
391 /*
392  * Given a diff and the set of interesting ranges, determine all hunks
393  * of the diff which touch (overlap) at least one of the interesting
394  * ranges in the target.
395  */
396 static void diff_ranges_filter_touched(struct diff_ranges *out,
397                                        struct diff_ranges *diff,
398                                        struct range_set *rs)
399 {
400         int i, j = 0;
401
402         assert(out->target.nr == 0);
403
404         for (i = 0; i < diff->target.nr; i++) {
405                 while (diff->target.ranges[i].start > rs->ranges[j].end) {
406                         j++;
407                         if (j == rs->nr)
408                                 return;
409                 }
410                 if (ranges_overlap(&diff->target.ranges[i], &rs->ranges[j])) {
411                         range_set_append(&out->parent,
412                                          diff->parent.ranges[i].start,
413                                          diff->parent.ranges[i].end);
414                         range_set_append(&out->target,
415                                          diff->target.ranges[i].start,
416                                          diff->target.ranges[i].end);
417                 }
418         }
419 }
420
421 /*
422  * Adjust the line counts in 'rs' to account for the lines
423  * added/removed in the diff.
424  */
425 static void range_set_shift_diff(struct range_set *out,
426                                  struct range_set *rs,
427                                  struct diff_ranges *diff)
428 {
429         int i, j = 0;
430         long offset = 0;
431         struct range *src = rs->ranges;
432         struct range *target = diff->target.ranges;
433         struct range *parent = diff->parent.ranges;
434
435         for (i = 0; i < rs->nr; i++) {
436                 while (j < diff->target.nr && src[i].start >= target[j].start) {
437                         offset += (parent[j].end-parent[j].start)
438                                 - (target[j].end-target[j].start);
439                         j++;
440                 }
441                 range_set_append(out, src[i].start+offset, src[i].end+offset);
442         }
443 }
444
445 /*
446  * Given a diff and the set of interesting ranges, map the ranges
447  * across the diff.  That is: observe that the target commit takes
448  * blame for all the + (target-side) ranges.  So for every pair of
449  * ranges in the diff that was touched, we remove the latter and add
450  * its parent side.
451  */
452 static void range_set_map_across_diff(struct range_set *out,
453                                       struct range_set *rs,
454                                       struct diff_ranges *diff,
455                                       struct diff_ranges **touched_out)
456 {
457         struct diff_ranges *touched = xmalloc(sizeof(*touched));
458         struct range_set tmp1 = RANGE_SET_INIT;
459         struct range_set tmp2 = RANGE_SET_INIT;
460
461         diff_ranges_init(touched);
462         diff_ranges_filter_touched(touched, diff, rs);
463         range_set_difference(&tmp1, rs, &touched->target);
464         range_set_shift_diff(&tmp2, &tmp1, diff);
465         range_set_union(out, &tmp2, &touched->parent);
466         range_set_release(&tmp1);
467         range_set_release(&tmp2);
468
469         *touched_out = touched;
470 }
471
472 static struct commit *check_single_commit(struct rev_info *revs)
473 {
474         struct object *commit = NULL;
475         int found = -1;
476         int i;
477
478         for (i = 0; i < revs->pending.nr; i++) {
479                 struct object *obj = revs->pending.objects[i].item;
480                 if (obj->flags & UNINTERESTING)
481                         continue;
482                 while (obj->type == OBJ_TAG)
483                         obj = deref_tag(obj, NULL, 0);
484                 if (obj->type != OBJ_COMMIT)
485                         die("Non commit %s?", revs->pending.objects[i].name);
486                 if (commit)
487                         die("More than one commit to dig from: %s and %s?",
488                             revs->pending.objects[i].name,
489                             revs->pending.objects[found].name);
490                 commit = obj;
491                 found = i;
492         }
493
494         if (!commit)
495                 die("No commit specified?");
496
497         return (struct commit *) commit;
498 }
499
500 static void fill_blob_sha1(struct commit *commit, struct diff_filespec *spec)
501 {
502         unsigned mode;
503         unsigned char sha1[20];
504
505         if (get_tree_entry(commit->object.sha1, spec->path,
506                            sha1, &mode))
507                 die("There is no path %s in the commit", spec->path);
508         fill_filespec(spec, sha1, 1, mode);
509
510         return;
511 }
512
513 static void fill_line_ends(struct diff_filespec *spec, long *lines,
514                            unsigned long **line_ends)
515 {
516         int num = 0, size = 50;
517         long cur = 0;
518         unsigned long *ends = NULL;
519         char *data = NULL;
520
521         if (diff_populate_filespec(spec, 0))
522                 die("Cannot read blob %s", sha1_to_hex(spec->sha1));
523
524         ends = xmalloc(size * sizeof(*ends));
525         ends[cur++] = 0;
526         data = spec->data;
527         while (num < spec->size) {
528                 if (data[num] == '\n' || num == spec->size - 1) {
529                         ALLOC_GROW(ends, (cur + 1), size);
530                         ends[cur++] = num;
531                 }
532                 num++;
533         }
534
535         /* shrink the array to fit the elements */
536         ends = xrealloc(ends, cur * sizeof(*ends));
537         *lines = cur-1;
538         *line_ends = ends;
539 }
540
541 struct nth_line_cb {
542         struct diff_filespec *spec;
543         long lines;
544         unsigned long *line_ends;
545 };
546
547 static const char *nth_line(void *data, long line)
548 {
549         struct nth_line_cb *d = data;
550         assert(d && line <= d->lines);
551         assert(d->spec && d->spec->data);
552
553         if (line == 0)
554                 return (char *)d->spec->data;
555         else
556                 return (char *)d->spec->data + d->line_ends[line] + 1;
557 }
558
559 static struct line_log_data *
560 parse_lines(struct commit *commit, const char *prefix, struct string_list *args)
561 {
562         long lines = 0;
563         unsigned long *ends = NULL;
564         struct nth_line_cb cb_data;
565         struct string_list_item *item;
566         struct line_log_data *ranges = NULL;
567         struct line_log_data *p;
568
569         for_each_string_list_item(item, args) {
570                 const char *name_part, *range_part;
571                 char *full_name;
572                 struct diff_filespec *spec;
573                 long begin = 0, end = 0;
574                 long anchor;
575
576                 name_part = skip_range_arg(item->string);
577                 if (!name_part || *name_part != ':' || !name_part[1])
578                         die("-L argument '%s' not of the form start,end:file",
579                             item->string);
580                 range_part = xstrndup(item->string, name_part - item->string);
581                 name_part++;
582
583                 full_name = prefix_path(prefix, prefix ? strlen(prefix) : 0,
584                                         name_part);
585
586                 spec = alloc_filespec(full_name);
587                 fill_blob_sha1(commit, spec);
588                 fill_line_ends(spec, &lines, &ends);
589                 cb_data.spec = spec;
590                 cb_data.lines = lines;
591                 cb_data.line_ends = ends;
592
593                 p = search_line_log_data(ranges, full_name, NULL);
594                 if (p && p->ranges.nr)
595                         anchor = p->ranges.ranges[p->ranges.nr - 1].end + 1;
596                 else
597                         anchor = 1;
598
599                 if (parse_range_arg(range_part, nth_line, &cb_data,
600                                     lines, anchor, &begin, &end,
601                                     full_name))
602                         die("malformed -L argument '%s'", range_part);
603                 if (lines < end || ((lines || begin) && lines < begin))
604                         die("file %s has only %lu lines", name_part, lines);
605                 if (begin < 1)
606                         begin = 1;
607                 if (end < 1)
608                         end = lines;
609                 begin--;
610                 line_log_data_insert(&ranges, full_name, begin, end);
611
612                 free_filespec(spec);
613                 free(ends);
614                 ends = NULL;
615         }
616
617         for (p = ranges; p; p = p->next)
618                 sort_and_merge_range_set(&p->ranges);
619
620         return ranges;
621 }
622
623 static struct line_log_data *line_log_data_copy_one(struct line_log_data *r)
624 {
625         struct line_log_data *ret = xmalloc(sizeof(*ret));
626
627         assert(r);
628         line_log_data_init(ret);
629         range_set_copy(&ret->ranges, &r->ranges);
630
631         ret->path = xstrdup(r->path);
632
633         return ret;
634 }
635
636 static struct line_log_data *
637 line_log_data_copy(struct line_log_data *r)
638 {
639         struct line_log_data *ret = NULL;
640         struct line_log_data *tmp = NULL, *prev = NULL;
641
642         assert(r);
643         ret = tmp = prev = line_log_data_copy_one(r);
644         r = r->next;
645         while (r) {
646                 tmp = line_log_data_copy_one(r);
647                 prev->next = tmp;
648                 prev = tmp;
649                 r = r->next;
650         }
651
652         return ret;
653 }
654
655 /* merge two range sets across files */
656 static struct line_log_data *line_log_data_merge(struct line_log_data *a,
657                                                  struct line_log_data *b)
658 {
659         struct line_log_data *head = NULL, **pp = &head;
660
661         while (a || b) {
662                 struct line_log_data *src;
663                 struct line_log_data *src2 = NULL;
664                 struct line_log_data *d;
665                 int cmp;
666                 if (!a)
667                         cmp = 1;
668                 else if (!b)
669                         cmp = -1;
670                 else
671                         cmp = strcmp(a->path, b->path);
672                 if (cmp < 0) {
673                         src = a;
674                         a = a->next;
675                 } else if (cmp == 0) {
676                         src = a;
677                         a = a->next;
678                         src2 = b;
679                         b = b->next;
680                 } else {
681                         src = b;
682                         b = b->next;
683                 }
684                 d = xmalloc(sizeof(struct line_log_data));
685                 line_log_data_init(d);
686                 d->path = xstrdup(src->path);
687                 *pp = d;
688                 pp = &d->next;
689                 if (src2)
690                         range_set_union(&d->ranges, &src->ranges, &src2->ranges);
691                 else
692                         range_set_copy(&d->ranges, &src->ranges);
693         }
694
695         return head;
696 }
697
698 static void add_line_range(struct rev_info *revs, struct commit *commit,
699                            struct line_log_data *range)
700 {
701         struct line_log_data *old = NULL;
702         struct line_log_data *new = NULL;
703
704         old = lookup_decoration(&revs->line_log_data, &commit->object);
705         if (old && range) {
706                 new = line_log_data_merge(old, range);
707                 free_line_log_data(old);
708         } else if (range)
709                 new = line_log_data_copy(range);
710
711         if (new)
712                 add_decoration(&revs->line_log_data, &commit->object, new);
713 }
714
715 static void clear_commit_line_range(struct rev_info *revs, struct commit *commit)
716 {
717         struct line_log_data *r;
718         r = lookup_decoration(&revs->line_log_data, &commit->object);
719         if (!r)
720                 return;
721         free_line_log_data(r);
722         add_decoration(&revs->line_log_data, &commit->object, NULL);
723 }
724
725 static struct line_log_data *lookup_line_range(struct rev_info *revs,
726                                                struct commit *commit)
727 {
728         struct line_log_data *ret = NULL;
729         struct line_log_data *d;
730
731         ret = lookup_decoration(&revs->line_log_data, &commit->object);
732
733         for (d = ret; d; d = d->next)
734                 range_set_check_invariants(&d->ranges);
735
736         return ret;
737 }
738
739 void line_log_init(struct rev_info *rev, const char *prefix, struct string_list *args)
740 {
741         struct commit *commit = NULL;
742         struct line_log_data *range;
743
744         commit = check_single_commit(rev);
745         range = parse_lines(commit, prefix, args);
746         add_line_range(rev, commit, range);
747
748         if (!rev->diffopt.detect_rename) {
749                 int i, count = 0;
750                 struct line_log_data *r = range;
751                 const char **paths;
752                 while (r) {
753                         count++;
754                         r = r->next;
755                 }
756                 paths = xmalloc((count+1)*sizeof(char *));
757                 r = range;
758                 for (i = 0; i < count; i++) {
759                         paths[i] = xstrdup(r->path);
760                         r = r->next;
761                 }
762                 paths[count] = NULL;
763                 parse_pathspec(&rev->diffopt.pathspec, 0, 0, "", paths);
764                 free(paths);
765         }
766 }
767
768 static void load_tree_desc(struct tree_desc *desc, void **tree,
769                            const unsigned char *sha1)
770 {
771         unsigned long size;
772         *tree = read_object_with_reference(sha1, tree_type, &size, NULL);
773         if (!*tree)
774                 die("Unable to read tree (%s)", sha1_to_hex(sha1));
775         init_tree_desc(desc, *tree, size);
776 }
777
778 static int count_parents(struct commit *commit)
779 {
780         struct commit_list *parents = commit->parents;
781         int count = 0;
782         while (parents) {
783                 count++;
784                 parents = parents->next;
785         }
786         return count;
787 }
788
789 static void move_diff_queue(struct diff_queue_struct *dst,
790                             struct diff_queue_struct *src)
791 {
792         assert(src != dst);
793         memcpy(dst, src, sizeof(struct diff_queue_struct));
794         DIFF_QUEUE_CLEAR(src);
795 }
796
797 static void filter_diffs_for_paths(struct line_log_data *range, int keep_deletions)
798 {
799         int i;
800         struct diff_queue_struct outq;
801         DIFF_QUEUE_CLEAR(&outq);
802
803         for (i = 0; i < diff_queued_diff.nr; i++) {
804                 struct diff_filepair *p = diff_queued_diff.queue[i];
805                 struct line_log_data *rg = NULL;
806
807                 if (!DIFF_FILE_VALID(p->two)) {
808                         if (keep_deletions)
809                                 diff_q(&outq, p);
810                         else
811                                 diff_free_filepair(p);
812                         continue;
813                 }
814                 for (rg = range; rg; rg = rg->next) {
815                         if (!strcmp(rg->path, p->two->path))
816                                 break;
817                 }
818                 if (rg)
819                         diff_q(&outq, p);
820                 else
821                         diff_free_filepair(p);
822         }
823         free(diff_queued_diff.queue);
824         diff_queued_diff = outq;
825 }
826
827 static inline int diff_might_be_rename(void)
828 {
829         int i;
830         for (i = 0; i < diff_queued_diff.nr; i++)
831                 if (!DIFF_FILE_VALID(diff_queued_diff.queue[i]->one)) {
832                         /* fprintf(stderr, "diff_might_be_rename found creation of: %s\n", */
833                         /*      diff_queued_diff.queue[i]->two->path); */
834                         return 1;
835                 }
836         return 0;
837 }
838
839 static void queue_diffs(struct line_log_data *range,
840                         struct diff_options *opt,
841                         struct diff_queue_struct *queue,
842                         struct commit *commit, struct commit *parent)
843 {
844         void *tree1 = NULL, *tree2 = NULL;
845         struct tree_desc desc1, desc2;
846
847         assert(commit);
848         load_tree_desc(&desc2, &tree2, commit->tree->object.sha1);
849         if (parent)
850                 load_tree_desc(&desc1, &tree1, parent->tree->object.sha1);
851         else
852                 init_tree_desc(&desc1, "", 0);
853
854         DIFF_QUEUE_CLEAR(&diff_queued_diff);
855         diff_tree(&desc1, &desc2, "", opt);
856         if (opt->detect_rename) {
857                 filter_diffs_for_paths(range, 1);
858                 if (diff_might_be_rename())
859                         diffcore_std(opt);
860                 filter_diffs_for_paths(range, 0);
861         }
862         move_diff_queue(queue, &diff_queued_diff);
863
864         if (tree1)
865                 free(tree1);
866         if (tree2)
867                 free(tree2);
868 }
869
870 static char *get_nth_line(long line, unsigned long *ends, void *data)
871 {
872         if (line == 0)
873                 return (char *)data;
874         else
875                 return (char *)data + ends[line] + 1;
876 }
877
878 static void print_line(const char *prefix, char first,
879                        long line, unsigned long *ends, void *data,
880                        const char *color, const char *reset)
881 {
882         char *begin = get_nth_line(line, ends, data);
883         char *end = get_nth_line(line+1, ends, data);
884         int had_nl = 0;
885
886         if (end > begin && end[-1] == '\n') {
887                 end--;
888                 had_nl = 1;
889         }
890
891         fputs(prefix, stdout);
892         fputs(color, stdout);
893         putchar(first);
894         fwrite(begin, 1, end-begin, stdout);
895         fputs(reset, stdout);
896         putchar('\n');
897         if (!had_nl)
898                 fputs("\\ No newline at end of file\n", stdout);
899 }
900
901 static char *output_prefix(struct diff_options *opt)
902 {
903         char *prefix = "";
904
905         if (opt->output_prefix) {
906                 struct strbuf *sb = opt->output_prefix(opt, opt->output_prefix_data);
907                 prefix = sb->buf;
908         }
909
910         return prefix;
911 }
912
913 static void dump_diff_hacky_one(struct rev_info *rev, struct line_log_data *range)
914 {
915         int i, j = 0;
916         long p_lines, t_lines;
917         unsigned long *p_ends = NULL, *t_ends = NULL;
918         struct diff_filepair *pair = range->pair;
919         struct diff_ranges *diff = &range->diff;
920
921         struct diff_options *opt = &rev->diffopt;
922         char *prefix = output_prefix(opt);
923         const char *c_reset = diff_get_color(opt->use_color, DIFF_RESET);
924         const char *c_frag = diff_get_color(opt->use_color, DIFF_FRAGINFO);
925         const char *c_meta = diff_get_color(opt->use_color, DIFF_METAINFO);
926         const char *c_old = diff_get_color(opt->use_color, DIFF_FILE_OLD);
927         const char *c_new = diff_get_color(opt->use_color, DIFF_FILE_NEW);
928         const char *c_plain = diff_get_color(opt->use_color, DIFF_PLAIN);
929
930         if (!pair || !diff)
931                 return;
932
933         if (pair->one->sha1_valid)
934                 fill_line_ends(pair->one, &p_lines, &p_ends);
935         fill_line_ends(pair->two, &t_lines, &t_ends);
936
937         printf("%s%sdiff --git a/%s b/%s%s\n", prefix, c_meta, pair->one->path, pair->two->path, c_reset);
938         printf("%s%s--- %s%s%s\n", prefix, c_meta,
939                pair->one->sha1_valid ? "a/" : "",
940                pair->one->sha1_valid ? pair->one->path : "/dev/null",
941                c_reset);
942         printf("%s%s+++ b/%s%s\n", prefix, c_meta, pair->two->path, c_reset);
943         for (i = 0; i < range->ranges.nr; i++) {
944                 long p_start, p_end;
945                 long t_start = range->ranges.ranges[i].start;
946                 long t_end = range->ranges.ranges[i].end;
947                 long t_cur = t_start;
948                 int j_last;
949
950                 while (j < diff->target.nr && diff->target.ranges[j].end < t_start)
951                         j++;
952                 if (j == diff->target.nr || diff->target.ranges[j].start > t_end)
953                         continue;
954
955                 /* Scan ahead to determine the last diff that falls in this range */
956                 j_last = j;
957                 while (j_last < diff->target.nr && diff->target.ranges[j_last].start < t_end)
958                         j_last++;
959                 if (j_last > j)
960                         j_last--;
961
962                 /*
963                  * Compute parent hunk headers: we know that the diff
964                  * has the correct line numbers (but not all hunks).
965                  * So it suffices to shift the start/end according to
966                  * the line numbers of the first/last hunk(s) that
967                  * fall in this range.
968                  */
969                 if (t_start < diff->target.ranges[j].start)
970                         p_start = diff->parent.ranges[j].start - (diff->target.ranges[j].start-t_start);
971                 else
972                         p_start = diff->parent.ranges[j].start;
973                 if (t_end > diff->target.ranges[j_last].end)
974                         p_end = diff->parent.ranges[j_last].end + (t_end-diff->target.ranges[j_last].end);
975                 else
976                         p_end = diff->parent.ranges[j_last].end;
977
978                 if (!p_start && !p_end) {
979                         p_start = -1;
980                         p_end = -1;
981                 }
982
983                 /* Now output a diff hunk for this range */
984                 printf("%s%s@@ -%ld,%ld +%ld,%ld @@%s\n",
985                        prefix, c_frag,
986                        p_start+1, p_end-p_start, t_start+1, t_end-t_start,
987                        c_reset);
988                 while (j < diff->target.nr && diff->target.ranges[j].start < t_end) {
989                         int k;
990                         for (; t_cur < diff->target.ranges[j].start; t_cur++)
991                                 print_line(prefix, ' ', t_cur, t_ends, pair->two->data,
992                                            c_plain, c_reset);
993                         for (k = diff->parent.ranges[j].start; k < diff->parent.ranges[j].end; k++)
994                                 print_line(prefix, '-', k, p_ends, pair->one->data,
995                                            c_old, c_reset);
996                         for (; t_cur < diff->target.ranges[j].end && t_cur < t_end; t_cur++)
997                                 print_line(prefix, '+', t_cur, t_ends, pair->two->data,
998                                            c_new, c_reset);
999                         j++;
1000                 }
1001                 for (; t_cur < t_end; t_cur++)
1002                         print_line(prefix, ' ', t_cur, t_ends, pair->two->data,
1003                                    c_plain, c_reset);
1004         }
1005
1006         free(p_ends);
1007         free(t_ends);
1008 }
1009
1010 /*
1011  * NEEDSWORK: manually building a diff here is not the Right
1012  * Thing(tm).  log -L should be built into the diff pipeline.
1013  */
1014 static void dump_diff_hacky(struct rev_info *rev, struct line_log_data *range)
1015 {
1016         puts(output_prefix(&rev->diffopt));
1017         while (range) {
1018                 dump_diff_hacky_one(rev, range);
1019                 range = range->next;
1020         }
1021 }
1022
1023 /*
1024  * Unlike most other functions, this destructively operates on
1025  * 'range'.
1026  */
1027 static int process_diff_filepair(struct rev_info *rev,
1028                                  struct diff_filepair *pair,
1029                                  struct line_log_data *range,
1030                                  struct diff_ranges **diff_out)
1031 {
1032         struct line_log_data *rg = range;
1033         struct range_set tmp;
1034         struct diff_ranges diff;
1035         mmfile_t file_parent, file_target;
1036
1037         assert(pair->two->path);
1038         while (rg) {
1039                 assert(rg->path);
1040                 if (!strcmp(rg->path, pair->two->path))
1041                         break;
1042                 rg = rg->next;
1043         }
1044
1045         if (!rg)
1046                 return 0;
1047         if (rg->ranges.nr == 0)
1048                 return 0;
1049
1050         assert(pair->two->sha1_valid);
1051         diff_populate_filespec(pair->two, 0);
1052         file_target.ptr = pair->two->data;
1053         file_target.size = pair->two->size;
1054
1055         if (pair->one->sha1_valid) {
1056                 diff_populate_filespec(pair->one, 0);
1057                 file_parent.ptr = pair->one->data;
1058                 file_parent.size = pair->one->size;
1059         } else {
1060                 file_parent.ptr = "";
1061                 file_parent.size = 0;
1062         }
1063
1064         diff_ranges_init(&diff);
1065         collect_diff(&file_parent, &file_target, &diff);
1066
1067         /* NEEDSWORK should apply some heuristics to prevent mismatches */
1068         free(rg->path);
1069         rg->path = xstrdup(pair->one->path);
1070
1071         range_set_init(&tmp, 0);
1072         range_set_map_across_diff(&tmp, &rg->ranges, &diff, diff_out);
1073         range_set_release(&rg->ranges);
1074         range_set_move(&rg->ranges, &tmp);
1075
1076         diff_ranges_release(&diff);
1077
1078         return ((*diff_out)->parent.nr > 0);
1079 }
1080
1081 static struct diff_filepair *diff_filepair_dup(struct diff_filepair *pair)
1082 {
1083         struct diff_filepair *new = xmalloc(sizeof(struct diff_filepair));
1084         new->one = pair->one;
1085         new->two = pair->two;
1086         new->one->count++;
1087         new->two->count++;
1088         return new;
1089 }
1090
1091 static void free_diffqueues(int n, struct diff_queue_struct *dq)
1092 {
1093         int i, j;
1094         for (i = 0; i < n; i++)
1095                 for (j = 0; j < dq[i].nr; j++)
1096                         diff_free_filepair(dq[i].queue[j]);
1097         free(dq);
1098 }
1099
1100 static int process_all_files(struct line_log_data **range_out,
1101                              struct rev_info *rev,
1102                              struct diff_queue_struct *queue,
1103                              struct line_log_data *range)
1104 {
1105         int i, changed = 0;
1106
1107         *range_out = line_log_data_copy(range);
1108
1109         for (i = 0; i < queue->nr; i++) {
1110                 struct diff_ranges *pairdiff = NULL;
1111                 struct diff_filepair *pair = queue->queue[i];
1112                 if (process_diff_filepair(rev, pair, *range_out, &pairdiff)) {
1113                         /*
1114                          * Store away the diff for later output.  We
1115                          * tuck it in the ranges we got as _input_,
1116                          * since that's the commit that caused the
1117                          * diff.
1118                          *
1119                          * NEEDSWORK not enough when we get around to
1120                          * doing something interesting with merges;
1121                          * currently each invocation on a merge parent
1122                          * trashes the previous one's diff.
1123                          *
1124                          * NEEDSWORK tramples over data structures not owned here
1125                          */
1126                         struct line_log_data *rg = range;
1127                         changed++;
1128                         while (rg && strcmp(rg->path, pair->two->path))
1129                                 rg = rg->next;
1130                         assert(rg);
1131                         rg->pair = diff_filepair_dup(queue->queue[i]);
1132                         memcpy(&rg->diff, pairdiff, sizeof(struct diff_ranges));
1133                 }
1134         }
1135
1136         return changed;
1137 }
1138
1139 int line_log_print(struct rev_info *rev, struct commit *commit)
1140 {
1141         struct line_log_data *range = lookup_line_range(rev, commit);
1142
1143         show_log(rev);
1144         dump_diff_hacky(rev, range);
1145         return 1;
1146 }
1147
1148 static int process_ranges_ordinary_commit(struct rev_info *rev, struct commit *commit,
1149                                           struct line_log_data *range)
1150 {
1151         struct commit *parent = NULL;
1152         struct diff_queue_struct queue;
1153         struct line_log_data *parent_range;
1154         int changed;
1155
1156         if (commit->parents)
1157                 parent = commit->parents->item;
1158
1159         queue_diffs(range, &rev->diffopt, &queue, commit, parent);
1160         changed = process_all_files(&parent_range, rev, &queue, range);
1161         if (parent)
1162                 add_line_range(rev, parent, parent_range);
1163         return changed;
1164 }
1165
1166 static int process_ranges_merge_commit(struct rev_info *rev, struct commit *commit,
1167                                        struct line_log_data *range)
1168 {
1169         struct diff_queue_struct *diffqueues;
1170         struct line_log_data **cand;
1171         struct commit **parents;
1172         struct commit_list *p;
1173         int i;
1174         int nparents = count_parents(commit);
1175
1176         diffqueues = xmalloc(nparents * sizeof(*diffqueues));
1177         cand = xmalloc(nparents * sizeof(*cand));
1178         parents = xmalloc(nparents * sizeof(*parents));
1179
1180         p = commit->parents;
1181         for (i = 0; i < nparents; i++) {
1182                 parents[i] = p->item;
1183                 p = p->next;
1184                 queue_diffs(range, &rev->diffopt, &diffqueues[i], commit, parents[i]);
1185         }
1186
1187         for (i = 0; i < nparents; i++) {
1188                 int changed;
1189                 cand[i] = NULL;
1190                 changed = process_all_files(&cand[i], rev, &diffqueues[i], range);
1191                 if (!changed) {
1192                         /*
1193                          * This parent can take all the blame, so we
1194                          * don't follow any other path in history
1195                          */
1196                         add_line_range(rev, parents[i], cand[i]);
1197                         clear_commit_line_range(rev, commit);
1198                         commit->parents = xmalloc(sizeof(struct commit_list));
1199                         commit->parents->item = parents[i];
1200                         commit->parents->next = NULL;
1201                         free(parents);
1202                         free(cand);
1203                         free_diffqueues(nparents, diffqueues);
1204                         /* NEEDSWORK leaking like a sieve */
1205                         return 0;
1206                 }
1207         }
1208
1209         /*
1210          * No single parent took the blame.  We add the candidates
1211          * from the above loop to the parents.
1212          */
1213         for (i = 0; i < nparents; i++) {
1214                 add_line_range(rev, parents[i], cand[i]);
1215         }
1216
1217         clear_commit_line_range(rev, commit);
1218         free(parents);
1219         free(cand);
1220         free_diffqueues(nparents, diffqueues);
1221         return 1;
1222
1223         /* NEEDSWORK evil merge detection stuff */
1224         /* NEEDSWORK leaking like a sieve */
1225 }
1226
1227 static int process_ranges_arbitrary_commit(struct rev_info *rev, struct commit *commit)
1228 {
1229         struct line_log_data *range = lookup_line_range(rev, commit);
1230         int changed = 0;
1231
1232         if (range) {
1233                 if (!commit->parents || !commit->parents->next)
1234                         changed = process_ranges_ordinary_commit(rev, commit, range);
1235                 else
1236                         changed = process_ranges_merge_commit(rev, commit, range);
1237         }
1238
1239         if (!changed)
1240                 commit->object.flags |= TREESAME;
1241
1242         return changed;
1243 }
1244
1245 static enum rewrite_result line_log_rewrite_one(struct rev_info *rev, struct commit **pp)
1246 {
1247         for (;;) {
1248                 struct commit *p = *pp;
1249                 if (p->parents && p->parents->next)
1250                         return rewrite_one_ok;
1251                 if (p->object.flags & UNINTERESTING)
1252                         return rewrite_one_ok;
1253                 if (!(p->object.flags & TREESAME))
1254                         return rewrite_one_ok;
1255                 if (!p->parents)
1256                         return rewrite_one_noparents;
1257                 *pp = p->parents->item;
1258         }
1259 }
1260
1261 int line_log_filter(struct rev_info *rev)
1262 {
1263         struct commit *commit;
1264         struct commit_list *list = rev->commits;
1265         struct commit_list *out = NULL, **pp = &out;
1266
1267         while (list) {
1268                 struct commit_list *to_free = NULL;
1269                 commit = list->item;
1270                 if (process_ranges_arbitrary_commit(rev, commit)) {
1271                         *pp = list;
1272                         pp = &list->next;
1273                 } else
1274                         to_free = list;
1275                 list = list->next;
1276                 free(to_free);
1277         }
1278         *pp = NULL;
1279
1280         for (list = out; list; list = list->next)
1281                 rewrite_parents(rev, list->item, line_log_rewrite_one);
1282
1283         rev->commits = out;
1284
1285         return 0;
1286 }