]> git.ipfire.org Git - thirdparty/git.git/blame - diff.c
Fix an "implicit function definition" warning.
[thirdparty/git.git] / diff.c
CommitLineData
6973dcae
JH
1/*
2 * Copyright (C) 2005 Junio C Hamano
3 */
6973dcae
JH
4#include "cache.h"
5#include "quote.h"
6#include "diff.h"
7#include "diffcore.h"
051308f6 8#include "delta.h"
6973dcae 9#include "xdiff-interface.h"
7c92fe0e 10#include "color.h"
6973dcae 11
1510fea7
SP
12#ifdef NO_FAST_WORKING_DIRECTORY
13#define FAST_WORKING_DIRECTORY 0
14#else
15#define FAST_WORKING_DIRECTORY 1
16#endif
17
6973dcae
JH
18static int use_size_cache;
19
96f1e58f 20static int diff_detect_rename_default;
801235c5 21static int diff_rename_limit_default = -1;
96f1e58f 22static int diff_use_color_default;
6973dcae 23
7c92fe0e 24static char diff_colors[][COLOR_MAXLEN] = {
f37399e6 25 "\033[m", /* reset */
448c3ef1
JH
26 "", /* PLAIN (normal) */
27 "\033[1m", /* METAINFO (bold) */
28 "\033[36m", /* FRAGINFO (cyan) */
29 "\033[31m", /* OLD (red) */
30 "\033[32m", /* NEW (green) */
31 "\033[33m", /* COMMIT (yellow) */
32 "\033[41m", /* WHITESPACE (red background) */
cd112cef
JS
33};
34
801235c5
JH
35static int parse_diff_color_slot(const char *var, int ofs)
36{
37 if (!strcasecmp(var+ofs, "plain"))
38 return DIFF_PLAIN;
39 if (!strcasecmp(var+ofs, "meta"))
40 return DIFF_METAINFO;
41 if (!strcasecmp(var+ofs, "frag"))
42 return DIFF_FRAGINFO;
43 if (!strcasecmp(var+ofs, "old"))
44 return DIFF_FILE_OLD;
45 if (!strcasecmp(var+ofs, "new"))
46 return DIFF_FILE_NEW;
ce436973
JK
47 if (!strcasecmp(var+ofs, "commit"))
48 return DIFF_COMMIT;
448c3ef1
JH
49 if (!strcasecmp(var+ofs, "whitespace"))
50 return DIFF_WHITESPACE;
801235c5
JH
51 die("bad config variable '%s'", var);
52}
53
83ad63cf
JH
54/*
55 * These are to give UI layer defaults.
56 * The core-level commands such as git-diff-files should
57 * never be affected by the setting of diff.renames
58 * the user happens to have in the configuration file.
59 */
60int git_diff_ui_config(const char *var, const char *value)
801235c5
JH
61{
62 if (!strcmp(var, "diff.renamelimit")) {
63 diff_rename_limit_default = git_config_int(var, value);
64 return 0;
65 }
a159ca0c 66 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
7c92fe0e 67 diff_use_color_default = git_config_colorbool(var, value);
801235c5
JH
68 return 0;
69 }
b68ea12e
EW
70 if (!strcmp(var, "diff.renames")) {
71 if (!value)
72 diff_detect_rename_default = DIFF_DETECT_RENAME;
73 else if (!strcasecmp(value, "copies") ||
74 !strcasecmp(value, "copy"))
75 diff_detect_rename_default = DIFF_DETECT_COPY;
76 else if (git_config_bool(var,value))
77 diff_detect_rename_default = DIFF_DETECT_RENAME;
78 return 0;
79 }
a159ca0c 80 if (!strncmp(var, "diff.color.", 11) || !strncmp(var, "color.diff.", 11)) {
801235c5 81 int slot = parse_diff_color_slot(var, 11);
7c92fe0e 82 color_parse(value, var, diff_colors[slot]);
801235c5
JH
83 return 0;
84 }
85 return git_default_config(var, value);
86}
87
6973dcae
JH
88static char *quote_one(const char *str)
89{
90 int needlen;
91 char *xp;
92
93 if (!str)
94 return NULL;
95 needlen = quote_c_style(str, NULL, NULL, 0);
96 if (!needlen)
9befac47 97 return xstrdup(str);
6973dcae
JH
98 xp = xmalloc(needlen + 1);
99 quote_c_style(str, xp, NULL, 0);
100 return xp;
101}
102
103static char *quote_two(const char *one, const char *two)
104{
105 int need_one = quote_c_style(one, NULL, NULL, 1);
106 int need_two = quote_c_style(two, NULL, NULL, 1);
107 char *xp;
108
109 if (need_one + need_two) {
110 if (!need_one) need_one = strlen(one);
111 if (!need_two) need_one = strlen(two);
112
113 xp = xmalloc(need_one + need_two + 3);
114 xp[0] = '"';
115 quote_c_style(one, xp + 1, NULL, 1);
116 quote_c_style(two, xp + need_one + 1, NULL, 1);
117 strcpy(xp + need_one + need_two + 1, "\"");
118 return xp;
119 }
120 need_one = strlen(one);
121 need_two = strlen(two);
122 xp = xmalloc(need_one + need_two + 1);
123 strcpy(xp, one);
124 strcpy(xp + need_one, two);
125 return xp;
126}
127
128static const char *external_diff(void)
129{
130 static const char *external_diff_cmd = NULL;
131 static int done_preparing = 0;
132
133 if (done_preparing)
134 return external_diff_cmd;
135 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
136 done_preparing = 1;
137 return external_diff_cmd;
138}
139
140#define TEMPFILE_PATH_LEN 50
141
142static struct diff_tempfile {
143 const char *name; /* filename external diff should read from */
144 char hex[41];
145 char mode[10];
146 char tmp_path[TEMPFILE_PATH_LEN];
147} diff_temp[2];
148
149static int count_lines(const char *data, int size)
150{
151 int count, ch, completely_empty = 1, nl_just_seen = 0;
152 count = 0;
153 while (0 < size--) {
154 ch = *data++;
155 if (ch == '\n') {
156 count++;
157 nl_just_seen = 1;
158 completely_empty = 0;
159 }
160 else {
161 nl_just_seen = 0;
162 completely_empty = 0;
163 }
164 }
165 if (completely_empty)
166 return 0;
167 if (!nl_just_seen)
168 count++; /* no trailing newline */
169 return count;
170}
171
172static void print_line_count(int count)
173{
174 switch (count) {
175 case 0:
176 printf("0,0");
177 break;
178 case 1:
179 printf("1");
180 break;
181 default:
182 printf("1,%d", count);
183 break;
184 }
185}
186
187static void copy_file(int prefix, const char *data, int size)
188{
189 int ch, nl_just_seen = 1;
190 while (0 < size--) {
191 ch = *data++;
192 if (nl_just_seen)
193 putchar(prefix);
194 putchar(ch);
195 if (ch == '\n')
196 nl_just_seen = 1;
197 else
198 nl_just_seen = 0;
199 }
200 if (!nl_just_seen)
201 printf("\n\\ No newline at end of file\n");
202}
203
204static void emit_rewrite_diff(const char *name_a,
205 const char *name_b,
206 struct diff_filespec *one,
207 struct diff_filespec *two)
208{
209 int lc_a, lc_b;
210 diff_populate_filespec(one, 0);
211 diff_populate_filespec(two, 0);
212 lc_a = count_lines(one->data, one->size);
213 lc_b = count_lines(two->data, two->size);
50892777
JH
214 name_a += (*name_a == '/');
215 name_b += (*name_b == '/');
bc1a5807 216 printf("--- a/%s\n+++ b/%s\n@@ -", name_a, name_b);
6973dcae
JH
217 print_line_count(lc_a);
218 printf(" +");
219 print_line_count(lc_b);
220 printf(" @@\n");
221 if (lc_a)
222 copy_file('-', one->data, one->size);
223 if (lc_b)
224 copy_file('+', two->data, two->size);
225}
226
227static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
228{
229 if (!DIFF_FILE_VALID(one)) {
d2543b8e 230 mf->ptr = (char *)""; /* does not matter */
6973dcae
JH
231 mf->size = 0;
232 return 0;
233 }
234 else if (diff_populate_filespec(one, 0))
235 return -1;
236 mf->ptr = one->data;
237 mf->size = one->size;
238 return 0;
239}
240
f59a59e2
JS
241struct diff_words_buffer {
242 mmfile_t text;
243 long alloc;
244 long current; /* output pointer */
245 int suppressed_newline;
246};
247
248static void diff_words_append(char *line, unsigned long len,
249 struct diff_words_buffer *buffer)
250{
251 if (buffer->text.size + len > buffer->alloc) {
252 buffer->alloc = (buffer->text.size + len) * 3 / 2;
253 buffer->text.ptr = xrealloc(buffer->text.ptr, buffer->alloc);
254 }
255 line++;
256 len--;
257 memcpy(buffer->text.ptr + buffer->text.size, line, len);
258 buffer->text.size += len;
259}
260
261struct diff_words_data {
262 struct xdiff_emit_state xm;
263 struct diff_words_buffer minus, plus;
264};
265
266static void print_word(struct diff_words_buffer *buffer, int len, int color,
267 int suppress_newline)
268{
269 const char *ptr;
270 int eol = 0;
271
272 if (len == 0)
273 return;
274
275 ptr = buffer->text.ptr + buffer->current;
276 buffer->current += len;
277
278 if (ptr[len - 1] == '\n') {
279 eol = 1;
280 len--;
281 }
282
283 fputs(diff_get_color(1, color), stdout);
284 fwrite(ptr, len, 1, stdout);
285 fputs(diff_get_color(1, DIFF_RESET), stdout);
286
287 if (eol) {
288 if (suppress_newline)
289 buffer->suppressed_newline = 1;
290 else
291 putchar('\n');
292 }
293}
294
295static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
296{
297 struct diff_words_data *diff_words = priv;
298
299 if (diff_words->minus.suppressed_newline) {
300 if (line[0] != '+')
301 putchar('\n');
302 diff_words->minus.suppressed_newline = 0;
303 }
304
305 len--;
306 switch (line[0]) {
307 case '-':
308 print_word(&diff_words->minus, len, DIFF_FILE_OLD, 1);
309 break;
310 case '+':
311 print_word(&diff_words->plus, len, DIFF_FILE_NEW, 0);
312 break;
313 case ' ':
314 print_word(&diff_words->plus, len, DIFF_PLAIN, 0);
315 diff_words->minus.current += len;
316 break;
317 }
318}
319
320/* this executes the word diff on the accumulated buffers */
321static void diff_words_show(struct diff_words_data *diff_words)
322{
323 xpparam_t xpp;
324 xdemitconf_t xecfg;
325 xdemitcb_t ecb;
326 mmfile_t minus, plus;
327 int i;
328
329 minus.size = diff_words->minus.text.size;
330 minus.ptr = xmalloc(minus.size);
331 memcpy(minus.ptr, diff_words->minus.text.ptr, minus.size);
332 for (i = 0; i < minus.size; i++)
333 if (isspace(minus.ptr[i]))
334 minus.ptr[i] = '\n';
335 diff_words->minus.current = 0;
336
337 plus.size = diff_words->plus.text.size;
338 plus.ptr = xmalloc(plus.size);
339 memcpy(plus.ptr, diff_words->plus.text.ptr, plus.size);
340 for (i = 0; i < plus.size; i++)
341 if (isspace(plus.ptr[i]))
342 plus.ptr[i] = '\n';
343 diff_words->plus.current = 0;
344
345 xpp.flags = XDF_NEED_MINIMAL;
346 xecfg.ctxlen = diff_words->minus.alloc + diff_words->plus.alloc;
347 xecfg.flags = 0;
348 ecb.outf = xdiff_outf;
349 ecb.priv = diff_words;
350 diff_words->xm.consume = fn_out_diff_words_aux;
351 xdl_diff(&minus, &plus, &xpp, &xecfg, &ecb);
352
353 free(minus.ptr);
354 free(plus.ptr);
355 diff_words->minus.text.size = diff_words->plus.text.size = 0;
356
357 if (diff_words->minus.suppressed_newline) {
358 putchar('\n');
359 diff_words->minus.suppressed_newline = 0;
360 }
361}
362
6973dcae 363struct emit_callback {
cd112cef
JS
364 struct xdiff_emit_state xm;
365 int nparents, color_diff;
6973dcae 366 const char **label_path;
f59a59e2 367 struct diff_words_data *diff_words;
6973dcae
JH
368};
369
f59a59e2
JS
370static void free_diff_words_data(struct emit_callback *ecbdata)
371{
372 if (ecbdata->diff_words) {
373 /* flush buffers */
374 if (ecbdata->diff_words->minus.text.size ||
375 ecbdata->diff_words->plus.text.size)
376 diff_words_show(ecbdata->diff_words);
377
378 if (ecbdata->diff_words->minus.text.ptr)
379 free (ecbdata->diff_words->minus.text.ptr);
380 if (ecbdata->diff_words->plus.text.ptr)
381 free (ecbdata->diff_words->plus.text.ptr);
382 free(ecbdata->diff_words);
383 ecbdata->diff_words = NULL;
384 }
385}
386
ce436973 387const char *diff_get_color(int diff_use_color, enum color_diff ix)
cd112cef
JS
388{
389 if (diff_use_color)
50f575fc
LT
390 return diff_colors[ix];
391 return "";
cd112cef
JS
392}
393
448c3ef1
JH
394static void emit_line(const char *set, const char *reset, const char *line, int len)
395{
396 if (len > 0 && line[len-1] == '\n')
397 len--;
398 fputs(set, stdout);
399 fwrite(line, len, 1, stdout);
400 puts(reset);
401}
402
403static void emit_add_line(const char *reset, struct emit_callback *ecbdata, const char *line, int len)
404{
405 int col0 = ecbdata->nparents;
406 int last_tab_in_indent = -1;
407 int last_space_in_indent = -1;
408 int i;
409 int tail = len;
410 int need_highlight_leading_space = 0;
411 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
412 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
413
414 if (!*ws) {
415 emit_line(set, reset, line, len);
416 return;
417 }
418
419 /* The line is a newly added line. Does it have funny leading
420 * whitespaces? In indent, SP should never precede a TAB.
421 */
422 for (i = col0; i < len; i++) {
423 if (line[i] == '\t') {
424 last_tab_in_indent = i;
425 if (0 <= last_space_in_indent)
426 need_highlight_leading_space = 1;
427 }
428 else if (line[i] == ' ')
429 last_space_in_indent = i;
430 else
431 break;
432 }
433 fputs(set, stdout);
434 fwrite(line, col0, 1, stdout);
435 fputs(reset, stdout);
436 if (((i == len) || line[i] == '\n') && i != col0) {
437 /* The whole line was indent */
438 emit_line(ws, reset, line + col0, len - col0);
439 return;
440 }
441 i = col0;
442 if (need_highlight_leading_space) {
443 while (i < last_tab_in_indent) {
444 if (line[i] == ' ') {
445 fputs(ws, stdout);
446 putchar(' ');
447 fputs(reset, stdout);
448 }
449 else
450 putchar(line[i]);
451 i++;
452 }
453 }
454 tail = len - 1;
455 if (line[tail] == '\n' && i < tail)
456 tail--;
457 while (i < tail) {
458 if (!isspace(line[tail]))
459 break;
460 tail--;
461 }
462 if ((i < tail && line[tail + 1] != '\n')) {
463 /* This has whitespace between tail+1..len */
464 fputs(set, stdout);
465 fwrite(line + i, tail - i + 1, 1, stdout);
466 fputs(reset, stdout);
467 emit_line(ws, reset, line + tail + 1, len - tail - 1);
468 }
469 else
470 emit_line(set, reset, line + i, len - i);
471}
472
cd112cef 473static void fn_out_consume(void *priv, char *line, unsigned long len)
6973dcae
JH
474{
475 int i;
448c3ef1 476 int color;
6973dcae 477 struct emit_callback *ecbdata = priv;
ce436973
JK
478 const char *set = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
479 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
6973dcae
JH
480
481 if (ecbdata->label_path[0]) {
50f575fc
LT
482 printf("%s--- %s%s\n", set, ecbdata->label_path[0], reset);
483 printf("%s+++ %s%s\n", set, ecbdata->label_path[1], reset);
6973dcae
JH
484 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
485 }
cd112cef
JS
486
487 /* This is not really necessary for now because
488 * this codepath only deals with two-way diffs.
489 */
490 for (i = 0; i < len && line[i] == '@'; i++)
491 ;
492 if (2 <= i && i < len && line[i] == ' ') {
493 ecbdata->nparents = i - 1;
448c3ef1
JH
494 emit_line(diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO),
495 reset, line, len);
496 return;
cd112cef 497 }
448c3ef1
JH
498
499 if (len < ecbdata->nparents) {
50f575fc 500 set = reset;
448c3ef1
JH
501 emit_line(reset, reset, line, len);
502 return;
cd112cef 503 }
448c3ef1
JH
504
505 color = DIFF_PLAIN;
506 if (ecbdata->diff_words && ecbdata->nparents != 1)
507 /* fall back to normal diff */
508 free_diff_words_data(ecbdata);
509 if (ecbdata->diff_words) {
510 if (line[0] == '-') {
511 diff_words_append(line, len,
512 &ecbdata->diff_words->minus);
513 return;
514 } else if (line[0] == '+') {
515 diff_words_append(line, len,
516 &ecbdata->diff_words->plus);
517 return;
518 }
519 if (ecbdata->diff_words->minus.text.size ||
520 ecbdata->diff_words->plus.text.size)
521 diff_words_show(ecbdata->diff_words);
522 line++;
50f575fc 523 len--;
448c3ef1
JH
524 emit_line(set, reset, line, len);
525 return;
526 }
527 for (i = 0; i < ecbdata->nparents && len; i++) {
528 if (line[i] == '-')
529 color = DIFF_FILE_OLD;
530 else if (line[i] == '+')
531 color = DIFF_FILE_NEW;
532 }
533
534 if (color != DIFF_FILE_NEW) {
535 emit_line(diff_get_color(ecbdata->color_diff, color),
536 reset, line, len);
537 return;
538 }
539 emit_add_line(reset, ecbdata, line, len);
6973dcae
JH
540}
541
542static char *pprint_rename(const char *a, const char *b)
543{
544 const char *old = a;
545 const char *new = b;
546 char *name = NULL;
547 int pfx_length, sfx_length;
548 int len_a = strlen(a);
549 int len_b = strlen(b);
e5bfbf9b
AJ
550 int qlen_a = quote_c_style(a, NULL, NULL, 0);
551 int qlen_b = quote_c_style(b, NULL, NULL, 0);
552
553 if (qlen_a || qlen_b) {
554 if (qlen_a) len_a = qlen_a;
555 if (qlen_b) len_b = qlen_b;
556 name = xmalloc( len_a + len_b + 5 );
557 if (qlen_a)
558 quote_c_style(a, name, NULL, 0);
559 else
560 memcpy(name, a, len_a);
561 memcpy(name + len_a, " => ", 4);
562 if (qlen_b)
563 quote_c_style(b, name + len_a + 4, NULL, 0);
564 else
565 memcpy(name + len_a + 4, b, len_b + 1);
566 return name;
567 }
6973dcae
JH
568
569 /* Find common prefix */
570 pfx_length = 0;
571 while (*old && *new && *old == *new) {
572 if (*old == '/')
573 pfx_length = old - a + 1;
574 old++;
575 new++;
576 }
577
578 /* Find common suffix */
579 old = a + len_a;
580 new = b + len_b;
581 sfx_length = 0;
582 while (a <= old && b <= new && *old == *new) {
583 if (*old == '/')
584 sfx_length = len_a - (old - a);
585 old--;
586 new--;
587 }
588
589 /*
590 * pfx{mid-a => mid-b}sfx
591 * {pfx-a => pfx-b}sfx
592 * pfx{sfx-a => sfx-b}
593 * name-a => name-b
594 */
595 if (pfx_length + sfx_length) {
cc908b82
JH
596 int a_midlen = len_a - pfx_length - sfx_length;
597 int b_midlen = len_b - pfx_length - sfx_length;
598 if (a_midlen < 0) a_midlen = 0;
599 if (b_midlen < 0) b_midlen = 0;
600
e3008464 601 name = xmalloc(pfx_length + a_midlen + b_midlen + sfx_length + 7);
6973dcae
JH
602 sprintf(name, "%.*s{%.*s => %.*s}%s",
603 pfx_length, a,
cc908b82
JH
604 a_midlen, a + pfx_length,
605 b_midlen, b + pfx_length,
6973dcae
JH
606 a + len_a - sfx_length);
607 }
608 else {
609 name = xmalloc(len_a + len_b + 5);
610 sprintf(name, "%s => %s", a, b);
611 }
612 return name;
613}
614
615struct diffstat_t {
616 struct xdiff_emit_state xm;
617
618 int nr;
619 int alloc;
620 struct diffstat_file {
621 char *name;
622 unsigned is_unmerged:1;
623 unsigned is_binary:1;
624 unsigned is_renamed:1;
625 unsigned int added, deleted;
626 } **files;
627};
628
629static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
630 const char *name_a,
631 const char *name_b)
632{
633 struct diffstat_file *x;
634 x = xcalloc(sizeof (*x), 1);
635 if (diffstat->nr == diffstat->alloc) {
636 diffstat->alloc = alloc_nr(diffstat->alloc);
637 diffstat->files = xrealloc(diffstat->files,
638 diffstat->alloc * sizeof(x));
639 }
640 diffstat->files[diffstat->nr++] = x;
641 if (name_b) {
642 x->name = pprint_rename(name_a, name_b);
643 x->is_renamed = 1;
644 }
645 else
9befac47 646 x->name = xstrdup(name_a);
6973dcae
JH
647 return x;
648}
649
650static void diffstat_consume(void *priv, char *line, unsigned long len)
651{
652 struct diffstat_t *diffstat = priv;
653 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
654
655 if (line[0] == '+')
656 x->added++;
657 else if (line[0] == '-')
658 x->deleted++;
659}
660
698ce6f8 661const char mime_boundary_leader[] = "------------";
6973dcae 662
a2540023
JH
663static int scale_linear(int it, int width, int max_change)
664{
665 /*
3ed74e60
JS
666 * make sure that at least one '-' is printed if there were deletions,
667 * and likewise for '+'.
a2540023 668 */
3ed74e60
JS
669 if (max_change < 2)
670 return it;
671 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
a2540023
JH
672}
673
785f7432
JH
674static void show_name(const char *prefix, const char *name, int len,
675 const char *reset, const char *set)
a2540023 676{
785f7432 677 printf(" %s%s%-*s%s |", set, prefix, len, name, reset);
a2540023
JH
678}
679
785f7432 680static void show_graph(char ch, int cnt, const char *set, const char *reset)
a2540023
JH
681{
682 if (cnt <= 0)
683 return;
785f7432 684 printf("%s", set);
a2540023
JH
685 while (cnt--)
686 putchar(ch);
785f7432 687 printf("%s", reset);
a2540023
JH
688}
689
690static void show_stats(struct diffstat_t* data, struct diff_options *options)
6973dcae 691{
6973dcae 692 int i, len, add, del, total, adds = 0, dels = 0;
a2540023 693 int max_change = 0, max_len = 0;
6973dcae 694 int total_files = data->nr;
a2540023 695 int width, name_width;
785f7432 696 const char *reset, *set, *add_c, *del_c;
6973dcae
JH
697
698 if (data->nr == 0)
699 return;
700
a2540023
JH
701 width = options->stat_width ? options->stat_width : 80;
702 name_width = options->stat_name_width ? options->stat_name_width : 50;
703
704 /* Sanity: give at least 5 columns to the graph,
705 * but leave at least 10 columns for the name.
706 */
707 if (width < name_width + 15) {
708 if (name_width <= 25)
709 width = name_width + 15;
710 else
711 name_width = width - 15;
712 }
713
714 /* Find the longest filename and max number of changes */
785f7432
JH
715 reset = diff_get_color(options->color_diff, DIFF_RESET);
716 set = diff_get_color(options->color_diff, DIFF_PLAIN);
717 add_c = diff_get_color(options->color_diff, DIFF_FILE_NEW);
718 del_c = diff_get_color(options->color_diff, DIFF_FILE_OLD);
719
6973dcae
JH
720 for (i = 0; i < data->nr; i++) {
721 struct diffstat_file *file = data->files[i];
a2540023
JH
722 int change = file->added + file->deleted;
723
e5bfbf9b
AJ
724 if (!file->is_renamed) { /* renames are already quoted by pprint_rename */
725 len = quote_c_style(file->name, NULL, NULL, 0);
726 if (len) {
727 char *qname = xmalloc(len + 1);
728 quote_c_style(file->name, qname, NULL, 0);
729 free(file->name);
730 file->name = qname;
731 }
a2540023 732 }
6973dcae
JH
733
734 len = strlen(file->name);
735 if (max_len < len)
736 max_len = len;
737
738 if (file->is_binary || file->is_unmerged)
739 continue;
a2540023
JH
740 if (max_change < change)
741 max_change = change;
6973dcae
JH
742 }
743
a2540023
JH
744 /* Compute the width of the graph part;
745 * 10 is for one blank at the beginning of the line plus
746 * " | count " between the name and the graph.
747 *
748 * From here on, name_width is the width of the name area,
749 * and width is the width of the graph area.
750 */
751 name_width = (name_width < max_len) ? name_width : max_len;
752 if (width < (name_width + 10) + max_change)
753 width = width - (name_width + 10);
754 else
755 width = max_change;
756
6973dcae 757 for (i = 0; i < data->nr; i++) {
d2543b8e 758 const char *prefix = "";
6973dcae
JH
759 char *name = data->files[i]->name;
760 int added = data->files[i]->added;
761 int deleted = data->files[i]->deleted;
a2540023 762 int name_len;
6973dcae
JH
763
764 /*
765 * "scale" the filename
766 */
a2540023
JH
767 len = name_width;
768 name_len = strlen(name);
769 if (name_width < name_len) {
6973dcae
JH
770 char *slash;
771 prefix = "...";
a2540023
JH
772 len -= 3;
773 name += name_len - len;
6973dcae
JH
774 slash = strchr(name, '/');
775 if (slash)
776 name = slash;
777 }
6973dcae
JH
778
779 if (data->files[i]->is_binary) {
785f7432 780 show_name(prefix, name, len, reset, set);
a2540023 781 printf(" Bin\n");
6973dcae
JH
782 goto free_diffstat_file;
783 }
784 else if (data->files[i]->is_unmerged) {
785f7432 785 show_name(prefix, name, len, reset, set);
a2540023 786 printf(" Unmerged\n");
6973dcae
JH
787 goto free_diffstat_file;
788 }
789 else if (!data->files[i]->is_renamed &&
790 (added + deleted == 0)) {
791 total_files--;
792 goto free_diffstat_file;
793 }
794
a2540023
JH
795 /*
796 * scale the add/delete
797 */
6973dcae
JH
798 add = added;
799 del = deleted;
800 total = add + del;
801 adds += add;
802 dels += del;
803
a2540023 804 if (width <= max_change) {
a2540023 805 add = scale_linear(add, width, max_change);
3ed74e60
JS
806 del = scale_linear(del, width, max_change);
807 total = add + del;
6973dcae 808 }
785f7432 809 show_name(prefix, name, len, reset, set);
a2540023 810 printf("%5d ", added + deleted);
785f7432
JH
811 show_graph('+', add, add_c, reset);
812 show_graph('-', del, del_c, reset);
a2540023 813 putchar('\n');
6973dcae
JH
814 free_diffstat_file:
815 free(data->files[i]->name);
816 free(data->files[i]);
817 }
818 free(data->files);
785f7432
JH
819 printf("%s %d files changed, %d insertions(+), %d deletions(-)%s\n",
820 set, total_files, adds, dels, reset);
6973dcae
JH
821}
822
ebd124c6
NP
823static void show_shortstats(struct diffstat_t* data)
824{
825 int i, adds = 0, dels = 0, total_files = data->nr;
826
827 if (data->nr == 0)
828 return;
829
830 for (i = 0; i < data->nr; i++) {
831 if (!data->files[i]->is_binary &&
832 !data->files[i]->is_unmerged) {
833 int added = data->files[i]->added;
834 int deleted= data->files[i]->deleted;
835 if (!data->files[i]->is_renamed &&
836 (added + deleted == 0)) {
837 total_files--;
838 } else {
839 adds += added;
840 dels += deleted;
841 }
842 }
843 free(data->files[i]->name);
844 free(data->files[i]);
845 }
846 free(data->files);
847
848 printf(" %d files changed, %d insertions(+), %d deletions(-)\n",
849 total_files, adds, dels);
850}
851
74e2abe5
JH
852static void show_numstat(struct diffstat_t* data, struct diff_options *options)
853{
854 int i;
855
856 for (i = 0; i < data->nr; i++) {
857 struct diffstat_file *file = data->files[i];
858
bfddbc5e
JH
859 if (file->is_binary)
860 printf("-\t-\t");
861 else
862 printf("%d\t%d\t", file->added, file->deleted);
e5bfbf9b 863 if (options->line_termination && !file->is_renamed &&
74e2abe5
JH
864 quote_c_style(file->name, NULL, NULL, 0))
865 quote_c_style(file->name, NULL, stdout, 0);
866 else
867 fputs(file->name, stdout);
868 putchar(options->line_termination);
869 }
870}
871
88246898
JS
872struct checkdiff_t {
873 struct xdiff_emit_state xm;
874 const char *filename;
875 int lineno;
876};
877
878static void checkdiff_consume(void *priv, char *line, unsigned long len)
879{
880 struct checkdiff_t *data = priv;
881
882 if (line[0] == '+') {
883 int i, spaces = 0;
884
88246898
JS
885 /* check space before tab */
886 for (i = 1; i < len && (line[i] == ' ' || line[i] == '\t'); i++)
887 if (line[i] == ' ')
888 spaces++;
889 if (line[i - 1] == '\t' && spaces)
890 printf("%s:%d: space before tab:%.*s\n",
891 data->filename, data->lineno, (int)len, line);
892
893 /* check white space at line end */
894 if (line[len - 1] == '\n')
895 len--;
896 if (isspace(line[len - 1]))
897 printf("%s:%d: white space at end: %.*s\n",
898 data->filename, data->lineno, (int)len, line);
e6d40d65
JS
899
900 data->lineno++;
88246898
JS
901 } else if (line[0] == ' ')
902 data->lineno++;
903 else if (line[0] == '@') {
904 char *plus = strchr(line, '+');
905 if (plus)
9e848163 906 data->lineno = strtol(plus, NULL, 10);
88246898
JS
907 else
908 die("invalid diff");
909 }
910}
911
0660626c
JH
912static unsigned char *deflate_it(char *data,
913 unsigned long size,
914 unsigned long *result_size)
051308f6 915{
0660626c
JH
916 int bound;
917 unsigned char *deflated;
918 z_stream stream;
919
920 memset(&stream, 0, sizeof(stream));
12f6c308 921 deflateInit(&stream, zlib_compression_level);
0660626c
JH
922 bound = deflateBound(&stream, size);
923 deflated = xmalloc(bound);
924 stream.next_out = deflated;
925 stream.avail_out = bound;
926
927 stream.next_in = (unsigned char *)data;
928 stream.avail_in = size;
929 while (deflate(&stream, Z_FINISH) == Z_OK)
930 ; /* nothing */
931 deflateEnd(&stream);
932 *result_size = stream.total_out;
933 return deflated;
051308f6
JH
934}
935
d4c452f0 936static void emit_binary_diff_body(mmfile_t *one, mmfile_t *two)
051308f6 937{
0660626c
JH
938 void *cp;
939 void *delta;
940 void *deflated;
941 void *data;
942 unsigned long orig_size;
943 unsigned long delta_size;
944 unsigned long deflate_size;
945 unsigned long data_size;
051308f6 946
0660626c
JH
947 /* We could do deflated delta, or we could do just deflated two,
948 * whichever is smaller.
051308f6 949 */
0660626c
JH
950 delta = NULL;
951 deflated = deflate_it(two->ptr, two->size, &deflate_size);
952 if (one->size && two->size) {
953 delta = diff_delta(one->ptr, one->size,
954 two->ptr, two->size,
955 &delta_size, deflate_size);
956 if (delta) {
957 void *to_free = delta;
958 orig_size = delta_size;
959 delta = deflate_it(delta, delta_size, &delta_size);
960 free(to_free);
051308f6
JH
961 }
962 }
051308f6 963
0660626c
JH
964 if (delta && delta_size < deflate_size) {
965 printf("delta %lu\n", orig_size);
966 free(deflated);
967 data = delta;
968 data_size = delta_size;
969 }
970 else {
971 printf("literal %lu\n", two->size);
972 free(delta);
973 data = deflated;
974 data_size = deflate_size;
975 }
051308f6 976
0660626c
JH
977 /* emit data encoded in base85 */
978 cp = data;
979 while (data_size) {
980 int bytes = (52 < data_size) ? 52 : data_size;
051308f6 981 char line[70];
0660626c 982 data_size -= bytes;
051308f6
JH
983 if (bytes <= 26)
984 line[0] = bytes + 'A' - 1;
985 else
986 line[0] = bytes - 26 + 'a' - 1;
987 encode_85(line + 1, cp, bytes);
1d7f171c 988 cp = (char *) cp + bytes;
051308f6
JH
989 puts(line);
990 }
991 printf("\n");
0660626c 992 free(data);
051308f6
JH
993}
994
d4c452f0
JH
995static void emit_binary_diff(mmfile_t *one, mmfile_t *two)
996{
997 printf("GIT binary patch\n");
998 emit_binary_diff_body(one, two);
999 emit_binary_diff_body(two, one);
1000}
1001
6973dcae
JH
1002#define FIRST_FEW_BYTES 8000
1003static int mmfile_is_binary(mmfile_t *mf)
1004{
1005 long sz = mf->size;
1006 if (FIRST_FEW_BYTES < sz)
1007 sz = FIRST_FEW_BYTES;
8c0b2bb6 1008 return !!memchr(mf->ptr, 0, sz);
6973dcae
JH
1009}
1010
1011static void builtin_diff(const char *name_a,
1012 const char *name_b,
1013 struct diff_filespec *one,
1014 struct diff_filespec *two,
1015 const char *xfrm_msg,
051308f6 1016 struct diff_options *o,
6973dcae
JH
1017 int complete_rewrite)
1018{
1019 mmfile_t mf1, mf2;
1020 const char *lbl[2];
1021 char *a_one, *b_two;
ce436973
JK
1022 const char *set = diff_get_color(o->color_diff, DIFF_METAINFO);
1023 const char *reset = diff_get_color(o->color_diff, DIFF_RESET);
6973dcae 1024
50892777
JH
1025 a_one = quote_two("a/", name_a + (*name_a == '/'));
1026 b_two = quote_two("b/", name_b + (*name_b == '/'));
6973dcae
JH
1027 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1028 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
50f575fc 1029 printf("%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
6973dcae
JH
1030 if (lbl[0][0] == '/') {
1031 /* /dev/null */
50f575fc
LT
1032 printf("%snew file mode %06o%s\n", set, two->mode, reset);
1033 if (xfrm_msg && xfrm_msg[0])
1034 printf("%s%s%s\n", set, xfrm_msg, reset);
6973dcae
JH
1035 }
1036 else if (lbl[1][0] == '/') {
50f575fc
LT
1037 printf("%sdeleted file mode %06o%s\n", set, one->mode, reset);
1038 if (xfrm_msg && xfrm_msg[0])
1039 printf("%s%s%s\n", set, xfrm_msg, reset);
6973dcae
JH
1040 }
1041 else {
1042 if (one->mode != two->mode) {
50f575fc
LT
1043 printf("%sold mode %06o%s\n", set, one->mode, reset);
1044 printf("%snew mode %06o%s\n", set, two->mode, reset);
cd112cef 1045 }
50f575fc
LT
1046 if (xfrm_msg && xfrm_msg[0])
1047 printf("%s%s%s\n", set, xfrm_msg, reset);
6973dcae
JH
1048 /*
1049 * we do not run diff between different kind
1050 * of objects.
1051 */
1052 if ((one->mode ^ two->mode) & S_IFMT)
1053 goto free_ab_and_return;
1054 if (complete_rewrite) {
1055 emit_rewrite_diff(name_a, name_b, one, two);
1056 goto free_ab_and_return;
1057 }
1058 }
1059
1060 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1061 die("unable to read files to diff");
1062
6d64ea96 1063 if (!o->text && (mmfile_is_binary(&mf1) || mmfile_is_binary(&mf2))) {
0660626c
JH
1064 /* Quite common confusing case */
1065 if (mf1.size == mf2.size &&
1066 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1067 goto free_ab_and_return;
1068 if (o->binary)
051308f6
JH
1069 emit_binary_diff(&mf1, &mf2);
1070 else
1071 printf("Binary files %s and %s differ\n",
1072 lbl[0], lbl[1]);
1073 }
6973dcae
JH
1074 else {
1075 /* Crazy xdl interfaces.. */
1076 const char *diffopts = getenv("GIT_DIFF_OPTS");
1077 xpparam_t xpp;
1078 xdemitconf_t xecfg;
1079 xdemitcb_t ecb;
1080 struct emit_callback ecbdata;
1081
cd112cef 1082 memset(&ecbdata, 0, sizeof(ecbdata));
6973dcae 1083 ecbdata.label_path = lbl;
cd112cef 1084 ecbdata.color_diff = o->color_diff;
0d21efa5 1085 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
ee1e5412 1086 xecfg.ctxlen = o->context;
6973dcae
JH
1087 xecfg.flags = XDL_EMIT_FUNCNAMES;
1088 if (!diffopts)
1089 ;
1090 else if (!strncmp(diffopts, "--unified=", 10))
1091 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1092 else if (!strncmp(diffopts, "-u", 2))
1093 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
cd112cef 1094 ecb.outf = xdiff_outf;
6973dcae 1095 ecb.priv = &ecbdata;
cd112cef 1096 ecbdata.xm.consume = fn_out_consume;
f59a59e2
JS
1097 if (o->color_diff_words)
1098 ecbdata.diff_words =
1099 xcalloc(1, sizeof(struct diff_words_data));
6973dcae 1100 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
f59a59e2
JS
1101 if (o->color_diff_words)
1102 free_diff_words_data(&ecbdata);
6973dcae
JH
1103 }
1104
1105 free_ab_and_return:
1106 free(a_one);
1107 free(b_two);
1108 return;
1109}
1110
1111static void builtin_diffstat(const char *name_a, const char *name_b,
1112 struct diff_filespec *one,
1113 struct diff_filespec *two,
710158e3 1114 struct diffstat_t *diffstat,
0d21efa5 1115 struct diff_options *o,
710158e3 1116 int complete_rewrite)
6973dcae
JH
1117{
1118 mmfile_t mf1, mf2;
1119 struct diffstat_file *data;
1120
1121 data = diffstat_add(diffstat, name_a, name_b);
1122
1123 if (!one || !two) {
1124 data->is_unmerged = 1;
1125 return;
1126 }
710158e3
JH
1127 if (complete_rewrite) {
1128 diff_populate_filespec(one, 0);
1129 diff_populate_filespec(two, 0);
1130 data->deleted = count_lines(one->data, one->size);
1131 data->added = count_lines(two->data, two->size);
1132 return;
1133 }
6973dcae
JH
1134 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1135 die("unable to read files to diff");
1136
1137 if (mmfile_is_binary(&mf1) || mmfile_is_binary(&mf2))
1138 data->is_binary = 1;
1139 else {
1140 /* Crazy xdl interfaces.. */
1141 xpparam_t xpp;
1142 xdemitconf_t xecfg;
1143 xdemitcb_t ecb;
1144
0d21efa5 1145 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
6973dcae
JH
1146 xecfg.ctxlen = 0;
1147 xecfg.flags = 0;
1148 ecb.outf = xdiff_outf;
1149 ecb.priv = diffstat;
1150 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1151 }
1152}
1153
88246898
JS
1154static void builtin_checkdiff(const char *name_a, const char *name_b,
1155 struct diff_filespec *one,
1156 struct diff_filespec *two)
1157{
1158 mmfile_t mf1, mf2;
1159 struct checkdiff_t data;
1160
1161 if (!two)
1162 return;
1163
1164 memset(&data, 0, sizeof(data));
1165 data.xm.consume = checkdiff_consume;
1166 data.filename = name_b ? name_b : name_a;
1167 data.lineno = 0;
1168
1169 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1170 die("unable to read files to diff");
1171
1172 if (mmfile_is_binary(&mf2))
1173 return;
1174 else {
1175 /* Crazy xdl interfaces.. */
1176 xpparam_t xpp;
1177 xdemitconf_t xecfg;
1178 xdemitcb_t ecb;
1179
1180 xpp.flags = XDF_NEED_MINIMAL;
1181 xecfg.ctxlen = 0;
1182 xecfg.flags = 0;
1183 ecb.outf = xdiff_outf;
1184 ecb.priv = &data;
1185 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1186 }
1187}
1188
6973dcae
JH
1189struct diff_filespec *alloc_filespec(const char *path)
1190{
1191 int namelen = strlen(path);
1192 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1193
1194 memset(spec, 0, sizeof(*spec));
1195 spec->path = (char *)(spec + 1);
1196 memcpy(spec->path, path, namelen+1);
1197 return spec;
1198}
1199
1200void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1201 unsigned short mode)
1202{
1203 if (mode) {
1204 spec->mode = canon_mode(mode);
e702496e 1205 hashcpy(spec->sha1, sha1);
0bef57ee 1206 spec->sha1_valid = !is_null_sha1(sha1);
6973dcae
JH
1207 }
1208}
1209
1210/*
1211 * Given a name and sha1 pair, if the dircache tells us the file in
1212 * the work tree has that object contents, return true, so that
1213 * prepare_temp_file() does not have to inflate and extract.
1214 */
1510fea7 1215static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
6973dcae
JH
1216{
1217 struct cache_entry *ce;
1218 struct stat st;
1219 int pos, len;
1220
1221 /* We do not read the cache ourselves here, because the
1222 * benchmark with my previous version that always reads cache
1223 * shows that it makes things worse for diff-tree comparing
1224 * two linux-2.6 kernel trees in an already checked out work
1225 * tree. This is because most diff-tree comparisons deal with
1226 * only a small number of files, while reading the cache is
1227 * expensive for a large project, and its cost outweighs the
1228 * savings we get by not inflating the object to a temporary
1229 * file. Practically, this code only helps when we are used
1230 * by diff-cache --cached, which does read the cache before
1231 * calling us.
1232 */
1233 if (!active_cache)
1234 return 0;
1235
1510fea7
SP
1236 /* We want to avoid the working directory if our caller
1237 * doesn't need the data in a normal file, this system
1238 * is rather slow with its stat/open/mmap/close syscalls,
1239 * and the object is contained in a pack file. The pack
1240 * is probably already open and will be faster to obtain
1241 * the data through than the working directory. Loose
1242 * objects however would tend to be slower as they need
1243 * to be individually opened and inflated.
1244 */
5caf9232 1245 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1, NULL))
1510fea7
SP
1246 return 0;
1247
6973dcae
JH
1248 len = strlen(name);
1249 pos = cache_name_pos(name, len);
1250 if (pos < 0)
1251 return 0;
1252 ce = active_cache[pos];
1253 if ((lstat(name, &st) < 0) ||
1254 !S_ISREG(st.st_mode) || /* careful! */
1255 ce_match_stat(ce, &st, 0) ||
a89fccd2 1256 hashcmp(sha1, ce->sha1))
6973dcae
JH
1257 return 0;
1258 /* we return 1 only when we can stat, it is a regular file,
1259 * stat information matches, and sha1 recorded in the cache
1260 * matches. I.e. we know the file in the work tree really is
1261 * the same as the <name, sha1> pair.
1262 */
1263 return 1;
1264}
1265
1266static struct sha1_size_cache {
1267 unsigned char sha1[20];
1268 unsigned long size;
1269} **sha1_size_cache;
1270static int sha1_size_cache_nr, sha1_size_cache_alloc;
1271
1272static struct sha1_size_cache *locate_size_cache(unsigned char *sha1,
1273 int find_only,
1274 unsigned long size)
1275{
1276 int first, last;
1277 struct sha1_size_cache *e;
1278
1279 first = 0;
1280 last = sha1_size_cache_nr;
1281 while (last > first) {
1282 int cmp, next = (last + first) >> 1;
1283 e = sha1_size_cache[next];
a89fccd2 1284 cmp = hashcmp(e->sha1, sha1);
6973dcae
JH
1285 if (!cmp)
1286 return e;
1287 if (cmp < 0) {
1288 last = next;
1289 continue;
1290 }
1291 first = next+1;
1292 }
1293 /* not found */
1294 if (find_only)
1295 return NULL;
1296 /* insert to make it at "first" */
1297 if (sha1_size_cache_alloc <= sha1_size_cache_nr) {
1298 sha1_size_cache_alloc = alloc_nr(sha1_size_cache_alloc);
1299 sha1_size_cache = xrealloc(sha1_size_cache,
1300 sha1_size_cache_alloc *
1301 sizeof(*sha1_size_cache));
1302 }
1303 sha1_size_cache_nr++;
1304 if (first < sha1_size_cache_nr)
1305 memmove(sha1_size_cache + first + 1, sha1_size_cache + first,
1306 (sha1_size_cache_nr - first - 1) *
1307 sizeof(*sha1_size_cache));
1308 e = xmalloc(sizeof(struct sha1_size_cache));
1309 sha1_size_cache[first] = e;
e702496e 1310 hashcpy(e->sha1, sha1);
6973dcae
JH
1311 e->size = size;
1312 return e;
1313}
1314
1315/*
1316 * While doing rename detection and pickaxe operation, we may need to
1317 * grab the data for the blob (or file) for our own in-core comparison.
1318 * diff_filespec has data and size fields for this purpose.
1319 */
1320int diff_populate_filespec(struct diff_filespec *s, int size_only)
1321{
1322 int err = 0;
1323 if (!DIFF_FILE_VALID(s))
1324 die("internal error: asking to populate invalid file.");
1325 if (S_ISDIR(s->mode))
1326 return -1;
1327
1328 if (!use_size_cache)
1329 size_only = 0;
1330
1331 if (s->data)
1332 return err;
1333 if (!s->sha1_valid ||
1510fea7 1334 reuse_worktree_file(s->path, s->sha1, 0)) {
6973dcae
JH
1335 struct stat st;
1336 int fd;
1337 if (lstat(s->path, &st) < 0) {
1338 if (errno == ENOENT) {
1339 err_empty:
1340 err = -1;
1341 empty:
d2543b8e 1342 s->data = (char *)"";
6973dcae
JH
1343 s->size = 0;
1344 return err;
1345 }
1346 }
1347 s->size = st.st_size;
1348 if (!s->size)
1349 goto empty;
1350 if (size_only)
1351 return 0;
1352 if (S_ISLNK(st.st_mode)) {
1353 int ret;
1354 s->data = xmalloc(s->size);
1355 s->should_free = 1;
1356 ret = readlink(s->path, s->data, s->size);
1357 if (ret < 0) {
1358 free(s->data);
1359 goto err_empty;
1360 }
1361 return 0;
1362 }
1363 fd = open(s->path, O_RDONLY);
1364 if (fd < 0)
1365 goto err_empty;
c4712e45 1366 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
6973dcae 1367 close(fd);
6973dcae 1368 s->should_munmap = 1;
bd3a5b5e 1369 /* FIXME! CRLF -> LF conversion goes here, based on "s->path" */
6973dcae
JH
1370 }
1371 else {
1372 char type[20];
1373 struct sha1_size_cache *e;
1374
1375 if (size_only) {
1376 e = locate_size_cache(s->sha1, 1, 0);
1377 if (e) {
1378 s->size = e->size;
1379 return 0;
1380 }
1381 if (!sha1_object_info(s->sha1, type, &s->size))
1382 locate_size_cache(s->sha1, 0, s->size);
1383 }
1384 else {
1385 s->data = read_sha1_file(s->sha1, type, &s->size);
1386 s->should_free = 1;
1387 }
1388 }
1389 return 0;
1390}
1391
1392void diff_free_filespec_data(struct diff_filespec *s)
1393{
1394 if (s->should_free)
1395 free(s->data);
1396 else if (s->should_munmap)
1397 munmap(s->data, s->size);
1398 s->should_free = s->should_munmap = 0;
1399 s->data = NULL;
1400 free(s->cnt_data);
1401 s->cnt_data = NULL;
1402}
1403
1404static void prep_temp_blob(struct diff_tempfile *temp,
1405 void *blob,
1406 unsigned long size,
1407 const unsigned char *sha1,
1408 int mode)
1409{
1410 int fd;
1411
1412 fd = git_mkstemp(temp->tmp_path, TEMPFILE_PATH_LEN, ".diff_XXXXXX");
1413 if (fd < 0)
1414 die("unable to create temp-file");
93822c22 1415 if (write_in_full(fd, blob, size) != size)
6973dcae
JH
1416 die("unable to write temp-file");
1417 close(fd);
1418 temp->name = temp->tmp_path;
1419 strcpy(temp->hex, sha1_to_hex(sha1));
1420 temp->hex[40] = 0;
1421 sprintf(temp->mode, "%06o", mode);
1422}
1423
1424static void prepare_temp_file(const char *name,
1425 struct diff_tempfile *temp,
1426 struct diff_filespec *one)
1427{
1428 if (!DIFF_FILE_VALID(one)) {
1429 not_a_valid_file:
1430 /* A '-' entry produces this for file-2, and
1431 * a '+' entry produces this for file-1.
1432 */
1433 temp->name = "/dev/null";
1434 strcpy(temp->hex, ".");
1435 strcpy(temp->mode, ".");
1436 return;
1437 }
1438
1439 if (!one->sha1_valid ||
1510fea7 1440 reuse_worktree_file(name, one->sha1, 1)) {
6973dcae
JH
1441 struct stat st;
1442 if (lstat(name, &st) < 0) {
1443 if (errno == ENOENT)
1444 goto not_a_valid_file;
1445 die("stat(%s): %s", name, strerror(errno));
1446 }
1447 if (S_ISLNK(st.st_mode)) {
1448 int ret;
1449 char buf[PATH_MAX + 1]; /* ought to be SYMLINK_MAX */
1450 if (sizeof(buf) <= st.st_size)
1451 die("symlink too long: %s", name);
1452 ret = readlink(name, buf, st.st_size);
1453 if (ret < 0)
1454 die("readlink(%s)", name);
1455 prep_temp_blob(temp, buf, st.st_size,
1456 (one->sha1_valid ?
1457 one->sha1 : null_sha1),
1458 (one->sha1_valid ?
1459 one->mode : S_IFLNK));
1460 }
1461 else {
1462 /* we can borrow from the file in the work tree */
1463 temp->name = name;
1464 if (!one->sha1_valid)
1465 strcpy(temp->hex, sha1_to_hex(null_sha1));
1466 else
1467 strcpy(temp->hex, sha1_to_hex(one->sha1));
1468 /* Even though we may sometimes borrow the
1469 * contents from the work tree, we always want
1470 * one->mode. mode is trustworthy even when
1471 * !(one->sha1_valid), as long as
1472 * DIFF_FILE_VALID(one).
1473 */
1474 sprintf(temp->mode, "%06o", one->mode);
1475 }
1476 return;
1477 }
1478 else {
1479 if (diff_populate_filespec(one, 0))
1480 die("cannot read data blob for %s", one->path);
1481 prep_temp_blob(temp, one->data, one->size,
1482 one->sha1, one->mode);
1483 }
1484}
1485
1486static void remove_tempfile(void)
1487{
1488 int i;
1489
1490 for (i = 0; i < 2; i++)
1491 if (diff_temp[i].name == diff_temp[i].tmp_path) {
1492 unlink(diff_temp[i].name);
1493 diff_temp[i].name = NULL;
1494 }
1495}
1496
1497static void remove_tempfile_on_signal(int signo)
1498{
1499 remove_tempfile();
1500 signal(SIGINT, SIG_DFL);
1501 raise(signo);
1502}
1503
1504static int spawn_prog(const char *pgm, const char **arg)
1505{
1506 pid_t pid;
1507 int status;
1508
1509 fflush(NULL);
1510 pid = fork();
1511 if (pid < 0)
1512 die("unable to fork");
1513 if (!pid) {
1514 execvp(pgm, (char *const*) arg);
1515 exit(255);
1516 }
1517
1518 while (waitpid(pid, &status, 0) < 0) {
1519 if (errno == EINTR)
1520 continue;
1521 return -1;
1522 }
1523
1524 /* Earlier we did not check the exit status because
1525 * diff exits non-zero if files are different, and
1526 * we are not interested in knowing that. It was a
1527 * mistake which made it harder to quit a diff-*
1528 * session that uses the git-apply-patch-script as
1529 * the GIT_EXTERNAL_DIFF. A custom GIT_EXTERNAL_DIFF
1530 * should also exit non-zero only when it wants to
1531 * abort the entire diff-* session.
1532 */
1533 if (WIFEXITED(status) && !WEXITSTATUS(status))
1534 return 0;
1535 return -1;
1536}
1537
1538/* An external diff command takes:
1539 *
1540 * diff-cmd name infile1 infile1-sha1 infile1-mode \
1541 * infile2 infile2-sha1 infile2-mode [ rename-to ]
1542 *
1543 */
1544static void run_external_diff(const char *pgm,
1545 const char *name,
1546 const char *other,
1547 struct diff_filespec *one,
1548 struct diff_filespec *two,
1549 const char *xfrm_msg,
1550 int complete_rewrite)
1551{
1552 const char *spawn_arg[10];
1553 struct diff_tempfile *temp = diff_temp;
1554 int retval;
1555 static int atexit_asked = 0;
1556 const char *othername;
1557 const char **arg = &spawn_arg[0];
1558
1559 othername = (other? other : name);
1560 if (one && two) {
1561 prepare_temp_file(name, &temp[0], one);
1562 prepare_temp_file(othername, &temp[1], two);
1563 if (! atexit_asked &&
1564 (temp[0].name == temp[0].tmp_path ||
1565 temp[1].name == temp[1].tmp_path)) {
1566 atexit_asked = 1;
1567 atexit(remove_tempfile);
1568 }
1569 signal(SIGINT, remove_tempfile_on_signal);
1570 }
1571
1572 if (one && two) {
1573 *arg++ = pgm;
1574 *arg++ = name;
1575 *arg++ = temp[0].name;
1576 *arg++ = temp[0].hex;
1577 *arg++ = temp[0].mode;
1578 *arg++ = temp[1].name;
1579 *arg++ = temp[1].hex;
1580 *arg++ = temp[1].mode;
1581 if (other) {
1582 *arg++ = other;
1583 *arg++ = xfrm_msg;
1584 }
1585 } else {
1586 *arg++ = pgm;
1587 *arg++ = name;
1588 }
1589 *arg = NULL;
1590 retval = spawn_prog(pgm, spawn_arg);
1591 remove_tempfile();
1592 if (retval) {
1593 fprintf(stderr, "external diff died, stopping at %s.\n", name);
1594 exit(1);
1595 }
1596}
1597
1598static void run_diff_cmd(const char *pgm,
1599 const char *name,
1600 const char *other,
1601 struct diff_filespec *one,
1602 struct diff_filespec *two,
1603 const char *xfrm_msg,
051308f6 1604 struct diff_options *o,
6973dcae
JH
1605 int complete_rewrite)
1606{
1607 if (pgm) {
1608 run_external_diff(pgm, name, other, one, two, xfrm_msg,
1609 complete_rewrite);
1610 return;
1611 }
1612 if (one && two)
1613 builtin_diff(name, other ? other : name,
051308f6 1614 one, two, xfrm_msg, o, complete_rewrite);
6973dcae
JH
1615 else
1616 printf("* Unmerged path %s\n", name);
1617}
1618
1619static void diff_fill_sha1_info(struct diff_filespec *one)
1620{
1621 if (DIFF_FILE_VALID(one)) {
1622 if (!one->sha1_valid) {
1623 struct stat st;
1624 if (lstat(one->path, &st) < 0)
1625 die("stat %s", one->path);
1626 if (index_path(one->sha1, one->path, &st, 0))
1627 die("cannot hash %s\n", one->path);
1628 }
1629 }
1630 else
e702496e 1631 hashclr(one->sha1);
6973dcae
JH
1632}
1633
1634static void run_diff(struct diff_filepair *p, struct diff_options *o)
1635{
1636 const char *pgm = external_diff();
1637 char msg[PATH_MAX*2+300], *xfrm_msg;
1638 struct diff_filespec *one;
1639 struct diff_filespec *two;
1640 const char *name;
1641 const char *other;
1642 char *name_munged, *other_munged;
1643 int complete_rewrite = 0;
1644 int len;
1645
1646 if (DIFF_PAIR_UNMERGED(p)) {
1647 /* unmerged */
051308f6 1648 run_diff_cmd(pgm, p->one->path, NULL, NULL, NULL, NULL, o, 0);
6973dcae
JH
1649 return;
1650 }
1651
1652 name = p->one->path;
1653 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1654 name_munged = quote_one(name);
1655 other_munged = quote_one(other);
1656 one = p->one; two = p->two;
1657
1658 diff_fill_sha1_info(one);
1659 diff_fill_sha1_info(two);
1660
1661 len = 0;
1662 switch (p->status) {
1663 case DIFF_STATUS_COPIED:
1664 len += snprintf(msg + len, sizeof(msg) - len,
1665 "similarity index %d%%\n"
1666 "copy from %s\n"
1667 "copy to %s\n",
1668 (int)(0.5 + p->score * 100.0/MAX_SCORE),
1669 name_munged, other_munged);
1670 break;
1671 case DIFF_STATUS_RENAMED:
1672 len += snprintf(msg + len, sizeof(msg) - len,
1673 "similarity index %d%%\n"
1674 "rename from %s\n"
1675 "rename to %s\n",
1676 (int)(0.5 + p->score * 100.0/MAX_SCORE),
1677 name_munged, other_munged);
1678 break;
1679 case DIFF_STATUS_MODIFIED:
1680 if (p->score) {
1681 len += snprintf(msg + len, sizeof(msg) - len,
1682 "dissimilarity index %d%%\n",
1683 (int)(0.5 + p->score *
1684 100.0/MAX_SCORE));
1685 complete_rewrite = 1;
1686 break;
1687 }
1688 /* fallthru */
1689 default:
1690 /* nothing */
1691 ;
1692 }
1693
a89fccd2 1694 if (hashcmp(one->sha1, two->sha1)) {
6973dcae 1695 int abbrev = o->full_index ? 40 : DEFAULT_ABBREV;
6973dcae 1696
82793c55
JH
1697 if (o->binary) {
1698 mmfile_t mf;
1699 if ((!fill_mmfile(&mf, one) && mmfile_is_binary(&mf)) ||
1700 (!fill_mmfile(&mf, two) && mmfile_is_binary(&mf)))
1701 abbrev = 40;
1702 }
6973dcae
JH
1703 len += snprintf(msg + len, sizeof(msg) - len,
1704 "index %.*s..%.*s",
dcb3450f
LT
1705 abbrev, sha1_to_hex(one->sha1),
1706 abbrev, sha1_to_hex(two->sha1));
6973dcae
JH
1707 if (one->mode == two->mode)
1708 len += snprintf(msg + len, sizeof(msg) - len,
1709 " %06o", one->mode);
1710 len += snprintf(msg + len, sizeof(msg) - len, "\n");
1711 }
1712
1713 if (len)
1714 msg[--len] = 0;
1715 xfrm_msg = len ? msg : NULL;
1716
1717 if (!pgm &&
1718 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
1719 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
1720 /* a filepair that changes between file and symlink
1721 * needs to be split into deletion and creation.
1722 */
1723 struct diff_filespec *null = alloc_filespec(two->path);
051308f6 1724 run_diff_cmd(NULL, name, other, one, null, xfrm_msg, o, 0);
6973dcae
JH
1725 free(null);
1726 null = alloc_filespec(one->path);
051308f6 1727 run_diff_cmd(NULL, name, other, null, two, xfrm_msg, o, 0);
6973dcae
JH
1728 free(null);
1729 }
1730 else
051308f6 1731 run_diff_cmd(pgm, name, other, one, two, xfrm_msg, o,
6973dcae
JH
1732 complete_rewrite);
1733
1734 free(name_munged);
1735 free(other_munged);
1736}
1737
1738static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
1739 struct diffstat_t *diffstat)
1740{
1741 const char *name;
1742 const char *other;
710158e3 1743 int complete_rewrite = 0;
6973dcae
JH
1744
1745 if (DIFF_PAIR_UNMERGED(p)) {
1746 /* unmerged */
0d21efa5 1747 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
6973dcae
JH
1748 return;
1749 }
1750
1751 name = p->one->path;
1752 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1753
1754 diff_fill_sha1_info(p->one);
1755 diff_fill_sha1_info(p->two);
1756
710158e3
JH
1757 if (p->status == DIFF_STATUS_MODIFIED && p->score)
1758 complete_rewrite = 1;
0d21efa5 1759 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
6973dcae
JH
1760}
1761
88246898
JS
1762static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
1763{
1764 const char *name;
1765 const char *other;
1766
1767 if (DIFF_PAIR_UNMERGED(p)) {
1768 /* unmerged */
1769 return;
1770 }
1771
1772 name = p->one->path;
1773 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1774
1775 diff_fill_sha1_info(p->one);
1776 diff_fill_sha1_info(p->two);
1777
1778 builtin_checkdiff(name, other, p->one, p->two);
1779}
1780
6973dcae
JH
1781void diff_setup(struct diff_options *options)
1782{
1783 memset(options, 0, sizeof(*options));
6973dcae
JH
1784 options->line_termination = '\n';
1785 options->break_opt = -1;
1786 options->rename_limit = -1;
ee1e5412 1787 options->context = 3;
3969cf7d 1788 options->msg_sep = "";
6973dcae
JH
1789
1790 options->change = diff_change;
1791 options->add_remove = diff_addremove;
801235c5 1792 options->color_diff = diff_use_color_default;
b68ea12e 1793 options->detect_rename = diff_detect_rename_default;
6973dcae
JH
1794}
1795
1796int diff_setup_done(struct diff_options *options)
1797{
d7de00f7
TH
1798 int count = 0;
1799
1800 if (options->output_format & DIFF_FORMAT_NAME)
1801 count++;
1802 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
1803 count++;
1804 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
1805 count++;
1806 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
1807 count++;
1808 if (count > 1)
1809 die("--name-only, --name-status, --check and -s are mutually exclusive");
1810
03b9d560
JH
1811 if (options->find_copies_harder)
1812 options->detect_rename = DIFF_DETECT_COPY;
1813
c6744349
TH
1814 if (options->output_format & (DIFF_FORMAT_NAME |
1815 DIFF_FORMAT_NAME_STATUS |
1816 DIFF_FORMAT_CHECKDIFF |
1817 DIFF_FORMAT_NO_OUTPUT))
1818 options->output_format &= ~(DIFF_FORMAT_RAW |
74e2abe5 1819 DIFF_FORMAT_NUMSTAT |
c6744349 1820 DIFF_FORMAT_DIFFSTAT |
ebd124c6 1821 DIFF_FORMAT_SHORTSTAT |
c6744349
TH
1822 DIFF_FORMAT_SUMMARY |
1823 DIFF_FORMAT_PATCH);
1824
6973dcae
JH
1825 /*
1826 * These cases always need recursive; we do not drop caller-supplied
1827 * recursive bits for other formats here.
1828 */
c6744349 1829 if (options->output_format & (DIFF_FORMAT_PATCH |
74e2abe5 1830 DIFF_FORMAT_NUMSTAT |
c6744349 1831 DIFF_FORMAT_DIFFSTAT |
ebd124c6 1832 DIFF_FORMAT_SHORTSTAT |
d7014dc0 1833 DIFF_FORMAT_SUMMARY |
c6744349 1834 DIFF_FORMAT_CHECKDIFF))
6973dcae 1835 options->recursive = 1;
5e363541 1836 /*
3969cf7d 1837 * Also pickaxe would not work very well if you do not say recursive
5e363541 1838 */
3969cf7d
JH
1839 if (options->pickaxe)
1840 options->recursive = 1;
5e363541 1841
6973dcae
JH
1842 if (options->detect_rename && options->rename_limit < 0)
1843 options->rename_limit = diff_rename_limit_default;
1844 if (options->setup & DIFF_SETUP_USE_CACHE) {
1845 if (!active_cache)
1846 /* read-cache does not die even when it fails
1847 * so it is safe for us to do this here. Also
1848 * it does not smudge active_cache or active_nr
1849 * when it fails, so we do not have to worry about
1850 * cleaning it up ourselves either.
1851 */
1852 read_cache();
1853 }
1854 if (options->setup & DIFF_SETUP_USE_SIZE_CACHE)
1855 use_size_cache = 1;
1856 if (options->abbrev <= 0 || 40 < options->abbrev)
1857 options->abbrev = 40; /* full */
1858
1859 return 0;
1860}
1861
d2543b8e 1862static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
ee1e5412
LT
1863{
1864 char c, *eq;
1865 int len;
1866
1867 if (*arg != '-')
1868 return 0;
1869 c = *++arg;
1870 if (!c)
1871 return 0;
1872 if (c == arg_short) {
1873 c = *++arg;
1874 if (!c)
1875 return 1;
1876 if (val && isdigit(c)) {
1877 char *end;
1878 int n = strtoul(arg, &end, 10);
1879 if (*end)
1880 return 0;
1881 *val = n;
1882 return 1;
1883 }
1884 return 0;
1885 }
1886 if (c != '-')
1887 return 0;
1888 arg++;
1889 eq = strchr(arg, '=');
1890 if (eq)
1891 len = eq - arg;
1892 else
1893 len = strlen(arg);
1894 if (!len || strncmp(arg, arg_long, len))
1895 return 0;
1896 if (eq) {
1897 int n;
1898 char *end;
1899 if (!isdigit(*++eq))
1900 return 0;
1901 n = strtoul(eq, &end, 10);
1902 if (*end)
1903 return 0;
1904 *val = n;
1905 }
1906 return 1;
1907}
1908
6973dcae
JH
1909int diff_opt_parse(struct diff_options *options, const char **av, int ac)
1910{
1911 const char *arg = av[0];
1912 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
c6744349 1913 options->output_format |= DIFF_FORMAT_PATCH;
ee1e5412 1914 else if (opt_arg(arg, 'U', "unified", &options->context))
c6744349 1915 options->output_format |= DIFF_FORMAT_PATCH;
a610786f
TH
1916 else if (!strcmp(arg, "--raw"))
1917 options->output_format |= DIFF_FORMAT_RAW;
6973dcae 1918 else if (!strcmp(arg, "--patch-with-raw")) {
c6744349 1919 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
6973dcae 1920 }
74e2abe5
JH
1921 else if (!strcmp(arg, "--numstat")) {
1922 options->output_format |= DIFF_FORMAT_NUMSTAT;
1923 }
ebd124c6
NP
1924 else if (!strcmp(arg, "--shortstat")) {
1925 options->output_format |= DIFF_FORMAT_SHORTSTAT;
1926 }
5c5b2ea9
LT
1927 else if (!strncmp(arg, "--stat", 6)) {
1928 char *end;
1929 int width = options->stat_width;
1930 int name_width = options->stat_name_width;
1931 arg += 6;
1932 end = (char *)arg;
1933
1934 switch (*arg) {
1935 case '-':
1936 if (!strncmp(arg, "-width=", 7))
1937 width = strtoul(arg + 7, &end, 10);
1938 else if (!strncmp(arg, "-name-width=", 12))
1939 name_width = strtoul(arg + 12, &end, 10);
1940 break;
1941 case '=':
1942 width = strtoul(arg+1, &end, 10);
1943 if (*end == ',')
1944 name_width = strtoul(end+1, &end, 10);
1945 }
1946
1947 /* Important! This checks all the error cases! */
1948 if (*end)
1949 return 0;
c6744349 1950 options->output_format |= DIFF_FORMAT_DIFFSTAT;
5c5b2ea9
LT
1951 options->stat_name_width = name_width;
1952 options->stat_width = width;
a2540023 1953 }
88246898 1954 else if (!strcmp(arg, "--check"))
c6744349 1955 options->output_format |= DIFF_FORMAT_CHECKDIFF;
4bbd261b 1956 else if (!strcmp(arg, "--summary"))
c6744349 1957 options->output_format |= DIFF_FORMAT_SUMMARY;
6973dcae 1958 else if (!strcmp(arg, "--patch-with-stat")) {
c6744349 1959 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
6973dcae
JH
1960 }
1961 else if (!strcmp(arg, "-z"))
1962 options->line_termination = 0;
1963 else if (!strncmp(arg, "-l", 2))
1964 options->rename_limit = strtoul(arg+2, NULL, 10);
1965 else if (!strcmp(arg, "--full-index"))
1966 options->full_index = 1;
0660626c 1967 else if (!strcmp(arg, "--binary")) {
c6744349 1968 options->output_format |= DIFF_FORMAT_PATCH;
82793c55 1969 options->binary = 1;
0660626c 1970 }
63ac4501 1971 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text")) {
6d64ea96
SF
1972 options->text = 1;
1973 }
6973dcae 1974 else if (!strcmp(arg, "--name-only"))
c6744349 1975 options->output_format |= DIFF_FORMAT_NAME;
6973dcae 1976 else if (!strcmp(arg, "--name-status"))
c6744349 1977 options->output_format |= DIFF_FORMAT_NAME_STATUS;
6973dcae
JH
1978 else if (!strcmp(arg, "-R"))
1979 options->reverse_diff = 1;
1980 else if (!strncmp(arg, "-S", 2))
1981 options->pickaxe = arg + 2;
c6744349
TH
1982 else if (!strcmp(arg, "-s")) {
1983 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
1984 }
6973dcae
JH
1985 else if (!strncmp(arg, "-O", 2))
1986 options->orderfile = arg + 2;
1987 else if (!strncmp(arg, "--diff-filter=", 14))
1988 options->filter = arg + 14;
1989 else if (!strcmp(arg, "--pickaxe-all"))
1990 options->pickaxe_opts = DIFF_PICKAXE_ALL;
1991 else if (!strcmp(arg, "--pickaxe-regex"))
1992 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
1993 else if (!strncmp(arg, "-B", 2)) {
1994 if ((options->break_opt =
1995 diff_scoreopt_parse(arg)) == -1)
1996 return -1;
1997 }
1998 else if (!strncmp(arg, "-M", 2)) {
1999 if ((options->rename_score =
2000 diff_scoreopt_parse(arg)) == -1)
2001 return -1;
2002 options->detect_rename = DIFF_DETECT_RENAME;
2003 }
2004 else if (!strncmp(arg, "-C", 2)) {
2005 if ((options->rename_score =
2006 diff_scoreopt_parse(arg)) == -1)
2007 return -1;
2008 options->detect_rename = DIFF_DETECT_COPY;
2009 }
2010 else if (!strcmp(arg, "--find-copies-harder"))
2011 options->find_copies_harder = 1;
2012 else if (!strcmp(arg, "--abbrev"))
2013 options->abbrev = DEFAULT_ABBREV;
2014 else if (!strncmp(arg, "--abbrev=", 9)) {
2015 options->abbrev = strtoul(arg + 9, NULL, 10);
2016 if (options->abbrev < MINIMUM_ABBREV)
2017 options->abbrev = MINIMUM_ABBREV;
2018 else if (40 < options->abbrev)
2019 options->abbrev = 40;
2020 }
cd112cef
JS
2021 else if (!strcmp(arg, "--color"))
2022 options->color_diff = 1;
fef88bb0
JH
2023 else if (!strcmp(arg, "--no-color"))
2024 options->color_diff = 0;
0d21efa5
JS
2025 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2026 options->xdl_opts |= XDF_IGNORE_WHITESPACE;
2027 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2028 options->xdl_opts |= XDF_IGNORE_WHITESPACE_CHANGE;
f59a59e2
JS
2029 else if (!strcmp(arg, "--color-words"))
2030 options->color_diff = options->color_diff_words = 1;
b68ea12e
EW
2031 else if (!strcmp(arg, "--no-renames"))
2032 options->detect_rename = 0;
6973dcae
JH
2033 else
2034 return 0;
2035 return 1;
2036}
2037
2038static int parse_num(const char **cp_p)
2039{
2040 unsigned long num, scale;
2041 int ch, dot;
2042 const char *cp = *cp_p;
2043
2044 num = 0;
2045 scale = 1;
2046 dot = 0;
2047 for(;;) {
2048 ch = *cp;
2049 if ( !dot && ch == '.' ) {
2050 scale = 1;
2051 dot = 1;
2052 } else if ( ch == '%' ) {
2053 scale = dot ? scale*100 : 100;
2054 cp++; /* % is always at the end */
2055 break;
2056 } else if ( ch >= '0' && ch <= '9' ) {
2057 if ( scale < 100000 ) {
2058 scale *= 10;
2059 num = (num*10) + (ch-'0');
2060 }
2061 } else {
2062 break;
2063 }
2064 cp++;
2065 }
2066 *cp_p = cp;
2067
2068 /* user says num divided by scale and we say internally that
2069 * is MAX_SCORE * num / scale.
2070 */
2071 return (num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale);
2072}
2073
2074int diff_scoreopt_parse(const char *opt)
2075{
2076 int opt1, opt2, cmd;
2077
2078 if (*opt++ != '-')
2079 return -1;
2080 cmd = *opt++;
2081 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2082 return -1; /* that is not a -M, -C nor -B option */
2083
2084 opt1 = parse_num(&opt);
2085 if (cmd != 'B')
2086 opt2 = 0;
2087 else {
2088 if (*opt == 0)
2089 opt2 = 0;
2090 else if (*opt != '/')
2091 return -1; /* we expect -B80/99 or -B80 */
2092 else {
2093 opt++;
2094 opt2 = parse_num(&opt);
2095 }
2096 }
2097 if (*opt != 0)
2098 return -1;
2099 return opt1 | (opt2 << 16);
2100}
2101
2102struct diff_queue_struct diff_queued_diff;
2103
2104void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2105{
2106 if (queue->alloc <= queue->nr) {
2107 queue->alloc = alloc_nr(queue->alloc);
2108 queue->queue = xrealloc(queue->queue,
2109 sizeof(dp) * queue->alloc);
2110 }
2111 queue->queue[queue->nr++] = dp;
2112}
2113
2114struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2115 struct diff_filespec *one,
2116 struct diff_filespec *two)
2117{
ef677686 2118 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
6973dcae
JH
2119 dp->one = one;
2120 dp->two = two;
6973dcae
JH
2121 if (queue)
2122 diff_q(queue, dp);
2123 return dp;
2124}
2125
2126void diff_free_filepair(struct diff_filepair *p)
2127{
2128 diff_free_filespec_data(p->one);
2129 diff_free_filespec_data(p->two);
2130 free(p->one);
2131 free(p->two);
2132 free(p);
2133}
2134
2135/* This is different from find_unique_abbrev() in that
2136 * it stuffs the result with dots for alignment.
2137 */
2138const char *diff_unique_abbrev(const unsigned char *sha1, int len)
2139{
2140 int abblen;
2141 const char *abbrev;
2142 if (len == 40)
2143 return sha1_to_hex(sha1);
2144
2145 abbrev = find_unique_abbrev(sha1, len);
2146 if (!abbrev)
2147 return sha1_to_hex(sha1);
2148 abblen = strlen(abbrev);
2149 if (abblen < 37) {
2150 static char hex[41];
2151 if (len < abblen && abblen <= len + 2)
2152 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
2153 else
2154 sprintf(hex, "%s...", abbrev);
2155 return hex;
2156 }
2157 return sha1_to_hex(sha1);
2158}
2159
2160static void diff_flush_raw(struct diff_filepair *p,
c6744349 2161 struct diff_options *options)
6973dcae
JH
2162{
2163 int two_paths;
2164 char status[10];
2165 int abbrev = options->abbrev;
2166 const char *path_one, *path_two;
c6744349
TH
2167 int inter_name_termination = '\t';
2168 int line_termination = options->line_termination;
2169
2170 if (!line_termination)
2171 inter_name_termination = 0;
6973dcae
JH
2172
2173 path_one = p->one->path;
2174 path_two = p->two->path;
2175 if (line_termination) {
2176 path_one = quote_one(path_one);
2177 path_two = quote_one(path_two);
2178 }
2179
2180 if (p->score)
2181 sprintf(status, "%c%03d", p->status,
2182 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2183 else {
2184 status[0] = p->status;
2185 status[1] = 0;
2186 }
2187 switch (p->status) {
2188 case DIFF_STATUS_COPIED:
2189 case DIFF_STATUS_RENAMED:
2190 two_paths = 1;
2191 break;
2192 case DIFF_STATUS_ADDED:
2193 case DIFF_STATUS_DELETED:
2194 two_paths = 0;
2195 break;
2196 default:
2197 two_paths = 0;
2198 break;
2199 }
c6744349 2200 if (!(options->output_format & DIFF_FORMAT_NAME_STATUS)) {
6973dcae
JH
2201 printf(":%06o %06o %s ",
2202 p->one->mode, p->two->mode,
2203 diff_unique_abbrev(p->one->sha1, abbrev));
2204 printf("%s ",
2205 diff_unique_abbrev(p->two->sha1, abbrev));
2206 }
2207 printf("%s%c%s", status, inter_name_termination, path_one);
2208 if (two_paths)
2209 printf("%c%s", inter_name_termination, path_two);
2210 putchar(line_termination);
2211 if (path_one != p->one->path)
2212 free((void*)path_one);
2213 if (path_two != p->two->path)
2214 free((void*)path_two);
2215}
2216
471efb09 2217static void diff_flush_name(struct diff_filepair *p, struct diff_options *opt)
6973dcae
JH
2218{
2219 char *path = p->two->path;
2220
471efb09 2221 if (opt->line_termination)
6973dcae 2222 path = quote_one(p->two->path);
471efb09 2223 printf("%s%c", path, opt->line_termination);
6973dcae
JH
2224 if (p->two->path != path)
2225 free(path);
2226}
2227
2228int diff_unmodified_pair(struct diff_filepair *p)
2229{
2230 /* This function is written stricter than necessary to support
2231 * the currently implemented transformers, but the idea is to
2232 * let transformers to produce diff_filepairs any way they want,
2233 * and filter and clean them up here before producing the output.
2234 */
2235 struct diff_filespec *one, *two;
2236
2237 if (DIFF_PAIR_UNMERGED(p))
2238 return 0; /* unmerged is interesting */
2239
2240 one = p->one;
2241 two = p->two;
2242
2243 /* deletion, addition, mode or type change
2244 * and rename are all interesting.
2245 */
2246 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
2247 DIFF_PAIR_MODE_CHANGED(p) ||
2248 strcmp(one->path, two->path))
2249 return 0;
2250
2251 /* both are valid and point at the same path. that is, we are
2252 * dealing with a change.
2253 */
2254 if (one->sha1_valid && two->sha1_valid &&
a89fccd2 2255 !hashcmp(one->sha1, two->sha1))
6973dcae
JH
2256 return 1; /* no change */
2257 if (!one->sha1_valid && !two->sha1_valid)
2258 return 1; /* both look at the same file on the filesystem. */
2259 return 0;
2260}
2261
2262static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
2263{
2264 if (diff_unmodified_pair(p))
2265 return;
2266
2267 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2268 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2269 return; /* no tree diffs in patch format */
2270
2271 run_diff(p, o);
2272}
2273
2274static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
2275 struct diffstat_t *diffstat)
2276{
2277 if (diff_unmodified_pair(p))
2278 return;
2279
2280 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2281 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2282 return; /* no tree diffs in patch format */
2283
2284 run_diffstat(p, o, diffstat);
2285}
2286
88246898
JS
2287static void diff_flush_checkdiff(struct diff_filepair *p,
2288 struct diff_options *o)
2289{
2290 if (diff_unmodified_pair(p))
2291 return;
2292
2293 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2294 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2295 return; /* no tree diffs in patch format */
2296
2297 run_checkdiff(p, o);
2298}
2299
6973dcae
JH
2300int diff_queue_is_empty(void)
2301{
2302 struct diff_queue_struct *q = &diff_queued_diff;
2303 int i;
2304 for (i = 0; i < q->nr; i++)
2305 if (!diff_unmodified_pair(q->queue[i]))
2306 return 0;
2307 return 1;
2308}
2309
2310#if DIFF_DEBUG
2311void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
2312{
2313 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
2314 x, one ? one : "",
2315 s->path,
2316 DIFF_FILE_VALID(s) ? "valid" : "invalid",
2317 s->mode,
2318 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
2319 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
2320 x, one ? one : "",
2321 s->size, s->xfrm_flags);
2322}
2323
2324void diff_debug_filepair(const struct diff_filepair *p, int i)
2325{
2326 diff_debug_filespec(p->one, i, "one");
2327 diff_debug_filespec(p->two, i, "two");
2328 fprintf(stderr, "score %d, status %c stays %d broken %d\n",
2329 p->score, p->status ? p->status : '?',
2330 p->source_stays, p->broken_pair);
2331}
2332
2333void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
2334{
2335 int i;
2336 if (msg)
2337 fprintf(stderr, "%s\n", msg);
2338 fprintf(stderr, "q->nr = %d\n", q->nr);
2339 for (i = 0; i < q->nr; i++) {
2340 struct diff_filepair *p = q->queue[i];
2341 diff_debug_filepair(p, i);
2342 }
2343}
2344#endif
2345
2346static void diff_resolve_rename_copy(void)
2347{
2348 int i, j;
2349 struct diff_filepair *p, *pp;
2350 struct diff_queue_struct *q = &diff_queued_diff;
2351
2352 diff_debug_queue("resolve-rename-copy", q);
2353
2354 for (i = 0; i < q->nr; i++) {
2355 p = q->queue[i];
2356 p->status = 0; /* undecided */
2357 if (DIFF_PAIR_UNMERGED(p))
2358 p->status = DIFF_STATUS_UNMERGED;
2359 else if (!DIFF_FILE_VALID(p->one))
2360 p->status = DIFF_STATUS_ADDED;
2361 else if (!DIFF_FILE_VALID(p->two))
2362 p->status = DIFF_STATUS_DELETED;
2363 else if (DIFF_PAIR_TYPE_CHANGED(p))
2364 p->status = DIFF_STATUS_TYPE_CHANGED;
2365
2366 /* from this point on, we are dealing with a pair
2367 * whose both sides are valid and of the same type, i.e.
2368 * either in-place edit or rename/copy edit.
2369 */
2370 else if (DIFF_PAIR_RENAME(p)) {
2371 if (p->source_stays) {
2372 p->status = DIFF_STATUS_COPIED;
2373 continue;
2374 }
2375 /* See if there is some other filepair that
2376 * copies from the same source as us. If so
2377 * we are a copy. Otherwise we are either a
2378 * copy if the path stays, or a rename if it
2379 * does not, but we already handled "stays" case.
2380 */
2381 for (j = i + 1; j < q->nr; j++) {
2382 pp = q->queue[j];
2383 if (strcmp(pp->one->path, p->one->path))
2384 continue; /* not us */
2385 if (!DIFF_PAIR_RENAME(pp))
2386 continue; /* not a rename/copy */
2387 /* pp is a rename/copy from the same source */
2388 p->status = DIFF_STATUS_COPIED;
2389 break;
2390 }
2391 if (!p->status)
2392 p->status = DIFF_STATUS_RENAMED;
2393 }
a89fccd2 2394 else if (hashcmp(p->one->sha1, p->two->sha1) ||
6973dcae
JH
2395 p->one->mode != p->two->mode)
2396 p->status = DIFF_STATUS_MODIFIED;
2397 else {
2398 /* This is a "no-change" entry and should not
2399 * happen anymore, but prepare for broken callers.
2400 */
2401 error("feeding unmodified %s to diffcore",
2402 p->one->path);
2403 p->status = DIFF_STATUS_UNKNOWN;
2404 }
2405 }
2406 diff_debug_queue("resolve-rename-copy done", q);
2407}
2408
c6744349 2409static int check_pair_status(struct diff_filepair *p)
6973dcae 2410{
6973dcae
JH
2411 switch (p->status) {
2412 case DIFF_STATUS_UNKNOWN:
c6744349 2413 return 0;
6973dcae
JH
2414 case 0:
2415 die("internal error in diff-resolve-rename-copy");
6973dcae 2416 default:
c6744349 2417 return 1;
6973dcae
JH
2418 }
2419}
2420
c6744349
TH
2421static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
2422{
2423 int fmt = opt->output_format;
2424
2425 if (fmt & DIFF_FORMAT_CHECKDIFF)
2426 diff_flush_checkdiff(p, opt);
2427 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
2428 diff_flush_raw(p, opt);
2429 else if (fmt & DIFF_FORMAT_NAME)
471efb09 2430 diff_flush_name(p, opt);
c6744349
TH
2431}
2432
4bbd261b
SE
2433static void show_file_mode_name(const char *newdelete, struct diff_filespec *fs)
2434{
0d26a64e 2435 char *name = quote_one(fs->path);
4bbd261b 2436 if (fs->mode)
0d26a64e 2437 printf(" %s mode %06o %s\n", newdelete, fs->mode, name);
4bbd261b 2438 else
0d26a64e
AJ
2439 printf(" %s %s\n", newdelete, name);
2440 free(name);
4bbd261b
SE
2441}
2442
2443
2444static void show_mode_change(struct diff_filepair *p, int show_name)
2445{
2446 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
0d26a64e
AJ
2447 if (show_name) {
2448 char *name = quote_one(p->two->path);
4bbd261b 2449 printf(" mode change %06o => %06o %s\n",
0d26a64e
AJ
2450 p->one->mode, p->two->mode, name);
2451 free(name);
2452 }
4bbd261b
SE
2453 else
2454 printf(" mode change %06o => %06o\n",
2455 p->one->mode, p->two->mode);
2456 }
2457}
2458
2459static void show_rename_copy(const char *renamecopy, struct diff_filepair *p)
2460{
b9f44164 2461 char *names = pprint_rename(p->one->path, p->two->path);
4bbd261b 2462
b9f44164
AJ
2463 printf(" %s %s (%d%%)\n", renamecopy, names,
2464 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2465 free(names);
4bbd261b
SE
2466 show_mode_change(p, 0);
2467}
2468
2469static void diff_summary(struct diff_filepair *p)
2470{
2471 switch(p->status) {
2472 case DIFF_STATUS_DELETED:
2473 show_file_mode_name("delete", p->one);
2474 break;
2475 case DIFF_STATUS_ADDED:
2476 show_file_mode_name("create", p->two);
2477 break;
2478 case DIFF_STATUS_COPIED:
2479 show_rename_copy("copy", p);
2480 break;
2481 case DIFF_STATUS_RENAMED:
2482 show_rename_copy("rename", p);
2483 break;
2484 default:
2485 if (p->score) {
0d26a64e
AJ
2486 char *name = quote_one(p->two->path);
2487 printf(" rewrite %s (%d%%)\n", name,
4bbd261b 2488 (int)(0.5 + p->score * 100.0/MAX_SCORE));
0d26a64e 2489 free(name);
4bbd261b
SE
2490 show_mode_change(p, 0);
2491 } else show_mode_change(p, 1);
2492 break;
2493 }
2494}
2495
fcb3d0ad
JS
2496struct patch_id_t {
2497 struct xdiff_emit_state xm;
2498 SHA_CTX *ctx;
2499 int patchlen;
2500};
2501
2502static int remove_space(char *line, int len)
2503{
2504 int i;
2505 char *dst = line;
2506 unsigned char c;
2507
2508 for (i = 0; i < len; i++)
2509 if (!isspace((c = line[i])))
2510 *dst++ = c;
2511
2512 return dst - line;
2513}
2514
2515static void patch_id_consume(void *priv, char *line, unsigned long len)
2516{
2517 struct patch_id_t *data = priv;
2518 int new_len;
2519
2520 /* Ignore line numbers when computing the SHA1 of the patch */
2521 if (!strncmp(line, "@@ -", 4))
2522 return;
2523
2524 new_len = remove_space(line, len);
2525
2526 SHA1_Update(data->ctx, line, new_len);
2527 data->patchlen += new_len;
2528}
2529
2530/* returns 0 upon success, and writes result into sha1 */
2531static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
2532{
2533 struct diff_queue_struct *q = &diff_queued_diff;
2534 int i;
2535 SHA_CTX ctx;
2536 struct patch_id_t data;
2537 char buffer[PATH_MAX * 4 + 20];
2538
2539 SHA1_Init(&ctx);
2540 memset(&data, 0, sizeof(struct patch_id_t));
2541 data.ctx = &ctx;
2542 data.xm.consume = patch_id_consume;
2543
2544 for (i = 0; i < q->nr; i++) {
2545 xpparam_t xpp;
2546 xdemitconf_t xecfg;
2547 xdemitcb_t ecb;
2548 mmfile_t mf1, mf2;
2549 struct diff_filepair *p = q->queue[i];
2550 int len1, len2;
2551
2552 if (p->status == 0)
2553 return error("internal diff status error");
2554 if (p->status == DIFF_STATUS_UNKNOWN)
2555 continue;
2556 if (diff_unmodified_pair(p))
2557 continue;
2558 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2559 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2560 continue;
2561 if (DIFF_PAIR_UNMERGED(p))
2562 continue;
2563
2564 diff_fill_sha1_info(p->one);
2565 diff_fill_sha1_info(p->two);
2566 if (fill_mmfile(&mf1, p->one) < 0 ||
2567 fill_mmfile(&mf2, p->two) < 0)
2568 return error("unable to read files to diff");
2569
2570 /* Maybe hash p->two? into the patch id? */
2571 if (mmfile_is_binary(&mf2))
2572 continue;
2573
2574 len1 = remove_space(p->one->path, strlen(p->one->path));
2575 len2 = remove_space(p->two->path, strlen(p->two->path));
2576 if (p->one->mode == 0)
2577 len1 = snprintf(buffer, sizeof(buffer),
2578 "diff--gita/%.*sb/%.*s"
2579 "newfilemode%06o"
2580 "---/dev/null"
2581 "+++b/%.*s",
2582 len1, p->one->path,
2583 len2, p->two->path,
2584 p->two->mode,
2585 len2, p->two->path);
2586 else if (p->two->mode == 0)
2587 len1 = snprintf(buffer, sizeof(buffer),
2588 "diff--gita/%.*sb/%.*s"
2589 "deletedfilemode%06o"
2590 "---a/%.*s"
2591 "+++/dev/null",
2592 len1, p->one->path,
2593 len2, p->two->path,
2594 p->one->mode,
2595 len1, p->one->path);
2596 else
2597 len1 = snprintf(buffer, sizeof(buffer),
2598 "diff--gita/%.*sb/%.*s"
2599 "---a/%.*s"
2600 "+++b/%.*s",
2601 len1, p->one->path,
2602 len2, p->two->path,
2603 len1, p->one->path,
2604 len2, p->two->path);
2605 SHA1_Update(&ctx, buffer, len1);
2606
2607 xpp.flags = XDF_NEED_MINIMAL;
2608 xecfg.ctxlen = 3;
9fdc3bb5 2609 xecfg.flags = XDL_EMIT_FUNCNAMES;
fcb3d0ad
JS
2610 ecb.outf = xdiff_outf;
2611 ecb.priv = &data;
2612 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
2613 }
2614
2615 SHA1_Final(sha1, &ctx);
2616 return 0;
2617}
2618
2619int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
2620{
2621 struct diff_queue_struct *q = &diff_queued_diff;
2622 int i;
2623 int result = diff_get_patch_id(options, sha1);
2624
2625 for (i = 0; i < q->nr; i++)
2626 diff_free_filepair(q->queue[i]);
2627
2628 free(q->queue);
2629 q->queue = NULL;
2630 q->nr = q->alloc = 0;
2631
2632 return result;
2633}
2634
946c3784 2635static int is_summary_empty(const struct diff_queue_struct *q)
6973dcae 2636{
6973dcae 2637 int i;
6973dcae 2638
946c3784
TH
2639 for (i = 0; i < q->nr; i++) {
2640 const struct diff_filepair *p = q->queue[i];
2641
2642 switch (p->status) {
2643 case DIFF_STATUS_DELETED:
2644 case DIFF_STATUS_ADDED:
2645 case DIFF_STATUS_COPIED:
2646 case DIFF_STATUS_RENAMED:
2647 return 0;
2648 default:
2649 if (p->score)
2650 return 0;
2651 if (p->one->mode && p->two->mode &&
2652 p->one->mode != p->two->mode)
2653 return 0;
2654 break;
2655 }
6973dcae 2656 }
946c3784
TH
2657 return 1;
2658}
2659
6973dcae
JH
2660void diff_flush(struct diff_options *options)
2661{
2662 struct diff_queue_struct *q = &diff_queued_diff;
c6744349 2663 int i, output_format = options->output_format;
946c3784 2664 int separator = 0;
6973dcae 2665
c6744349
TH
2666 /*
2667 * Order: raw, stat, summary, patch
2668 * or: name/name-status/checkdiff (other bits clear)
2669 */
946c3784
TH
2670 if (!q->nr)
2671 goto free_queue;
6973dcae 2672
c6744349
TH
2673 if (output_format & (DIFF_FORMAT_RAW |
2674 DIFF_FORMAT_NAME |
2675 DIFF_FORMAT_NAME_STATUS |
2676 DIFF_FORMAT_CHECKDIFF)) {
6973dcae
JH
2677 for (i = 0; i < q->nr; i++) {
2678 struct diff_filepair *p = q->queue[i];
c6744349
TH
2679 if (check_pair_status(p))
2680 flush_one_pair(p, options);
6973dcae 2681 }
946c3784 2682 separator++;
6973dcae 2683 }
c6744349 2684
ebd124c6 2685 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
5e2b0636 2686 struct diffstat_t diffstat;
c6744349 2687
5e2b0636
TH
2688 memset(&diffstat, 0, sizeof(struct diffstat_t));
2689 diffstat.xm.consume = diffstat_consume;
6973dcae
JH
2690 for (i = 0; i < q->nr; i++) {
2691 struct diff_filepair *p = q->queue[i];
c6744349 2692 if (check_pair_status(p))
5e2b0636 2693 diff_flush_stat(p, options, &diffstat);
6973dcae 2694 }
74e2abe5
JH
2695 if (output_format & DIFF_FORMAT_NUMSTAT)
2696 show_numstat(&diffstat, options);
2697 if (output_format & DIFF_FORMAT_DIFFSTAT)
2698 show_stats(&diffstat, options);
ebd124c6
NP
2699 else if (output_format & DIFF_FORMAT_SHORTSTAT)
2700 show_shortstats(&diffstat);
3969cf7d 2701 separator++;
6973dcae
JH
2702 }
2703
946c3784 2704 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
c6744349
TH
2705 for (i = 0; i < q->nr; i++)
2706 diff_summary(q->queue[i]);
3969cf7d 2707 separator++;
6973dcae
JH
2708 }
2709
c6744349 2710 if (output_format & DIFF_FORMAT_PATCH) {
946c3784
TH
2711 if (separator) {
2712 if (options->stat_sep) {
2713 /* attach patch instead of inline */
c6744349 2714 fputs(options->stat_sep, stdout);
946c3784 2715 } else {
c6744349 2716 putchar(options->line_termination);
946c3784 2717 }
c6744349
TH
2718 }
2719
2720 for (i = 0; i < q->nr; i++) {
2721 struct diff_filepair *p = q->queue[i];
2722 if (check_pair_status(p))
2723 diff_flush_patch(p, options);
2724 }
4bbd261b
SE
2725 }
2726
04245581
JK
2727 if (output_format & DIFF_FORMAT_CALLBACK)
2728 options->format_callback(q, options, options->format_callback_data);
2729
c6744349
TH
2730 for (i = 0; i < q->nr; i++)
2731 diff_free_filepair(q->queue[i]);
946c3784 2732free_queue:
6973dcae
JH
2733 free(q->queue);
2734 q->queue = NULL;
2735 q->nr = q->alloc = 0;
2736}
2737
2738static void diffcore_apply_filter(const char *filter)
2739{
2740 int i;
2741 struct diff_queue_struct *q = &diff_queued_diff;
2742 struct diff_queue_struct outq;
2743 outq.queue = NULL;
2744 outq.nr = outq.alloc = 0;
2745
2746 if (!filter)
2747 return;
2748
2749 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
2750 int found;
2751 for (i = found = 0; !found && i < q->nr; i++) {
2752 struct diff_filepair *p = q->queue[i];
2753 if (((p->status == DIFF_STATUS_MODIFIED) &&
2754 ((p->score &&
2755 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
2756 (!p->score &&
2757 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
2758 ((p->status != DIFF_STATUS_MODIFIED) &&
2759 strchr(filter, p->status)))
2760 found++;
2761 }
2762 if (found)
2763 return;
2764
2765 /* otherwise we will clear the whole queue
2766 * by copying the empty outq at the end of this
2767 * function, but first clear the current entries
2768 * in the queue.
2769 */
2770 for (i = 0; i < q->nr; i++)
2771 diff_free_filepair(q->queue[i]);
2772 }
2773 else {
2774 /* Only the matching ones */
2775 for (i = 0; i < q->nr; i++) {
2776 struct diff_filepair *p = q->queue[i];
2777
2778 if (((p->status == DIFF_STATUS_MODIFIED) &&
2779 ((p->score &&
2780 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
2781 (!p->score &&
2782 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
2783 ((p->status != DIFF_STATUS_MODIFIED) &&
2784 strchr(filter, p->status)))
2785 diff_q(&outq, p);
2786 else
2787 diff_free_filepair(p);
2788 }
2789 }
2790 free(q->queue);
2791 *q = outq;
2792}
2793
2794void diffcore_std(struct diff_options *options)
2795{
2796 if (options->break_opt != -1)
2797 diffcore_break(options->break_opt);
2798 if (options->detect_rename)
2799 diffcore_rename(options);
2800 if (options->break_opt != -1)
2801 diffcore_merge_broken();
2802 if (options->pickaxe)
2803 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
2804 if (options->orderfile)
2805 diffcore_order(options->orderfile);
2806 diff_resolve_rename_copy();
2807 diffcore_apply_filter(options->filter);
2808}
2809
2810
2811void diffcore_std_no_resolve(struct diff_options *options)
2812{
2813 if (options->pickaxe)
2814 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
2815 if (options->orderfile)
2816 diffcore_order(options->orderfile);
2817 diffcore_apply_filter(options->filter);
2818}
2819
2820void diff_addremove(struct diff_options *options,
2821 int addremove, unsigned mode,
2822 const unsigned char *sha1,
2823 const char *base, const char *path)
2824{
2825 char concatpath[PATH_MAX];
2826 struct diff_filespec *one, *two;
2827
2828 /* This may look odd, but it is a preparation for
2829 * feeding "there are unchanged files which should
2830 * not produce diffs, but when you are doing copy
2831 * detection you would need them, so here they are"
2832 * entries to the diff-core. They will be prefixed
2833 * with something like '=' or '*' (I haven't decided
2834 * which but should not make any difference).
2835 * Feeding the same new and old to diff_change()
2836 * also has the same effect.
2837 * Before the final output happens, they are pruned after
2838 * merged into rename/copy pairs as appropriate.
2839 */
2840 if (options->reverse_diff)
2841 addremove = (addremove == '+' ? '-' :
2842 addremove == '-' ? '+' : addremove);
2843
2844 if (!path) path = "";
2845 sprintf(concatpath, "%s%s", base, path);
2846 one = alloc_filespec(concatpath);
2847 two = alloc_filespec(concatpath);
2848
2849 if (addremove != '+')
2850 fill_filespec(one, sha1, mode);
2851 if (addremove != '-')
2852 fill_filespec(two, sha1, mode);
2853
2854 diff_queue(&diff_queued_diff, one, two);
2855}
2856
2857void diff_change(struct diff_options *options,
2858 unsigned old_mode, unsigned new_mode,
2859 const unsigned char *old_sha1,
2860 const unsigned char *new_sha1,
2861 const char *base, const char *path)
2862{
2863 char concatpath[PATH_MAX];
2864 struct diff_filespec *one, *two;
2865
2866 if (options->reverse_diff) {
2867 unsigned tmp;
2868 const unsigned char *tmp_c;
2869 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
2870 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
2871 }
2872 if (!path) path = "";
2873 sprintf(concatpath, "%s%s", base, path);
2874 one = alloc_filespec(concatpath);
2875 two = alloc_filespec(concatpath);
2876 fill_filespec(one, old_sha1, old_mode);
2877 fill_filespec(two, new_sha1, new_mode);
2878
2879 diff_queue(&diff_queued_diff, one, two);
2880}
2881
2882void diff_unmerge(struct diff_options *options,
e9c84099
JH
2883 const char *path,
2884 unsigned mode, const unsigned char *sha1)
6973dcae
JH
2885{
2886 struct diff_filespec *one, *two;
2887 one = alloc_filespec(path);
2888 two = alloc_filespec(path);
e9c84099
JH
2889 fill_filespec(one, sha1, mode);
2890 diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;
6973dcae 2891}