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