]> git.ipfire.org Git - thirdparty/git.git/blame - diff.c
Merge branch 'master' into js/fmt-patch
[thirdparty/git.git] / diff.c
CommitLineData
6973dcae
JH
1/*
2 * Copyright (C) 2005 Junio C Hamano
3 */
4#include <sys/types.h>
5#include <sys/wait.h>
6#include <signal.h>
7#include "cache.h"
8#include "quote.h"
9#include "diff.h"
10#include "diffcore.h"
051308f6 11#include "delta.h"
6973dcae
JH
12#include "xdiff-interface.h"
13
14static int use_size_cache;
15
16int diff_rename_limit_default = -1;
17
18int git_diff_config(const char *var, const char *value)
19{
20 if (!strcmp(var, "diff.renamelimit")) {
21 diff_rename_limit_default = git_config_int(var, value);
22 return 0;
23 }
24
25 return git_default_config(var, value);
26}
27
28static char *quote_one(const char *str)
29{
30 int needlen;
31 char *xp;
32
33 if (!str)
34 return NULL;
35 needlen = quote_c_style(str, NULL, NULL, 0);
36 if (!needlen)
37 return strdup(str);
38 xp = xmalloc(needlen + 1);
39 quote_c_style(str, xp, NULL, 0);
40 return xp;
41}
42
43static char *quote_two(const char *one, const char *two)
44{
45 int need_one = quote_c_style(one, NULL, NULL, 1);
46 int need_two = quote_c_style(two, NULL, NULL, 1);
47 char *xp;
48
49 if (need_one + need_two) {
50 if (!need_one) need_one = strlen(one);
51 if (!need_two) need_one = strlen(two);
52
53 xp = xmalloc(need_one + need_two + 3);
54 xp[0] = '"';
55 quote_c_style(one, xp + 1, NULL, 1);
56 quote_c_style(two, xp + need_one + 1, NULL, 1);
57 strcpy(xp + need_one + need_two + 1, "\"");
58 return xp;
59 }
60 need_one = strlen(one);
61 need_two = strlen(two);
62 xp = xmalloc(need_one + need_two + 1);
63 strcpy(xp, one);
64 strcpy(xp + need_one, two);
65 return xp;
66}
67
68static const char *external_diff(void)
69{
70 static const char *external_diff_cmd = NULL;
71 static int done_preparing = 0;
72
73 if (done_preparing)
74 return external_diff_cmd;
75 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
76 done_preparing = 1;
77 return external_diff_cmd;
78}
79
80#define TEMPFILE_PATH_LEN 50
81
82static struct diff_tempfile {
83 const char *name; /* filename external diff should read from */
84 char hex[41];
85 char mode[10];
86 char tmp_path[TEMPFILE_PATH_LEN];
87} diff_temp[2];
88
89static int count_lines(const char *data, int size)
90{
91 int count, ch, completely_empty = 1, nl_just_seen = 0;
92 count = 0;
93 while (0 < size--) {
94 ch = *data++;
95 if (ch == '\n') {
96 count++;
97 nl_just_seen = 1;
98 completely_empty = 0;
99 }
100 else {
101 nl_just_seen = 0;
102 completely_empty = 0;
103 }
104 }
105 if (completely_empty)
106 return 0;
107 if (!nl_just_seen)
108 count++; /* no trailing newline */
109 return count;
110}
111
112static void print_line_count(int count)
113{
114 switch (count) {
115 case 0:
116 printf("0,0");
117 break;
118 case 1:
119 printf("1");
120 break;
121 default:
122 printf("1,%d", count);
123 break;
124 }
125}
126
127static void copy_file(int prefix, const char *data, int size)
128{
129 int ch, nl_just_seen = 1;
130 while (0 < size--) {
131 ch = *data++;
132 if (nl_just_seen)
133 putchar(prefix);
134 putchar(ch);
135 if (ch == '\n')
136 nl_just_seen = 1;
137 else
138 nl_just_seen = 0;
139 }
140 if (!nl_just_seen)
141 printf("\n\\ No newline at end of file\n");
142}
143
144static void emit_rewrite_diff(const char *name_a,
145 const char *name_b,
146 struct diff_filespec *one,
147 struct diff_filespec *two)
148{
149 int lc_a, lc_b;
150 diff_populate_filespec(one, 0);
151 diff_populate_filespec(two, 0);
152 lc_a = count_lines(one->data, one->size);
153 lc_b = count_lines(two->data, two->size);
154 printf("--- %s\n+++ %s\n@@ -", name_a, name_b);
155 print_line_count(lc_a);
156 printf(" +");
157 print_line_count(lc_b);
158 printf(" @@\n");
159 if (lc_a)
160 copy_file('-', one->data, one->size);
161 if (lc_b)
162 copy_file('+', two->data, two->size);
163}
164
165static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
166{
167 if (!DIFF_FILE_VALID(one)) {
168 mf->ptr = ""; /* does not matter */
169 mf->size = 0;
170 return 0;
171 }
172 else if (diff_populate_filespec(one, 0))
173 return -1;
174 mf->ptr = one->data;
175 mf->size = one->size;
176 return 0;
177}
178
179struct emit_callback {
180 const char **label_path;
181};
182
183static int fn_out(void *priv, mmbuffer_t *mb, int nbuf)
184{
185 int i;
186 struct emit_callback *ecbdata = priv;
187
188 if (ecbdata->label_path[0]) {
189 printf("--- %s\n", ecbdata->label_path[0]);
190 printf("+++ %s\n", ecbdata->label_path[1]);
191 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
192 }
193 for (i = 0; i < nbuf; i++)
194 if (!fwrite(mb[i].ptr, mb[i].size, 1, stdout))
195 return -1;
196 return 0;
197}
198
199static char *pprint_rename(const char *a, const char *b)
200{
201 const char *old = a;
202 const char *new = b;
203 char *name = NULL;
204 int pfx_length, sfx_length;
205 int len_a = strlen(a);
206 int len_b = strlen(b);
207
208 /* Find common prefix */
209 pfx_length = 0;
210 while (*old && *new && *old == *new) {
211 if (*old == '/')
212 pfx_length = old - a + 1;
213 old++;
214 new++;
215 }
216
217 /* Find common suffix */
218 old = a + len_a;
219 new = b + len_b;
220 sfx_length = 0;
221 while (a <= old && b <= new && *old == *new) {
222 if (*old == '/')
223 sfx_length = len_a - (old - a);
224 old--;
225 new--;
226 }
227
228 /*
229 * pfx{mid-a => mid-b}sfx
230 * {pfx-a => pfx-b}sfx
231 * pfx{sfx-a => sfx-b}
232 * name-a => name-b
233 */
234 if (pfx_length + sfx_length) {
cc908b82
JH
235 int a_midlen = len_a - pfx_length - sfx_length;
236 int b_midlen = len_b - pfx_length - sfx_length;
237 if (a_midlen < 0) a_midlen = 0;
238 if (b_midlen < 0) b_midlen = 0;
239
6973dcae
JH
240 name = xmalloc(len_a + len_b - pfx_length - sfx_length + 7);
241 sprintf(name, "%.*s{%.*s => %.*s}%s",
242 pfx_length, a,
cc908b82
JH
243 a_midlen, a + pfx_length,
244 b_midlen, b + pfx_length,
6973dcae
JH
245 a + len_a - sfx_length);
246 }
247 else {
248 name = xmalloc(len_a + len_b + 5);
249 sprintf(name, "%s => %s", a, b);
250 }
251 return name;
252}
253
254struct diffstat_t {
255 struct xdiff_emit_state xm;
256
257 int nr;
258 int alloc;
259 struct diffstat_file {
260 char *name;
261 unsigned is_unmerged:1;
262 unsigned is_binary:1;
263 unsigned is_renamed:1;
264 unsigned int added, deleted;
265 } **files;
266};
267
268static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
269 const char *name_a,
270 const char *name_b)
271{
272 struct diffstat_file *x;
273 x = xcalloc(sizeof (*x), 1);
274 if (diffstat->nr == diffstat->alloc) {
275 diffstat->alloc = alloc_nr(diffstat->alloc);
276 diffstat->files = xrealloc(diffstat->files,
277 diffstat->alloc * sizeof(x));
278 }
279 diffstat->files[diffstat->nr++] = x;
280 if (name_b) {
281 x->name = pprint_rename(name_a, name_b);
282 x->is_renamed = 1;
283 }
284 else
285 x->name = strdup(name_a);
286 return x;
287}
288
289static void diffstat_consume(void *priv, char *line, unsigned long len)
290{
291 struct diffstat_t *diffstat = priv;
292 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
293
294 if (line[0] == '+')
295 x->added++;
296 else if (line[0] == '-')
297 x->deleted++;
298}
299
300static const char pluses[] = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
301static const char minuses[]= "----------------------------------------------------------------------";
302
303static void show_stats(struct diffstat_t* data)
304{
6973dcae
JH
305 int i, len, add, del, total, adds = 0, dels = 0;
306 int max, max_change = 0, max_len = 0;
307 int total_files = data->nr;
308
309 if (data->nr == 0)
310 return;
311
312 for (i = 0; i < data->nr; i++) {
313 struct diffstat_file *file = data->files[i];
314
315 len = strlen(file->name);
316 if (max_len < len)
317 max_len = len;
318
319 if (file->is_binary || file->is_unmerged)
320 continue;
321 if (max_change < file->added + file->deleted)
322 max_change = file->added + file->deleted;
323 }
324
325 for (i = 0; i < data->nr; i++) {
5d6a9f45 326 char *prefix = "";
6973dcae
JH
327 char *name = data->files[i]->name;
328 int added = data->files[i]->added;
329 int deleted = data->files[i]->deleted;
330
331 if (0 < (len = quote_c_style(name, NULL, NULL, 0))) {
332 char *qname = xmalloc(len + 1);
333 quote_c_style(name, qname, NULL, 0);
334 free(name);
335 data->files[i]->name = name = qname;
336 }
337
338 /*
339 * "scale" the filename
340 */
341 len = strlen(name);
342 max = max_len;
343 if (max > 50)
344 max = 50;
345 if (len > max) {
346 char *slash;
347 prefix = "...";
348 max -= 3;
349 name += len - max;
350 slash = strchr(name, '/');
351 if (slash)
352 name = slash;
353 }
354 len = max;
355
356 /*
357 * scale the add/delete
358 */
359 max = max_change;
360 if (max + len > 70)
361 max = 70 - len;
362
363 if (data->files[i]->is_binary) {
364 printf(" %s%-*s | Bin\n", prefix, len, name);
365 goto free_diffstat_file;
366 }
367 else if (data->files[i]->is_unmerged) {
368 printf(" %s%-*s | Unmerged\n", prefix, len, name);
369 goto free_diffstat_file;
370 }
371 else if (!data->files[i]->is_renamed &&
372 (added + deleted == 0)) {
373 total_files--;
374 goto free_diffstat_file;
375 }
376
377 add = added;
378 del = deleted;
379 total = add + del;
380 adds += add;
381 dels += del;
382
383 if (max_change > 0) {
384 total = (total * max + max_change / 2) / max_change;
385 add = (add * max + max_change / 2) / max_change;
386 del = total - add;
387 }
388 printf(" %s%-*s |%5d %.*s%.*s\n", prefix,
389 len, name, added + deleted,
390 add, pluses, del, minuses);
391 free_diffstat_file:
392 free(data->files[i]->name);
393 free(data->files[i]);
394 }
395 free(data->files);
396 printf(" %d files changed, %d insertions(+), %d deletions(-)\n",
397 total_files, adds, dels);
398}
399
88246898
JS
400struct checkdiff_t {
401 struct xdiff_emit_state xm;
402 const char *filename;
403 int lineno;
404};
405
406static void checkdiff_consume(void *priv, char *line, unsigned long len)
407{
408 struct checkdiff_t *data = priv;
409
410 if (line[0] == '+') {
411 int i, spaces = 0;
412
413 data->lineno++;
414
415 /* check space before tab */
416 for (i = 1; i < len && (line[i] == ' ' || line[i] == '\t'); i++)
417 if (line[i] == ' ')
418 spaces++;
419 if (line[i - 1] == '\t' && spaces)
420 printf("%s:%d: space before tab:%.*s\n",
421 data->filename, data->lineno, (int)len, line);
422
423 /* check white space at line end */
424 if (line[len - 1] == '\n')
425 len--;
426 if (isspace(line[len - 1]))
427 printf("%s:%d: white space at end: %.*s\n",
428 data->filename, data->lineno, (int)len, line);
429 } else if (line[0] == ' ')
430 data->lineno++;
431 else if (line[0] == '@') {
432 char *plus = strchr(line, '+');
433 if (plus)
434 data->lineno = strtol(plus, line + len, 10);
435 else
436 die("invalid diff");
437 }
438}
439
0660626c
JH
440static unsigned char *deflate_it(char *data,
441 unsigned long size,
442 unsigned long *result_size)
051308f6 443{
0660626c
JH
444 int bound;
445 unsigned char *deflated;
446 z_stream stream;
447
448 memset(&stream, 0, sizeof(stream));
449 deflateInit(&stream, Z_BEST_COMPRESSION);
450 bound = deflateBound(&stream, size);
451 deflated = xmalloc(bound);
452 stream.next_out = deflated;
453 stream.avail_out = bound;
454
455 stream.next_in = (unsigned char *)data;
456 stream.avail_in = size;
457 while (deflate(&stream, Z_FINISH) == Z_OK)
458 ; /* nothing */
459 deflateEnd(&stream);
460 *result_size = stream.total_out;
461 return deflated;
051308f6
JH
462}
463
0660626c 464static void emit_binary_diff(mmfile_t *one, mmfile_t *two)
051308f6 465{
0660626c
JH
466 void *cp;
467 void *delta;
468 void *deflated;
469 void *data;
470 unsigned long orig_size;
471 unsigned long delta_size;
472 unsigned long deflate_size;
473 unsigned long data_size;
051308f6 474
0660626c
JH
475 printf("GIT binary patch\n");
476 /* We could do deflated delta, or we could do just deflated two,
477 * whichever is smaller.
051308f6 478 */
0660626c
JH
479 delta = NULL;
480 deflated = deflate_it(two->ptr, two->size, &deflate_size);
481 if (one->size && two->size) {
482 delta = diff_delta(one->ptr, one->size,
483 two->ptr, two->size,
484 &delta_size, deflate_size);
485 if (delta) {
486 void *to_free = delta;
487 orig_size = delta_size;
488 delta = deflate_it(delta, delta_size, &delta_size);
489 free(to_free);
051308f6
JH
490 }
491 }
051308f6 492
0660626c
JH
493 if (delta && delta_size < deflate_size) {
494 printf("delta %lu\n", orig_size);
495 free(deflated);
496 data = delta;
497 data_size = delta_size;
498 }
499 else {
500 printf("literal %lu\n", two->size);
501 free(delta);
502 data = deflated;
503 data_size = deflate_size;
504 }
051308f6 505
0660626c
JH
506 /* emit data encoded in base85 */
507 cp = data;
508 while (data_size) {
509 int bytes = (52 < data_size) ? 52 : data_size;
051308f6 510 char line[70];
0660626c 511 data_size -= bytes;
051308f6
JH
512 if (bytes <= 26)
513 line[0] = bytes + 'A' - 1;
514 else
515 line[0] = bytes - 26 + 'a' - 1;
516 encode_85(line + 1, cp, bytes);
517 cp += bytes;
518 puts(line);
519 }
520 printf("\n");
0660626c 521 free(data);
051308f6
JH
522}
523
6973dcae
JH
524#define FIRST_FEW_BYTES 8000
525static int mmfile_is_binary(mmfile_t *mf)
526{
527 long sz = mf->size;
528 if (FIRST_FEW_BYTES < sz)
529 sz = FIRST_FEW_BYTES;
530 if (memchr(mf->ptr, 0, sz))
531 return 1;
532 return 0;
533}
534
535static void builtin_diff(const char *name_a,
536 const char *name_b,
537 struct diff_filespec *one,
538 struct diff_filespec *two,
539 const char *xfrm_msg,
051308f6 540 struct diff_options *o,
6973dcae
JH
541 int complete_rewrite)
542{
543 mmfile_t mf1, mf2;
544 const char *lbl[2];
545 char *a_one, *b_two;
546
547 a_one = quote_two("a/", name_a);
548 b_two = quote_two("b/", name_b);
549 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
550 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
551 printf("diff --git %s %s\n", a_one, b_two);
552 if (lbl[0][0] == '/') {
553 /* /dev/null */
554 printf("new file mode %06o\n", two->mode);
555 if (xfrm_msg && xfrm_msg[0])
556 puts(xfrm_msg);
557 }
558 else if (lbl[1][0] == '/') {
559 printf("deleted file mode %06o\n", one->mode);
560 if (xfrm_msg && xfrm_msg[0])
561 puts(xfrm_msg);
562 }
563 else {
564 if (one->mode != two->mode) {
565 printf("old mode %06o\n", one->mode);
566 printf("new mode %06o\n", two->mode);
567 }
568 if (xfrm_msg && xfrm_msg[0])
569 puts(xfrm_msg);
570 /*
571 * we do not run diff between different kind
572 * of objects.
573 */
574 if ((one->mode ^ two->mode) & S_IFMT)
575 goto free_ab_and_return;
576 if (complete_rewrite) {
577 emit_rewrite_diff(name_a, name_b, one, two);
578 goto free_ab_and_return;
579 }
580 }
581
582 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
583 die("unable to read files to diff");
584
051308f6 585 if (mmfile_is_binary(&mf1) || mmfile_is_binary(&mf2)) {
0660626c
JH
586 /* Quite common confusing case */
587 if (mf1.size == mf2.size &&
588 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
589 goto free_ab_and_return;
590 if (o->binary)
051308f6
JH
591 emit_binary_diff(&mf1, &mf2);
592 else
593 printf("Binary files %s and %s differ\n",
594 lbl[0], lbl[1]);
595 }
6973dcae
JH
596 else {
597 /* Crazy xdl interfaces.. */
598 const char *diffopts = getenv("GIT_DIFF_OPTS");
599 xpparam_t xpp;
600 xdemitconf_t xecfg;
601 xdemitcb_t ecb;
602 struct emit_callback ecbdata;
603
604 ecbdata.label_path = lbl;
605 xpp.flags = XDF_NEED_MINIMAL;
ee1e5412 606 xecfg.ctxlen = o->context;
6973dcae
JH
607 xecfg.flags = XDL_EMIT_FUNCNAMES;
608 if (!diffopts)
609 ;
610 else if (!strncmp(diffopts, "--unified=", 10))
611 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
612 else if (!strncmp(diffopts, "-u", 2))
613 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
614 ecb.outf = fn_out;
615 ecb.priv = &ecbdata;
616 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
617 }
618
619 free_ab_and_return:
620 free(a_one);
621 free(b_two);
622 return;
623}
624
625static void builtin_diffstat(const char *name_a, const char *name_b,
626 struct diff_filespec *one,
627 struct diff_filespec *two,
710158e3
JH
628 struct diffstat_t *diffstat,
629 int complete_rewrite)
6973dcae
JH
630{
631 mmfile_t mf1, mf2;
632 struct diffstat_file *data;
633
634 data = diffstat_add(diffstat, name_a, name_b);
635
636 if (!one || !two) {
637 data->is_unmerged = 1;
638 return;
639 }
710158e3
JH
640 if (complete_rewrite) {
641 diff_populate_filespec(one, 0);
642 diff_populate_filespec(two, 0);
643 data->deleted = count_lines(one->data, one->size);
644 data->added = count_lines(two->data, two->size);
645 return;
646 }
6973dcae
JH
647 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
648 die("unable to read files to diff");
649
650 if (mmfile_is_binary(&mf1) || mmfile_is_binary(&mf2))
651 data->is_binary = 1;
652 else {
653 /* Crazy xdl interfaces.. */
654 xpparam_t xpp;
655 xdemitconf_t xecfg;
656 xdemitcb_t ecb;
657
658 xpp.flags = XDF_NEED_MINIMAL;
659 xecfg.ctxlen = 0;
660 xecfg.flags = 0;
661 ecb.outf = xdiff_outf;
662 ecb.priv = diffstat;
663 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
664 }
665}
666
88246898
JS
667static void builtin_checkdiff(const char *name_a, const char *name_b,
668 struct diff_filespec *one,
669 struct diff_filespec *two)
670{
671 mmfile_t mf1, mf2;
672 struct checkdiff_t data;
673
674 if (!two)
675 return;
676
677 memset(&data, 0, sizeof(data));
678 data.xm.consume = checkdiff_consume;
679 data.filename = name_b ? name_b : name_a;
680 data.lineno = 0;
681
682 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
683 die("unable to read files to diff");
684
685 if (mmfile_is_binary(&mf2))
686 return;
687 else {
688 /* Crazy xdl interfaces.. */
689 xpparam_t xpp;
690 xdemitconf_t xecfg;
691 xdemitcb_t ecb;
692
693 xpp.flags = XDF_NEED_MINIMAL;
694 xecfg.ctxlen = 0;
695 xecfg.flags = 0;
696 ecb.outf = xdiff_outf;
697 ecb.priv = &data;
698 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
699 }
700}
701
6973dcae
JH
702struct diff_filespec *alloc_filespec(const char *path)
703{
704 int namelen = strlen(path);
705 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
706
707 memset(spec, 0, sizeof(*spec));
708 spec->path = (char *)(spec + 1);
709 memcpy(spec->path, path, namelen+1);
710 return spec;
711}
712
713void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
714 unsigned short mode)
715{
716 if (mode) {
717 spec->mode = canon_mode(mode);
718 memcpy(spec->sha1, sha1, 20);
719 spec->sha1_valid = !!memcmp(sha1, null_sha1, 20);
720 }
721}
722
723/*
724 * Given a name and sha1 pair, if the dircache tells us the file in
725 * the work tree has that object contents, return true, so that
726 * prepare_temp_file() does not have to inflate and extract.
727 */
728static int work_tree_matches(const char *name, const unsigned char *sha1)
729{
730 struct cache_entry *ce;
731 struct stat st;
732 int pos, len;
733
734 /* We do not read the cache ourselves here, because the
735 * benchmark with my previous version that always reads cache
736 * shows that it makes things worse for diff-tree comparing
737 * two linux-2.6 kernel trees in an already checked out work
738 * tree. This is because most diff-tree comparisons deal with
739 * only a small number of files, while reading the cache is
740 * expensive for a large project, and its cost outweighs the
741 * savings we get by not inflating the object to a temporary
742 * file. Practically, this code only helps when we are used
743 * by diff-cache --cached, which does read the cache before
744 * calling us.
745 */
746 if (!active_cache)
747 return 0;
748
749 len = strlen(name);
750 pos = cache_name_pos(name, len);
751 if (pos < 0)
752 return 0;
753 ce = active_cache[pos];
754 if ((lstat(name, &st) < 0) ||
755 !S_ISREG(st.st_mode) || /* careful! */
756 ce_match_stat(ce, &st, 0) ||
757 memcmp(sha1, ce->sha1, 20))
758 return 0;
759 /* we return 1 only when we can stat, it is a regular file,
760 * stat information matches, and sha1 recorded in the cache
761 * matches. I.e. we know the file in the work tree really is
762 * the same as the <name, sha1> pair.
763 */
764 return 1;
765}
766
767static struct sha1_size_cache {
768 unsigned char sha1[20];
769 unsigned long size;
770} **sha1_size_cache;
771static int sha1_size_cache_nr, sha1_size_cache_alloc;
772
773static struct sha1_size_cache *locate_size_cache(unsigned char *sha1,
774 int find_only,
775 unsigned long size)
776{
777 int first, last;
778 struct sha1_size_cache *e;
779
780 first = 0;
781 last = sha1_size_cache_nr;
782 while (last > first) {
783 int cmp, next = (last + first) >> 1;
784 e = sha1_size_cache[next];
785 cmp = memcmp(e->sha1, sha1, 20);
786 if (!cmp)
787 return e;
788 if (cmp < 0) {
789 last = next;
790 continue;
791 }
792 first = next+1;
793 }
794 /* not found */
795 if (find_only)
796 return NULL;
797 /* insert to make it at "first" */
798 if (sha1_size_cache_alloc <= sha1_size_cache_nr) {
799 sha1_size_cache_alloc = alloc_nr(sha1_size_cache_alloc);
800 sha1_size_cache = xrealloc(sha1_size_cache,
801 sha1_size_cache_alloc *
802 sizeof(*sha1_size_cache));
803 }
804 sha1_size_cache_nr++;
805 if (first < sha1_size_cache_nr)
806 memmove(sha1_size_cache + first + 1, sha1_size_cache + first,
807 (sha1_size_cache_nr - first - 1) *
808 sizeof(*sha1_size_cache));
809 e = xmalloc(sizeof(struct sha1_size_cache));
810 sha1_size_cache[first] = e;
811 memcpy(e->sha1, sha1, 20);
812 e->size = size;
813 return e;
814}
815
816/*
817 * While doing rename detection and pickaxe operation, we may need to
818 * grab the data for the blob (or file) for our own in-core comparison.
819 * diff_filespec has data and size fields for this purpose.
820 */
821int diff_populate_filespec(struct diff_filespec *s, int size_only)
822{
823 int err = 0;
824 if (!DIFF_FILE_VALID(s))
825 die("internal error: asking to populate invalid file.");
826 if (S_ISDIR(s->mode))
827 return -1;
828
829 if (!use_size_cache)
830 size_only = 0;
831
832 if (s->data)
833 return err;
834 if (!s->sha1_valid ||
835 work_tree_matches(s->path, s->sha1)) {
836 struct stat st;
837 int fd;
838 if (lstat(s->path, &st) < 0) {
839 if (errno == ENOENT) {
840 err_empty:
841 err = -1;
842 empty:
843 s->data = "";
844 s->size = 0;
845 return err;
846 }
847 }
848 s->size = st.st_size;
849 if (!s->size)
850 goto empty;
851 if (size_only)
852 return 0;
853 if (S_ISLNK(st.st_mode)) {
854 int ret;
855 s->data = xmalloc(s->size);
856 s->should_free = 1;
857 ret = readlink(s->path, s->data, s->size);
858 if (ret < 0) {
859 free(s->data);
860 goto err_empty;
861 }
862 return 0;
863 }
864 fd = open(s->path, O_RDONLY);
865 if (fd < 0)
866 goto err_empty;
867 s->data = mmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
868 close(fd);
869 if (s->data == MAP_FAILED)
870 goto err_empty;
871 s->should_munmap = 1;
872 }
873 else {
874 char type[20];
875 struct sha1_size_cache *e;
876
877 if (size_only) {
878 e = locate_size_cache(s->sha1, 1, 0);
879 if (e) {
880 s->size = e->size;
881 return 0;
882 }
883 if (!sha1_object_info(s->sha1, type, &s->size))
884 locate_size_cache(s->sha1, 0, s->size);
885 }
886 else {
887 s->data = read_sha1_file(s->sha1, type, &s->size);
888 s->should_free = 1;
889 }
890 }
891 return 0;
892}
893
894void diff_free_filespec_data(struct diff_filespec *s)
895{
896 if (s->should_free)
897 free(s->data);
898 else if (s->should_munmap)
899 munmap(s->data, s->size);
900 s->should_free = s->should_munmap = 0;
901 s->data = NULL;
902 free(s->cnt_data);
903 s->cnt_data = NULL;
904}
905
906static void prep_temp_blob(struct diff_tempfile *temp,
907 void *blob,
908 unsigned long size,
909 const unsigned char *sha1,
910 int mode)
911{
912 int fd;
913
914 fd = git_mkstemp(temp->tmp_path, TEMPFILE_PATH_LEN, ".diff_XXXXXX");
915 if (fd < 0)
916 die("unable to create temp-file");
917 if (write(fd, blob, size) != size)
918 die("unable to write temp-file");
919 close(fd);
920 temp->name = temp->tmp_path;
921 strcpy(temp->hex, sha1_to_hex(sha1));
922 temp->hex[40] = 0;
923 sprintf(temp->mode, "%06o", mode);
924}
925
926static void prepare_temp_file(const char *name,
927 struct diff_tempfile *temp,
928 struct diff_filespec *one)
929{
930 if (!DIFF_FILE_VALID(one)) {
931 not_a_valid_file:
932 /* A '-' entry produces this for file-2, and
933 * a '+' entry produces this for file-1.
934 */
935 temp->name = "/dev/null";
936 strcpy(temp->hex, ".");
937 strcpy(temp->mode, ".");
938 return;
939 }
940
941 if (!one->sha1_valid ||
942 work_tree_matches(name, one->sha1)) {
943 struct stat st;
944 if (lstat(name, &st) < 0) {
945 if (errno == ENOENT)
946 goto not_a_valid_file;
947 die("stat(%s): %s", name, strerror(errno));
948 }
949 if (S_ISLNK(st.st_mode)) {
950 int ret;
951 char buf[PATH_MAX + 1]; /* ought to be SYMLINK_MAX */
952 if (sizeof(buf) <= st.st_size)
953 die("symlink too long: %s", name);
954 ret = readlink(name, buf, st.st_size);
955 if (ret < 0)
956 die("readlink(%s)", name);
957 prep_temp_blob(temp, buf, st.st_size,
958 (one->sha1_valid ?
959 one->sha1 : null_sha1),
960 (one->sha1_valid ?
961 one->mode : S_IFLNK));
962 }
963 else {
964 /* we can borrow from the file in the work tree */
965 temp->name = name;
966 if (!one->sha1_valid)
967 strcpy(temp->hex, sha1_to_hex(null_sha1));
968 else
969 strcpy(temp->hex, sha1_to_hex(one->sha1));
970 /* Even though we may sometimes borrow the
971 * contents from the work tree, we always want
972 * one->mode. mode is trustworthy even when
973 * !(one->sha1_valid), as long as
974 * DIFF_FILE_VALID(one).
975 */
976 sprintf(temp->mode, "%06o", one->mode);
977 }
978 return;
979 }
980 else {
981 if (diff_populate_filespec(one, 0))
982 die("cannot read data blob for %s", one->path);
983 prep_temp_blob(temp, one->data, one->size,
984 one->sha1, one->mode);
985 }
986}
987
988static void remove_tempfile(void)
989{
990 int i;
991
992 for (i = 0; i < 2; i++)
993 if (diff_temp[i].name == diff_temp[i].tmp_path) {
994 unlink(diff_temp[i].name);
995 diff_temp[i].name = NULL;
996 }
997}
998
999static void remove_tempfile_on_signal(int signo)
1000{
1001 remove_tempfile();
1002 signal(SIGINT, SIG_DFL);
1003 raise(signo);
1004}
1005
1006static int spawn_prog(const char *pgm, const char **arg)
1007{
1008 pid_t pid;
1009 int status;
1010
1011 fflush(NULL);
1012 pid = fork();
1013 if (pid < 0)
1014 die("unable to fork");
1015 if (!pid) {
1016 execvp(pgm, (char *const*) arg);
1017 exit(255);
1018 }
1019
1020 while (waitpid(pid, &status, 0) < 0) {
1021 if (errno == EINTR)
1022 continue;
1023 return -1;
1024 }
1025
1026 /* Earlier we did not check the exit status because
1027 * diff exits non-zero if files are different, and
1028 * we are not interested in knowing that. It was a
1029 * mistake which made it harder to quit a diff-*
1030 * session that uses the git-apply-patch-script as
1031 * the GIT_EXTERNAL_DIFF. A custom GIT_EXTERNAL_DIFF
1032 * should also exit non-zero only when it wants to
1033 * abort the entire diff-* session.
1034 */
1035 if (WIFEXITED(status) && !WEXITSTATUS(status))
1036 return 0;
1037 return -1;
1038}
1039
1040/* An external diff command takes:
1041 *
1042 * diff-cmd name infile1 infile1-sha1 infile1-mode \
1043 * infile2 infile2-sha1 infile2-mode [ rename-to ]
1044 *
1045 */
1046static void run_external_diff(const char *pgm,
1047 const char *name,
1048 const char *other,
1049 struct diff_filespec *one,
1050 struct diff_filespec *two,
1051 const char *xfrm_msg,
1052 int complete_rewrite)
1053{
1054 const char *spawn_arg[10];
1055 struct diff_tempfile *temp = diff_temp;
1056 int retval;
1057 static int atexit_asked = 0;
1058 const char *othername;
1059 const char **arg = &spawn_arg[0];
1060
1061 othername = (other? other : name);
1062 if (one && two) {
1063 prepare_temp_file(name, &temp[0], one);
1064 prepare_temp_file(othername, &temp[1], two);
1065 if (! atexit_asked &&
1066 (temp[0].name == temp[0].tmp_path ||
1067 temp[1].name == temp[1].tmp_path)) {
1068 atexit_asked = 1;
1069 atexit(remove_tempfile);
1070 }
1071 signal(SIGINT, remove_tempfile_on_signal);
1072 }
1073
1074 if (one && two) {
1075 *arg++ = pgm;
1076 *arg++ = name;
1077 *arg++ = temp[0].name;
1078 *arg++ = temp[0].hex;
1079 *arg++ = temp[0].mode;
1080 *arg++ = temp[1].name;
1081 *arg++ = temp[1].hex;
1082 *arg++ = temp[1].mode;
1083 if (other) {
1084 *arg++ = other;
1085 *arg++ = xfrm_msg;
1086 }
1087 } else {
1088 *arg++ = pgm;
1089 *arg++ = name;
1090 }
1091 *arg = NULL;
1092 retval = spawn_prog(pgm, spawn_arg);
1093 remove_tempfile();
1094 if (retval) {
1095 fprintf(stderr, "external diff died, stopping at %s.\n", name);
1096 exit(1);
1097 }
1098}
1099
1100static void run_diff_cmd(const char *pgm,
1101 const char *name,
1102 const char *other,
1103 struct diff_filespec *one,
1104 struct diff_filespec *two,
1105 const char *xfrm_msg,
051308f6 1106 struct diff_options *o,
6973dcae
JH
1107 int complete_rewrite)
1108{
1109 if (pgm) {
1110 run_external_diff(pgm, name, other, one, two, xfrm_msg,
1111 complete_rewrite);
1112 return;
1113 }
1114 if (one && two)
1115 builtin_diff(name, other ? other : name,
051308f6 1116 one, two, xfrm_msg, o, complete_rewrite);
6973dcae
JH
1117 else
1118 printf("* Unmerged path %s\n", name);
1119}
1120
1121static void diff_fill_sha1_info(struct diff_filespec *one)
1122{
1123 if (DIFF_FILE_VALID(one)) {
1124 if (!one->sha1_valid) {
1125 struct stat st;
1126 if (lstat(one->path, &st) < 0)
1127 die("stat %s", one->path);
1128 if (index_path(one->sha1, one->path, &st, 0))
1129 die("cannot hash %s\n", one->path);
1130 }
1131 }
1132 else
1133 memset(one->sha1, 0, 20);
1134}
1135
1136static void run_diff(struct diff_filepair *p, struct diff_options *o)
1137{
1138 const char *pgm = external_diff();
1139 char msg[PATH_MAX*2+300], *xfrm_msg;
1140 struct diff_filespec *one;
1141 struct diff_filespec *two;
1142 const char *name;
1143 const char *other;
1144 char *name_munged, *other_munged;
1145 int complete_rewrite = 0;
1146 int len;
1147
1148 if (DIFF_PAIR_UNMERGED(p)) {
1149 /* unmerged */
051308f6 1150 run_diff_cmd(pgm, p->one->path, NULL, NULL, NULL, NULL, o, 0);
6973dcae
JH
1151 return;
1152 }
1153
1154 name = p->one->path;
1155 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1156 name_munged = quote_one(name);
1157 other_munged = quote_one(other);
1158 one = p->one; two = p->two;
1159
1160 diff_fill_sha1_info(one);
1161 diff_fill_sha1_info(two);
1162
1163 len = 0;
1164 switch (p->status) {
1165 case DIFF_STATUS_COPIED:
1166 len += snprintf(msg + len, sizeof(msg) - len,
1167 "similarity index %d%%\n"
1168 "copy from %s\n"
1169 "copy to %s\n",
1170 (int)(0.5 + p->score * 100.0/MAX_SCORE),
1171 name_munged, other_munged);
1172 break;
1173 case DIFF_STATUS_RENAMED:
1174 len += snprintf(msg + len, sizeof(msg) - len,
1175 "similarity index %d%%\n"
1176 "rename from %s\n"
1177 "rename to %s\n",
1178 (int)(0.5 + p->score * 100.0/MAX_SCORE),
1179 name_munged, other_munged);
1180 break;
1181 case DIFF_STATUS_MODIFIED:
1182 if (p->score) {
1183 len += snprintf(msg + len, sizeof(msg) - len,
1184 "dissimilarity index %d%%\n",
1185 (int)(0.5 + p->score *
1186 100.0/MAX_SCORE));
1187 complete_rewrite = 1;
1188 break;
1189 }
1190 /* fallthru */
1191 default:
1192 /* nothing */
1193 ;
1194 }
1195
1196 if (memcmp(one->sha1, two->sha1, 20)) {
6973dcae 1197 int abbrev = o->full_index ? 40 : DEFAULT_ABBREV;
6973dcae
JH
1198
1199 len += snprintf(msg + len, sizeof(msg) - len,
1200 "index %.*s..%.*s",
dcb3450f
LT
1201 abbrev, sha1_to_hex(one->sha1),
1202 abbrev, sha1_to_hex(two->sha1));
6973dcae
JH
1203 if (one->mode == two->mode)
1204 len += snprintf(msg + len, sizeof(msg) - len,
1205 " %06o", one->mode);
1206 len += snprintf(msg + len, sizeof(msg) - len, "\n");
1207 }
1208
1209 if (len)
1210 msg[--len] = 0;
1211 xfrm_msg = len ? msg : NULL;
1212
1213 if (!pgm &&
1214 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
1215 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
1216 /* a filepair that changes between file and symlink
1217 * needs to be split into deletion and creation.
1218 */
1219 struct diff_filespec *null = alloc_filespec(two->path);
051308f6 1220 run_diff_cmd(NULL, name, other, one, null, xfrm_msg, o, 0);
6973dcae
JH
1221 free(null);
1222 null = alloc_filespec(one->path);
051308f6 1223 run_diff_cmd(NULL, name, other, null, two, xfrm_msg, o, 0);
6973dcae
JH
1224 free(null);
1225 }
1226 else
051308f6 1227 run_diff_cmd(pgm, name, other, one, two, xfrm_msg, o,
6973dcae
JH
1228 complete_rewrite);
1229
1230 free(name_munged);
1231 free(other_munged);
1232}
1233
1234static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
1235 struct diffstat_t *diffstat)
1236{
1237 const char *name;
1238 const char *other;
710158e3 1239 int complete_rewrite = 0;
6973dcae
JH
1240
1241 if (DIFF_PAIR_UNMERGED(p)) {
1242 /* unmerged */
710158e3 1243 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, 0);
6973dcae
JH
1244 return;
1245 }
1246
1247 name = p->one->path;
1248 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1249
1250 diff_fill_sha1_info(p->one);
1251 diff_fill_sha1_info(p->two);
1252
710158e3
JH
1253 if (p->status == DIFF_STATUS_MODIFIED && p->score)
1254 complete_rewrite = 1;
1255 builtin_diffstat(name, other, p->one, p->two, diffstat, complete_rewrite);
6973dcae
JH
1256}
1257
88246898
JS
1258static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
1259{
1260 const char *name;
1261 const char *other;
1262
1263 if (DIFF_PAIR_UNMERGED(p)) {
1264 /* unmerged */
1265 return;
1266 }
1267
1268 name = p->one->path;
1269 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1270
1271 diff_fill_sha1_info(p->one);
1272 diff_fill_sha1_info(p->two);
1273
1274 builtin_checkdiff(name, other, p->one, p->two);
1275}
1276
6973dcae
JH
1277void diff_setup(struct diff_options *options)
1278{
1279 memset(options, 0, sizeof(*options));
1280 options->output_format = DIFF_FORMAT_RAW;
1281 options->line_termination = '\n';
1282 options->break_opt = -1;
1283 options->rename_limit = -1;
ee1e5412 1284 options->context = 3;
6973dcae
JH
1285
1286 options->change = diff_change;
1287 options->add_remove = diff_addremove;
1288}
1289
1290int diff_setup_done(struct diff_options *options)
1291{
1292 if ((options->find_copies_harder &&
1293 options->detect_rename != DIFF_DETECT_COPY) ||
1294 (0 <= options->rename_limit && !options->detect_rename))
1295 return -1;
1296
1297 /*
1298 * These cases always need recursive; we do not drop caller-supplied
1299 * recursive bits for other formats here.
1300 */
1301 if ((options->output_format == DIFF_FORMAT_PATCH) ||
88246898
JS
1302 (options->output_format == DIFF_FORMAT_DIFFSTAT) ||
1303 (options->output_format == DIFF_FORMAT_CHECKDIFF))
6973dcae
JH
1304 options->recursive = 1;
1305
1306 if (options->detect_rename && options->rename_limit < 0)
1307 options->rename_limit = diff_rename_limit_default;
1308 if (options->setup & DIFF_SETUP_USE_CACHE) {
1309 if (!active_cache)
1310 /* read-cache does not die even when it fails
1311 * so it is safe for us to do this here. Also
1312 * it does not smudge active_cache or active_nr
1313 * when it fails, so we do not have to worry about
1314 * cleaning it up ourselves either.
1315 */
1316 read_cache();
1317 }
1318 if (options->setup & DIFF_SETUP_USE_SIZE_CACHE)
1319 use_size_cache = 1;
1320 if (options->abbrev <= 0 || 40 < options->abbrev)
1321 options->abbrev = 40; /* full */
1322
1323 return 0;
1324}
1325
ee1e5412
LT
1326int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
1327{
1328 char c, *eq;
1329 int len;
1330
1331 if (*arg != '-')
1332 return 0;
1333 c = *++arg;
1334 if (!c)
1335 return 0;
1336 if (c == arg_short) {
1337 c = *++arg;
1338 if (!c)
1339 return 1;
1340 if (val && isdigit(c)) {
1341 char *end;
1342 int n = strtoul(arg, &end, 10);
1343 if (*end)
1344 return 0;
1345 *val = n;
1346 return 1;
1347 }
1348 return 0;
1349 }
1350 if (c != '-')
1351 return 0;
1352 arg++;
1353 eq = strchr(arg, '=');
1354 if (eq)
1355 len = eq - arg;
1356 else
1357 len = strlen(arg);
1358 if (!len || strncmp(arg, arg_long, len))
1359 return 0;
1360 if (eq) {
1361 int n;
1362 char *end;
1363 if (!isdigit(*++eq))
1364 return 0;
1365 n = strtoul(eq, &end, 10);
1366 if (*end)
1367 return 0;
1368 *val = n;
1369 }
1370 return 1;
1371}
1372
6973dcae
JH
1373int diff_opt_parse(struct diff_options *options, const char **av, int ac)
1374{
1375 const char *arg = av[0];
1376 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
1377 options->output_format = DIFF_FORMAT_PATCH;
ee1e5412
LT
1378 else if (opt_arg(arg, 'U', "unified", &options->context))
1379 options->output_format = DIFF_FORMAT_PATCH;
6973dcae
JH
1380 else if (!strcmp(arg, "--patch-with-raw")) {
1381 options->output_format = DIFF_FORMAT_PATCH;
1382 options->with_raw = 1;
1383 }
1384 else if (!strcmp(arg, "--stat"))
1385 options->output_format = DIFF_FORMAT_DIFFSTAT;
88246898
JS
1386 else if (!strcmp(arg, "--check"))
1387 options->output_format = DIFF_FORMAT_CHECKDIFF;
4bbd261b
SE
1388 else if (!strcmp(arg, "--summary"))
1389 options->summary = 1;
6973dcae
JH
1390 else if (!strcmp(arg, "--patch-with-stat")) {
1391 options->output_format = DIFF_FORMAT_PATCH;
1392 options->with_stat = 1;
1393 }
1394 else if (!strcmp(arg, "-z"))
1395 options->line_termination = 0;
1396 else if (!strncmp(arg, "-l", 2))
1397 options->rename_limit = strtoul(arg+2, NULL, 10);
1398 else if (!strcmp(arg, "--full-index"))
1399 options->full_index = 1;
0660626c
JH
1400 else if (!strcmp(arg, "--binary")) {
1401 options->output_format = DIFF_FORMAT_PATCH;
1402 options->full_index = options->binary = 1;
1403 }
6973dcae
JH
1404 else if (!strcmp(arg, "--name-only"))
1405 options->output_format = DIFF_FORMAT_NAME;
1406 else if (!strcmp(arg, "--name-status"))
1407 options->output_format = DIFF_FORMAT_NAME_STATUS;
1408 else if (!strcmp(arg, "-R"))
1409 options->reverse_diff = 1;
1410 else if (!strncmp(arg, "-S", 2))
1411 options->pickaxe = arg + 2;
1412 else if (!strcmp(arg, "-s"))
1413 options->output_format = DIFF_FORMAT_NO_OUTPUT;
1414 else if (!strncmp(arg, "-O", 2))
1415 options->orderfile = arg + 2;
1416 else if (!strncmp(arg, "--diff-filter=", 14))
1417 options->filter = arg + 14;
1418 else if (!strcmp(arg, "--pickaxe-all"))
1419 options->pickaxe_opts = DIFF_PICKAXE_ALL;
1420 else if (!strcmp(arg, "--pickaxe-regex"))
1421 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
1422 else if (!strncmp(arg, "-B", 2)) {
1423 if ((options->break_opt =
1424 diff_scoreopt_parse(arg)) == -1)
1425 return -1;
1426 }
1427 else if (!strncmp(arg, "-M", 2)) {
1428 if ((options->rename_score =
1429 diff_scoreopt_parse(arg)) == -1)
1430 return -1;
1431 options->detect_rename = DIFF_DETECT_RENAME;
1432 }
1433 else if (!strncmp(arg, "-C", 2)) {
1434 if ((options->rename_score =
1435 diff_scoreopt_parse(arg)) == -1)
1436 return -1;
1437 options->detect_rename = DIFF_DETECT_COPY;
1438 }
1439 else if (!strcmp(arg, "--find-copies-harder"))
1440 options->find_copies_harder = 1;
1441 else if (!strcmp(arg, "--abbrev"))
1442 options->abbrev = DEFAULT_ABBREV;
1443 else if (!strncmp(arg, "--abbrev=", 9)) {
1444 options->abbrev = strtoul(arg + 9, NULL, 10);
1445 if (options->abbrev < MINIMUM_ABBREV)
1446 options->abbrev = MINIMUM_ABBREV;
1447 else if (40 < options->abbrev)
1448 options->abbrev = 40;
1449 }
1450 else
1451 return 0;
1452 return 1;
1453}
1454
1455static int parse_num(const char **cp_p)
1456{
1457 unsigned long num, scale;
1458 int ch, dot;
1459 const char *cp = *cp_p;
1460
1461 num = 0;
1462 scale = 1;
1463 dot = 0;
1464 for(;;) {
1465 ch = *cp;
1466 if ( !dot && ch == '.' ) {
1467 scale = 1;
1468 dot = 1;
1469 } else if ( ch == '%' ) {
1470 scale = dot ? scale*100 : 100;
1471 cp++; /* % is always at the end */
1472 break;
1473 } else if ( ch >= '0' && ch <= '9' ) {
1474 if ( scale < 100000 ) {
1475 scale *= 10;
1476 num = (num*10) + (ch-'0');
1477 }
1478 } else {
1479 break;
1480 }
1481 cp++;
1482 }
1483 *cp_p = cp;
1484
1485 /* user says num divided by scale and we say internally that
1486 * is MAX_SCORE * num / scale.
1487 */
1488 return (num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale);
1489}
1490
1491int diff_scoreopt_parse(const char *opt)
1492{
1493 int opt1, opt2, cmd;
1494
1495 if (*opt++ != '-')
1496 return -1;
1497 cmd = *opt++;
1498 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
1499 return -1; /* that is not a -M, -C nor -B option */
1500
1501 opt1 = parse_num(&opt);
1502 if (cmd != 'B')
1503 opt2 = 0;
1504 else {
1505 if (*opt == 0)
1506 opt2 = 0;
1507 else if (*opt != '/')
1508 return -1; /* we expect -B80/99 or -B80 */
1509 else {
1510 opt++;
1511 opt2 = parse_num(&opt);
1512 }
1513 }
1514 if (*opt != 0)
1515 return -1;
1516 return opt1 | (opt2 << 16);
1517}
1518
1519struct diff_queue_struct diff_queued_diff;
1520
1521void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
1522{
1523 if (queue->alloc <= queue->nr) {
1524 queue->alloc = alloc_nr(queue->alloc);
1525 queue->queue = xrealloc(queue->queue,
1526 sizeof(dp) * queue->alloc);
1527 }
1528 queue->queue[queue->nr++] = dp;
1529}
1530
1531struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
1532 struct diff_filespec *one,
1533 struct diff_filespec *two)
1534{
1535 struct diff_filepair *dp = xmalloc(sizeof(*dp));
1536 dp->one = one;
1537 dp->two = two;
1538 dp->score = 0;
1539 dp->status = 0;
1540 dp->source_stays = 0;
1541 dp->broken_pair = 0;
1542 if (queue)
1543 diff_q(queue, dp);
1544 return dp;
1545}
1546
1547void diff_free_filepair(struct diff_filepair *p)
1548{
1549 diff_free_filespec_data(p->one);
1550 diff_free_filespec_data(p->two);
1551 free(p->one);
1552 free(p->two);
1553 free(p);
1554}
1555
1556/* This is different from find_unique_abbrev() in that
1557 * it stuffs the result with dots for alignment.
1558 */
1559const char *diff_unique_abbrev(const unsigned char *sha1, int len)
1560{
1561 int abblen;
1562 const char *abbrev;
1563 if (len == 40)
1564 return sha1_to_hex(sha1);
1565
1566 abbrev = find_unique_abbrev(sha1, len);
1567 if (!abbrev)
1568 return sha1_to_hex(sha1);
1569 abblen = strlen(abbrev);
1570 if (abblen < 37) {
1571 static char hex[41];
1572 if (len < abblen && abblen <= len + 2)
1573 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
1574 else
1575 sprintf(hex, "%s...", abbrev);
1576 return hex;
1577 }
1578 return sha1_to_hex(sha1);
1579}
1580
1581static void diff_flush_raw(struct diff_filepair *p,
1582 int line_termination,
1583 int inter_name_termination,
1584 struct diff_options *options,
1585 int output_format)
1586{
1587 int two_paths;
1588 char status[10];
1589 int abbrev = options->abbrev;
1590 const char *path_one, *path_two;
1591
1592 path_one = p->one->path;
1593 path_two = p->two->path;
1594 if (line_termination) {
1595 path_one = quote_one(path_one);
1596 path_two = quote_one(path_two);
1597 }
1598
1599 if (p->score)
1600 sprintf(status, "%c%03d", p->status,
1601 (int)(0.5 + p->score * 100.0/MAX_SCORE));
1602 else {
1603 status[0] = p->status;
1604 status[1] = 0;
1605 }
1606 switch (p->status) {
1607 case DIFF_STATUS_COPIED:
1608 case DIFF_STATUS_RENAMED:
1609 two_paths = 1;
1610 break;
1611 case DIFF_STATUS_ADDED:
1612 case DIFF_STATUS_DELETED:
1613 two_paths = 0;
1614 break;
1615 default:
1616 two_paths = 0;
1617 break;
1618 }
1619 if (output_format != DIFF_FORMAT_NAME_STATUS) {
1620 printf(":%06o %06o %s ",
1621 p->one->mode, p->two->mode,
1622 diff_unique_abbrev(p->one->sha1, abbrev));
1623 printf("%s ",
1624 diff_unique_abbrev(p->two->sha1, abbrev));
1625 }
1626 printf("%s%c%s", status, inter_name_termination, path_one);
1627 if (two_paths)
1628 printf("%c%s", inter_name_termination, path_two);
1629 putchar(line_termination);
1630 if (path_one != p->one->path)
1631 free((void*)path_one);
1632 if (path_two != p->two->path)
1633 free((void*)path_two);
1634}
1635
1636static void diff_flush_name(struct diff_filepair *p,
1637 int inter_name_termination,
1638 int line_termination)
1639{
1640 char *path = p->two->path;
1641
1642 if (line_termination)
1643 path = quote_one(p->two->path);
1644 else
1645 path = p->two->path;
1646 printf("%s%c", path, line_termination);
1647 if (p->two->path != path)
1648 free(path);
1649}
1650
1651int diff_unmodified_pair(struct diff_filepair *p)
1652{
1653 /* This function is written stricter than necessary to support
1654 * the currently implemented transformers, but the idea is to
1655 * let transformers to produce diff_filepairs any way they want,
1656 * and filter and clean them up here before producing the output.
1657 */
1658 struct diff_filespec *one, *two;
1659
1660 if (DIFF_PAIR_UNMERGED(p))
1661 return 0; /* unmerged is interesting */
1662
1663 one = p->one;
1664 two = p->two;
1665
1666 /* deletion, addition, mode or type change
1667 * and rename are all interesting.
1668 */
1669 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
1670 DIFF_PAIR_MODE_CHANGED(p) ||
1671 strcmp(one->path, two->path))
1672 return 0;
1673
1674 /* both are valid and point at the same path. that is, we are
1675 * dealing with a change.
1676 */
1677 if (one->sha1_valid && two->sha1_valid &&
1678 !memcmp(one->sha1, two->sha1, sizeof(one->sha1)))
1679 return 1; /* no change */
1680 if (!one->sha1_valid && !two->sha1_valid)
1681 return 1; /* both look at the same file on the filesystem. */
1682 return 0;
1683}
1684
1685static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
1686{
1687 if (diff_unmodified_pair(p))
1688 return;
1689
1690 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
1691 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
1692 return; /* no tree diffs in patch format */
1693
1694 run_diff(p, o);
1695}
1696
1697static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
1698 struct diffstat_t *diffstat)
1699{
1700 if (diff_unmodified_pair(p))
1701 return;
1702
1703 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
1704 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
1705 return; /* no tree diffs in patch format */
1706
1707 run_diffstat(p, o, diffstat);
1708}
1709
88246898
JS
1710static void diff_flush_checkdiff(struct diff_filepair *p,
1711 struct diff_options *o)
1712{
1713 if (diff_unmodified_pair(p))
1714 return;
1715
1716 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
1717 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
1718 return; /* no tree diffs in patch format */
1719
1720 run_checkdiff(p, o);
1721}
1722
6973dcae
JH
1723int diff_queue_is_empty(void)
1724{
1725 struct diff_queue_struct *q = &diff_queued_diff;
1726 int i;
1727 for (i = 0; i < q->nr; i++)
1728 if (!diff_unmodified_pair(q->queue[i]))
1729 return 0;
1730 return 1;
1731}
1732
1733#if DIFF_DEBUG
1734void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
1735{
1736 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
1737 x, one ? one : "",
1738 s->path,
1739 DIFF_FILE_VALID(s) ? "valid" : "invalid",
1740 s->mode,
1741 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
1742 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
1743 x, one ? one : "",
1744 s->size, s->xfrm_flags);
1745}
1746
1747void diff_debug_filepair(const struct diff_filepair *p, int i)
1748{
1749 diff_debug_filespec(p->one, i, "one");
1750 diff_debug_filespec(p->two, i, "two");
1751 fprintf(stderr, "score %d, status %c stays %d broken %d\n",
1752 p->score, p->status ? p->status : '?',
1753 p->source_stays, p->broken_pair);
1754}
1755
1756void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
1757{
1758 int i;
1759 if (msg)
1760 fprintf(stderr, "%s\n", msg);
1761 fprintf(stderr, "q->nr = %d\n", q->nr);
1762 for (i = 0; i < q->nr; i++) {
1763 struct diff_filepair *p = q->queue[i];
1764 diff_debug_filepair(p, i);
1765 }
1766}
1767#endif
1768
1769static void diff_resolve_rename_copy(void)
1770{
1771 int i, j;
1772 struct diff_filepair *p, *pp;
1773 struct diff_queue_struct *q = &diff_queued_diff;
1774
1775 diff_debug_queue("resolve-rename-copy", q);
1776
1777 for (i = 0; i < q->nr; i++) {
1778 p = q->queue[i];
1779 p->status = 0; /* undecided */
1780 if (DIFF_PAIR_UNMERGED(p))
1781 p->status = DIFF_STATUS_UNMERGED;
1782 else if (!DIFF_FILE_VALID(p->one))
1783 p->status = DIFF_STATUS_ADDED;
1784 else if (!DIFF_FILE_VALID(p->two))
1785 p->status = DIFF_STATUS_DELETED;
1786 else if (DIFF_PAIR_TYPE_CHANGED(p))
1787 p->status = DIFF_STATUS_TYPE_CHANGED;
1788
1789 /* from this point on, we are dealing with a pair
1790 * whose both sides are valid and of the same type, i.e.
1791 * either in-place edit or rename/copy edit.
1792 */
1793 else if (DIFF_PAIR_RENAME(p)) {
1794 if (p->source_stays) {
1795 p->status = DIFF_STATUS_COPIED;
1796 continue;
1797 }
1798 /* See if there is some other filepair that
1799 * copies from the same source as us. If so
1800 * we are a copy. Otherwise we are either a
1801 * copy if the path stays, or a rename if it
1802 * does not, but we already handled "stays" case.
1803 */
1804 for (j = i + 1; j < q->nr; j++) {
1805 pp = q->queue[j];
1806 if (strcmp(pp->one->path, p->one->path))
1807 continue; /* not us */
1808 if (!DIFF_PAIR_RENAME(pp))
1809 continue; /* not a rename/copy */
1810 /* pp is a rename/copy from the same source */
1811 p->status = DIFF_STATUS_COPIED;
1812 break;
1813 }
1814 if (!p->status)
1815 p->status = DIFF_STATUS_RENAMED;
1816 }
1817 else if (memcmp(p->one->sha1, p->two->sha1, 20) ||
1818 p->one->mode != p->two->mode)
1819 p->status = DIFF_STATUS_MODIFIED;
1820 else {
1821 /* This is a "no-change" entry and should not
1822 * happen anymore, but prepare for broken callers.
1823 */
1824 error("feeding unmodified %s to diffcore",
1825 p->one->path);
1826 p->status = DIFF_STATUS_UNKNOWN;
1827 }
1828 }
1829 diff_debug_queue("resolve-rename-copy done", q);
1830}
1831
1832static void flush_one_pair(struct diff_filepair *p,
1833 int diff_output_format,
1834 struct diff_options *options,
1835 struct diffstat_t *diffstat)
1836{
1837 int inter_name_termination = '\t';
1838 int line_termination = options->line_termination;
1839 if (!line_termination)
1840 inter_name_termination = 0;
1841
1842 switch (p->status) {
1843 case DIFF_STATUS_UNKNOWN:
1844 break;
1845 case 0:
1846 die("internal error in diff-resolve-rename-copy");
1847 break;
1848 default:
1849 switch (diff_output_format) {
1850 case DIFF_FORMAT_DIFFSTAT:
1851 diff_flush_stat(p, options, diffstat);
1852 break;
88246898
JS
1853 case DIFF_FORMAT_CHECKDIFF:
1854 diff_flush_checkdiff(p, options);
1855 break;
6973dcae
JH
1856 case DIFF_FORMAT_PATCH:
1857 diff_flush_patch(p, options);
1858 break;
1859 case DIFF_FORMAT_RAW:
1860 case DIFF_FORMAT_NAME_STATUS:
1861 diff_flush_raw(p, line_termination,
1862 inter_name_termination,
1863 options, diff_output_format);
1864 break;
1865 case DIFF_FORMAT_NAME:
1866 diff_flush_name(p,
1867 inter_name_termination,
1868 line_termination);
1869 break;
1870 case DIFF_FORMAT_NO_OUTPUT:
1871 break;
1872 }
1873 }
1874}
1875
4bbd261b
SE
1876static void show_file_mode_name(const char *newdelete, struct diff_filespec *fs)
1877{
1878 if (fs->mode)
1879 printf(" %s mode %06o %s\n", newdelete, fs->mode, fs->path);
1880 else
1881 printf(" %s %s\n", newdelete, fs->path);
1882}
1883
1884
1885static void show_mode_change(struct diff_filepair *p, int show_name)
1886{
1887 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
1888 if (show_name)
1889 printf(" mode change %06o => %06o %s\n",
1890 p->one->mode, p->two->mode, p->two->path);
1891 else
1892 printf(" mode change %06o => %06o\n",
1893 p->one->mode, p->two->mode);
1894 }
1895}
1896
1897static void show_rename_copy(const char *renamecopy, struct diff_filepair *p)
1898{
1899 const char *old, *new;
1900
1901 /* Find common prefix */
1902 old = p->one->path;
1903 new = p->two->path;
1904 while (1) {
1905 const char *slash_old, *slash_new;
1906 slash_old = strchr(old, '/');
1907 slash_new = strchr(new, '/');
1908 if (!slash_old ||
1909 !slash_new ||
1910 slash_old - old != slash_new - new ||
1911 memcmp(old, new, slash_new - new))
1912 break;
1913 old = slash_old + 1;
1914 new = slash_new + 1;
1915 }
1916 /* p->one->path thru old is the common prefix, and old and new
1917 * through the end of names are renames
1918 */
1919 if (old != p->one->path)
1920 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
1921 (int)(old - p->one->path), p->one->path,
1922 old, new, (int)(0.5 + p->score * 100.0/MAX_SCORE));
1923 else
1924 printf(" %s %s => %s (%d%%)\n", renamecopy,
1925 p->one->path, p->two->path,
1926 (int)(0.5 + p->score * 100.0/MAX_SCORE));
1927 show_mode_change(p, 0);
1928}
1929
1930static void diff_summary(struct diff_filepair *p)
1931{
1932 switch(p->status) {
1933 case DIFF_STATUS_DELETED:
1934 show_file_mode_name("delete", p->one);
1935 break;
1936 case DIFF_STATUS_ADDED:
1937 show_file_mode_name("create", p->two);
1938 break;
1939 case DIFF_STATUS_COPIED:
1940 show_rename_copy("copy", p);
1941 break;
1942 case DIFF_STATUS_RENAMED:
1943 show_rename_copy("rename", p);
1944 break;
1945 default:
1946 if (p->score) {
1947 printf(" rewrite %s (%d%%)\n", p->two->path,
1948 (int)(0.5 + p->score * 100.0/MAX_SCORE));
1949 show_mode_change(p, 0);
1950 } else show_mode_change(p, 1);
1951 break;
1952 }
1953}
1954
6973dcae
JH
1955void diff_flush(struct diff_options *options)
1956{
1957 struct diff_queue_struct *q = &diff_queued_diff;
1958 int i;
1959 int diff_output_format = options->output_format;
1960 struct diffstat_t *diffstat = NULL;
1961
1962 if (diff_output_format == DIFF_FORMAT_DIFFSTAT || options->with_stat) {
1963 diffstat = xcalloc(sizeof (struct diffstat_t), 1);
1964 diffstat->xm.consume = diffstat_consume;
1965 }
1966
1967 if (options->with_raw) {
1968 for (i = 0; i < q->nr; i++) {
1969 struct diff_filepair *p = q->queue[i];
1970 flush_one_pair(p, DIFF_FORMAT_RAW, options, NULL);
1971 }
1972 putchar(options->line_termination);
1973 }
1974 if (options->with_stat) {
1975 for (i = 0; i < q->nr; i++) {
1976 struct diff_filepair *p = q->queue[i];
1977 flush_one_pair(p, DIFF_FORMAT_DIFFSTAT, options,
1978 diffstat);
1979 }
1980 show_stats(diffstat);
1981 free(diffstat);
1982 diffstat = NULL;
1983 putchar(options->line_termination);
1984 }
1985 for (i = 0; i < q->nr; i++) {
1986 struct diff_filepair *p = q->queue[i];
1987 flush_one_pair(p, diff_output_format, options, diffstat);
6973dcae
JH
1988 }
1989
1990 if (diffstat) {
1991 show_stats(diffstat);
1992 free(diffstat);
1993 }
1994
4bbd261b
SE
1995 for (i = 0; i < q->nr; i++) {
1996 if (options->summary)
1997 diff_summary(q->queue[i]);
1998 diff_free_filepair(q->queue[i]);
1999 }
2000
6973dcae
JH
2001 free(q->queue);
2002 q->queue = NULL;
2003 q->nr = q->alloc = 0;
2004}
2005
2006static void diffcore_apply_filter(const char *filter)
2007{
2008 int i;
2009 struct diff_queue_struct *q = &diff_queued_diff;
2010 struct diff_queue_struct outq;
2011 outq.queue = NULL;
2012 outq.nr = outq.alloc = 0;
2013
2014 if (!filter)
2015 return;
2016
2017 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
2018 int found;
2019 for (i = found = 0; !found && i < q->nr; i++) {
2020 struct diff_filepair *p = q->queue[i];
2021 if (((p->status == DIFF_STATUS_MODIFIED) &&
2022 ((p->score &&
2023 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
2024 (!p->score &&
2025 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
2026 ((p->status != DIFF_STATUS_MODIFIED) &&
2027 strchr(filter, p->status)))
2028 found++;
2029 }
2030 if (found)
2031 return;
2032
2033 /* otherwise we will clear the whole queue
2034 * by copying the empty outq at the end of this
2035 * function, but first clear the current entries
2036 * in the queue.
2037 */
2038 for (i = 0; i < q->nr; i++)
2039 diff_free_filepair(q->queue[i]);
2040 }
2041 else {
2042 /* Only the matching ones */
2043 for (i = 0; i < q->nr; i++) {
2044 struct diff_filepair *p = q->queue[i];
2045
2046 if (((p->status == DIFF_STATUS_MODIFIED) &&
2047 ((p->score &&
2048 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
2049 (!p->score &&
2050 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
2051 ((p->status != DIFF_STATUS_MODIFIED) &&
2052 strchr(filter, p->status)))
2053 diff_q(&outq, p);
2054 else
2055 diff_free_filepair(p);
2056 }
2057 }
2058 free(q->queue);
2059 *q = outq;
2060}
2061
2062void diffcore_std(struct diff_options *options)
2063{
2064 if (options->break_opt != -1)
2065 diffcore_break(options->break_opt);
2066 if (options->detect_rename)
2067 diffcore_rename(options);
2068 if (options->break_opt != -1)
2069 diffcore_merge_broken();
2070 if (options->pickaxe)
2071 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
2072 if (options->orderfile)
2073 diffcore_order(options->orderfile);
2074 diff_resolve_rename_copy();
2075 diffcore_apply_filter(options->filter);
2076}
2077
2078
2079void diffcore_std_no_resolve(struct diff_options *options)
2080{
2081 if (options->pickaxe)
2082 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
2083 if (options->orderfile)
2084 diffcore_order(options->orderfile);
2085 diffcore_apply_filter(options->filter);
2086}
2087
2088void diff_addremove(struct diff_options *options,
2089 int addremove, unsigned mode,
2090 const unsigned char *sha1,
2091 const char *base, const char *path)
2092{
2093 char concatpath[PATH_MAX];
2094 struct diff_filespec *one, *two;
2095
2096 /* This may look odd, but it is a preparation for
2097 * feeding "there are unchanged files which should
2098 * not produce diffs, but when you are doing copy
2099 * detection you would need them, so here they are"
2100 * entries to the diff-core. They will be prefixed
2101 * with something like '=' or '*' (I haven't decided
2102 * which but should not make any difference).
2103 * Feeding the same new and old to diff_change()
2104 * also has the same effect.
2105 * Before the final output happens, they are pruned after
2106 * merged into rename/copy pairs as appropriate.
2107 */
2108 if (options->reverse_diff)
2109 addremove = (addremove == '+' ? '-' :
2110 addremove == '-' ? '+' : addremove);
2111
2112 if (!path) path = "";
2113 sprintf(concatpath, "%s%s", base, path);
2114 one = alloc_filespec(concatpath);
2115 two = alloc_filespec(concatpath);
2116
2117 if (addremove != '+')
2118 fill_filespec(one, sha1, mode);
2119 if (addremove != '-')
2120 fill_filespec(two, sha1, mode);
2121
2122 diff_queue(&diff_queued_diff, one, two);
2123}
2124
2125void diff_change(struct diff_options *options,
2126 unsigned old_mode, unsigned new_mode,
2127 const unsigned char *old_sha1,
2128 const unsigned char *new_sha1,
2129 const char *base, const char *path)
2130{
2131 char concatpath[PATH_MAX];
2132 struct diff_filespec *one, *two;
2133
2134 if (options->reverse_diff) {
2135 unsigned tmp;
2136 const unsigned char *tmp_c;
2137 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
2138 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
2139 }
2140 if (!path) path = "";
2141 sprintf(concatpath, "%s%s", base, path);
2142 one = alloc_filespec(concatpath);
2143 two = alloc_filespec(concatpath);
2144 fill_filespec(one, old_sha1, old_mode);
2145 fill_filespec(two, new_sha1, new_mode);
2146
2147 diff_queue(&diff_queued_diff, one, two);
2148}
2149
2150void diff_unmerge(struct diff_options *options,
2151 const char *path)
2152{
2153 struct diff_filespec *one, *two;
2154 one = alloc_filespec(path);
2155 two = alloc_filespec(path);
2156 diff_queue(&diff_queued_diff, one, two);
2157}