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