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