Git 1.7.1
[git/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"
8c701249 11#include "attr.h"
d5535ec7 12#include "run-command.h"
23707811 13#include "utf8.h"
be58e70d 14#include "userdiff.h"
4a16d072 15#include "sigchain.h"
752c0c24 16#include "submodule.h"
a757c646 17#include "ll-merge.h"
6973dcae 18
1510fea7
SP
19#ifdef NO_FAST_WORKING_DIRECTORY
20#define FAST_WORKING_DIRECTORY 0
21#else
22#define FAST_WORKING_DIRECTORY 1
23#endif
24
96f1e58f 25static int diff_detect_rename_default;
50705915 26static int diff_rename_limit_default = 200;
a624eaa7 27static int diff_suppress_blank_empty;
6b2f2d98 28int diff_use_color_default = -1;
98a4d87b 29static const char *diff_word_regex_cfg;
cbe02100 30static const char *external_diff_cmd_cfg;
aecbf914 31int diff_auto_refresh_index = 1;
a5a818ee 32static int diff_mnemonic_prefix;
6973dcae 33
7c92fe0e 34static char diff_colors[][COLOR_MAXLEN] = {
dc6ebd4c
AL
35 GIT_COLOR_RESET,
36 GIT_COLOR_NORMAL, /* PLAIN */
37 GIT_COLOR_BOLD, /* METAINFO */
38 GIT_COLOR_CYAN, /* FRAGINFO */
39 GIT_COLOR_RED, /* OLD */
40 GIT_COLOR_GREEN, /* NEW */
41 GIT_COLOR_YELLOW, /* COMMIT */
42 GIT_COLOR_BG_RED, /* WHITESPACE */
89cb73a1 43 GIT_COLOR_NORMAL, /* FUNCINFO */
cd112cef
JS
44};
45
9cb92c39
JK
46static void diff_filespec_load_driver(struct diff_filespec *one);
47static char *run_textconv(const char *, struct diff_filespec *, size_t *);
48
801235c5
JH
49static int parse_diff_color_slot(const char *var, int ofs)
50{
51 if (!strcasecmp(var+ofs, "plain"))
52 return DIFF_PLAIN;
53 if (!strcasecmp(var+ofs, "meta"))
54 return DIFF_METAINFO;
55 if (!strcasecmp(var+ofs, "frag"))
56 return DIFF_FRAGINFO;
57 if (!strcasecmp(var+ofs, "old"))
58 return DIFF_FILE_OLD;
59 if (!strcasecmp(var+ofs, "new"))
60 return DIFF_FILE_NEW;
ce436973
JK
61 if (!strcasecmp(var+ofs, "commit"))
62 return DIFF_COMMIT;
448c3ef1
JH
63 if (!strcasecmp(var+ofs, "whitespace"))
64 return DIFF_WHITESPACE;
89cb73a1
BW
65 if (!strcasecmp(var+ofs, "func"))
66 return DIFF_FUNCINFO;
8b8e8624 67 return -1;
801235c5
JH
68}
69
cced5fbc
LT
70static int git_config_rename(const char *var, const char *value)
71{
72 if (!value)
73 return DIFF_DETECT_RENAME;
74 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
75 return DIFF_DETECT_COPY;
76 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
77}
78
83ad63cf
JH
79/*
80 * These are to give UI layer defaults.
81 * The core-level commands such as git-diff-files should
82 * never be affected by the setting of diff.renames
83 * the user happens to have in the configuration file.
84 */
ef90d6d4 85int git_diff_ui_config(const char *var, const char *value, void *cb)
801235c5 86{
a159ca0c 87 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
0f6f5a40 88 diff_use_color_default = git_config_colorbool(var, value, -1);
801235c5
JH
89 return 0;
90 }
b68ea12e 91 if (!strcmp(var, "diff.renames")) {
cced5fbc 92 diff_detect_rename_default = git_config_rename(var, value);
b68ea12e
EW
93 return 0;
94 }
aecbf914
JH
95 if (!strcmp(var, "diff.autorefreshindex")) {
96 diff_auto_refresh_index = git_config_bool(var, value);
97 return 0;
98 }
a5a818ee
JH
99 if (!strcmp(var, "diff.mnemonicprefix")) {
100 diff_mnemonic_prefix = git_config_bool(var, value);
101 return 0;
102 }
daec808c
BH
103 if (!strcmp(var, "diff.external"))
104 return git_config_string(&external_diff_cmd_cfg, var, value);
98a4d87b
BSSJ
105 if (!strcmp(var, "diff.wordregex"))
106 return git_config_string(&diff_word_regex_cfg, var, value);
f1af60bd 107
ef90d6d4 108 return git_diff_basic_config(var, value, cb);
9a1805a8
JK
109}
110
ef90d6d4 111int git_diff_basic_config(const char *var, const char *value, void *cb)
9a1805a8 112{
2b6ca6df
LT
113 if (!strcmp(var, "diff.renamelimit")) {
114 diff_rename_limit_default = git_config_int(var, value);
115 return 0;
116 }
117
c7534ef4
JK
118 switch (userdiff_config(var, value)) {
119 case 0: break;
120 case -1: return -1;
121 default: return 0;
122 }
123
1968d77d 124 if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
801235c5 125 int slot = parse_diff_color_slot(var, 11);
8b8e8624
JK
126 if (slot < 0)
127 return 0;
64f30e94
JH
128 if (!value)
129 return config_error_nonbool(var);
7c92fe0e 130 color_parse(value, var, diff_colors[slot]);
801235c5
JH
131 return 0;
132 }
f1af60bd 133
a624eaa7 134 /* like GNU diff's --suppress-blank-empty option */
950db879
JS
135 if (!strcmp(var, "diff.suppressblankempty") ||
136 /* for backwards compatibility */
137 !strcmp(var, "diff.suppress-blank-empty")) {
a624eaa7
JM
138 diff_suppress_blank_empty = git_config_bool(var, value);
139 return 0;
140 }
141
ef90d6d4 142 return git_color_default_config(var, value, cb);
801235c5
JH
143}
144
6973dcae
JH
145static char *quote_two(const char *one, const char *two)
146{
147 int need_one = quote_c_style(one, NULL, NULL, 1);
148 int need_two = quote_c_style(two, NULL, NULL, 1);
f285a2d7 149 struct strbuf res = STRBUF_INIT;
6973dcae
JH
150
151 if (need_one + need_two) {
663af342
PH
152 strbuf_addch(&res, '"');
153 quote_c_style(one, &res, NULL, 1);
154 quote_c_style(two, &res, NULL, 1);
155 strbuf_addch(&res, '"');
156 } else {
157 strbuf_addstr(&res, one);
158 strbuf_addstr(&res, two);
6973dcae 159 }
b315c5c0 160 return strbuf_detach(&res, NULL);
6973dcae
JH
161}
162
163static const char *external_diff(void)
164{
165 static const char *external_diff_cmd = NULL;
166 static int done_preparing = 0;
167
168 if (done_preparing)
169 return external_diff_cmd;
170 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
cbe02100
JS
171 if (!external_diff_cmd)
172 external_diff_cmd = external_diff_cmd_cfg;
6973dcae
JH
173 done_preparing = 1;
174 return external_diff_cmd;
175}
176
6973dcae
JH
177static struct diff_tempfile {
178 const char *name; /* filename external diff should read from */
179 char hex[41];
180 char mode[10];
1472966c 181 char tmp_path[PATH_MAX];
6973dcae
JH
182} diff_temp[2];
183
6957eb9a
JH
184typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
185
186struct emit_callback {
6957eb9a
JH
187 int color_diff;
188 unsigned ws_rule;
189 int blank_at_eof_in_preimage;
190 int blank_at_eof_in_postimage;
191 int lno_in_preimage;
192 int lno_in_postimage;
193 sane_truncate_fn truncate;
194 const char **label_path;
195 struct diff_words_data *diff_words;
196 int *found_changesp;
197 FILE *file;
3e97c7c6 198 struct strbuf *header;
6957eb9a
JH
199};
200
6973dcae
JH
201static int count_lines(const char *data, int size)
202{
203 int count, ch, completely_empty = 1, nl_just_seen = 0;
204 count = 0;
205 while (0 < size--) {
206 ch = *data++;
207 if (ch == '\n') {
208 count++;
209 nl_just_seen = 1;
210 completely_empty = 0;
211 }
212 else {
213 nl_just_seen = 0;
214 completely_empty = 0;
215 }
216 }
217 if (completely_empty)
218 return 0;
219 if (!nl_just_seen)
220 count++; /* no trailing newline */
221 return count;
222}
223
6957eb9a
JH
224static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
225{
226 if (!DIFF_FILE_VALID(one)) {
227 mf->ptr = (char *)""; /* does not matter */
228 mf->size = 0;
229 return 0;
230 }
231 else if (diff_populate_filespec(one, 0))
232 return -1;
bb35fefb 233
6957eb9a
JH
234 mf->ptr = one->data;
235 mf->size = one->size;
236 return 0;
237}
238
239static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
240{
241 char *ptr = mf->ptr;
242 long size = mf->size;
243 int cnt = 0;
244
245 if (!size)
246 return cnt;
247 ptr += size - 1; /* pointing at the very end */
248 if (*ptr != '\n')
249 ; /* incomplete line */
250 else
251 ptr--; /* skip the last LF */
252 while (mf->ptr < ptr) {
253 char *prev_eol;
254 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
255 if (*prev_eol == '\n')
256 break;
257 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
258 break;
259 cnt++;
260 ptr = prev_eol - 1;
261 }
262 return cnt;
263}
264
265static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
266 struct emit_callback *ecbdata)
267{
268 int l1, l2, at;
269 unsigned ws_rule = ecbdata->ws_rule;
270 l1 = count_trailing_blank(mf1, ws_rule);
271 l2 = count_trailing_blank(mf2, ws_rule);
272 if (l2 <= l1) {
273 ecbdata->blank_at_eof_in_preimage = 0;
274 ecbdata->blank_at_eof_in_postimage = 0;
275 return;
276 }
277 at = count_lines(mf1->ptr, mf1->size);
278 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
279
280 at = count_lines(mf2->ptr, mf2->size);
281 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
282}
283
250f7993
JH
284static void emit_line_0(FILE *file, const char *set, const char *reset,
285 int first, const char *line, int len)
6957eb9a
JH
286{
287 int has_trailing_newline, has_trailing_carriage_return;
250f7993 288 int nofirst;
6957eb9a 289
250f7993
JH
290 if (len == 0) {
291 has_trailing_newline = (first == '\n');
292 has_trailing_carriage_return = (!has_trailing_newline &&
293 (first == '\r'));
294 nofirst = has_trailing_newline || has_trailing_carriage_return;
295 } else {
296 has_trailing_newline = (len > 0 && line[len-1] == '\n');
297 if (has_trailing_newline)
298 len--;
299 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
300 if (has_trailing_carriage_return)
301 len--;
302 nofirst = 0;
303 }
6957eb9a 304
06a47552
JH
305 if (len || !nofirst) {
306 fputs(set, file);
307 if (!nofirst)
308 fputc(first, file);
309 fwrite(line, len, 1, file);
310 fputs(reset, file);
311 }
6957eb9a
JH
312 if (has_trailing_carriage_return)
313 fputc('\r', file);
314 if (has_trailing_newline)
315 fputc('\n', file);
316}
317
250f7993
JH
318static void emit_line(FILE *file, const char *set, const char *reset,
319 const char *line, int len)
320{
321 emit_line_0(file, set, reset, line[0], line+1, len-1);
322}
323
6957eb9a
JH
324static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
325{
326 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
327 ecbdata->blank_at_eof_in_preimage &&
328 ecbdata->blank_at_eof_in_postimage &&
329 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
330 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
331 return 0;
018cff70 332 return ws_blank_line(line, len, ecbdata->ws_rule);
6957eb9a
JH
333}
334
018cff70
JH
335static void emit_add_line(const char *reset,
336 struct emit_callback *ecbdata,
337 const char *line, int len)
6957eb9a
JH
338{
339 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
340 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
341
342 if (!*ws)
018cff70 343 emit_line_0(ecbdata->file, set, reset, '+', line, len);
6957eb9a
JH
344 else if (new_blank_line_at_eof(ecbdata, line, len))
345 /* Blank line at EOF - paint '+' as well */
018cff70 346 emit_line_0(ecbdata->file, ws, reset, '+', line, len);
6957eb9a
JH
347 else {
348 /* Emit just the prefix, then the rest. */
018cff70
JH
349 emit_line_0(ecbdata->file, set, reset, '+', "", 0);
350 ws_check_emit(line, len, ecbdata->ws_rule,
6957eb9a
JH
351 ecbdata->file, set, reset, ws);
352 }
353}
354
89cb73a1
BW
355static void emit_hunk_header(struct emit_callback *ecbdata,
356 const char *line, int len)
357{
358 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
359 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
360 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
361 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
362 static const char atat[2] = { '@', '@' };
363 const char *cp, *ep;
364
365 /*
366 * As a hunk header must begin with "@@ -<old>, +<new> @@",
367 * it always is at least 10 bytes long.
368 */
369 if (len < 10 ||
370 memcmp(line, atat, 2) ||
371 !(ep = memmem(line + 2, len - 2, atat, 2))) {
372 emit_line(ecbdata->file, plain, reset, line, len);
373 return;
374 }
375 ep += 2; /* skip over @@ */
376
377 /* The hunk header in fraginfo color */
378 emit_line(ecbdata->file, frag, reset, line, ep - line);
379
380 /* blank before the func header */
381 for (cp = ep; ep - line < len; ep++)
382 if (*ep != ' ' && *ep != '\t')
383 break;
384 if (ep != cp)
385 emit_line(ecbdata->file, plain, reset, cp, ep - cp);
386
387 if (ep < line + len)
388 emit_line(ecbdata->file, func, reset, ep, line + len - ep);
389}
390
479b0ae8
JK
391static struct diff_tempfile *claim_diff_tempfile(void) {
392 int i;
393 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
394 if (!diff_temp[i].name)
395 return diff_temp + i;
396 die("BUG: diff is failing to clean up its tempfiles");
397}
398
399static int remove_tempfile_installed;
400
401static void remove_tempfile(void)
402{
403 int i;
a8344abe
NR
404 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
405 if (diff_temp[i].name == diff_temp[i].tmp_path)
691f1a28 406 unlink_or_warn(diff_temp[i].name);
a8344abe
NR
407 diff_temp[i].name = NULL;
408 }
479b0ae8
JK
409}
410
411static void remove_tempfile_on_signal(int signo)
412{
413 remove_tempfile();
4a16d072 414 sigchain_pop(signo);
479b0ae8
JK
415 raise(signo);
416}
417
c0c77734 418static void print_line_count(FILE *file, int count)
6973dcae
JH
419{
420 switch (count) {
421 case 0:
c0c77734 422 fprintf(file, "0,0");
6973dcae
JH
423 break;
424 case 1:
c0c77734 425 fprintf(file, "1");
6973dcae
JH
426 break;
427 default:
c0c77734 428 fprintf(file, "1,%d", count);
6973dcae
JH
429 break;
430 }
431}
432
7f7ee2ff
JH
433static void emit_rewrite_lines(struct emit_callback *ecb,
434 int prefix, const char *data, int size)
6973dcae 435{
7f7ee2ff
JH
436 const char *endp = NULL;
437 static const char *nneof = " No newline at end of file\n";
438 const char *old = diff_get_color(ecb->color_diff, DIFF_FILE_OLD);
439 const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
440
441 while (0 < size) {
442 int len;
443
444 endp = memchr(data, '\n', size);
445 len = endp ? (endp - data + 1) : size;
446 if (prefix != '+') {
447 ecb->lno_in_preimage++;
448 emit_line_0(ecb->file, old, reset, '-',
449 data, len);
450 } else {
451 ecb->lno_in_postimage++;
452 emit_add_line(reset, ecb, data, len);
13e36ec5 453 }
7f7ee2ff
JH
454 size -= len;
455 data += len;
456 }
457 if (!endp) {
458 const char *plain = diff_get_color(ecb->color_diff,
459 DIFF_PLAIN);
460 emit_line_0(ecb->file, plain, reset, '\\',
461 nneof, strlen(nneof));
6973dcae 462 }
6973dcae
JH
463}
464
465static void emit_rewrite_diff(const char *name_a,
466 const char *name_b,
467 struct diff_filespec *one,
13e36ec5 468 struct diff_filespec *two,
3aa1f7ca
JK
469 const char *textconv_one,
470 const char *textconv_two,
eab9a40b 471 struct diff_options *o)
6973dcae
JH
472{
473 int lc_a, lc_b;
eab9a40b 474 int color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
1a9eb3b9 475 const char *name_a_tab, *name_b_tab;
13e36ec5
JS
476 const char *metainfo = diff_get_color(color_diff, DIFF_METAINFO);
477 const char *fraginfo = diff_get_color(color_diff, DIFF_FRAGINFO);
13e36ec5 478 const char *reset = diff_get_color(color_diff, DIFF_RESET);
d5625091 479 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
a5a818ee 480 const char *a_prefix, *b_prefix;
3aa1f7ca
JK
481 const char *data_one, *data_two;
482 size_t size_one, size_two;
7f7ee2ff 483 struct emit_callback ecbdata;
a5a818ee
JH
484
485 if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
486 a_prefix = o->b_prefix;
487 b_prefix = o->a_prefix;
488 } else {
489 a_prefix = o->a_prefix;
490 b_prefix = o->b_prefix;
491 }
1a9eb3b9 492
8a13becc
JH
493 name_a += (*name_a == '/');
494 name_b += (*name_b == '/');
1a9eb3b9
JH
495 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
496 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
497
d5625091
JH
498 strbuf_reset(&a_name);
499 strbuf_reset(&b_name);
a5a818ee
JH
500 quote_two_c_style(&a_name, a_prefix, name_a, 0);
501 quote_two_c_style(&b_name, b_prefix, name_b, 0);
d5625091 502
6973dcae
JH
503 diff_populate_filespec(one, 0);
504 diff_populate_filespec(two, 0);
3aa1f7ca
JK
505 if (textconv_one) {
506 data_one = run_textconv(textconv_one, one, &size_one);
507 if (!data_one)
508 die("unable to read files to diff");
509 }
510 else {
511 data_one = one->data;
512 size_one = one->size;
513 }
514 if (textconv_two) {
515 data_two = run_textconv(textconv_two, two, &size_two);
516 if (!data_two)
517 die("unable to read files to diff");
518 }
519 else {
520 data_two = two->data;
521 size_two = two->size;
522 }
523
d91ba8fa
JH
524 memset(&ecbdata, 0, sizeof(ecbdata));
525 ecbdata.color_diff = color_diff;
526 ecbdata.found_changesp = &o->found_changes;
527 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
528 ecbdata.file = o->file;
529 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
530 mmfile_t mf1, mf2;
531 mf1.ptr = (char *)data_one;
532 mf2.ptr = (char *)data_two;
533 mf1.size = size_one;
534 mf2.size = size_two;
535 check_blank_at_eof(&mf1, &mf2, &ecbdata);
536 }
537 ecbdata.lno_in_preimage = 1;
538 ecbdata.lno_in_postimage = 1;
539
3aa1f7ca
JK
540 lc_a = count_lines(data_one, size_one);
541 lc_b = count_lines(data_two, size_two);
c0c77734
DB
542 fprintf(o->file,
543 "%s--- %s%s%s\n%s+++ %s%s%s\n%s@@ -",
544 metainfo, a_name.buf, name_a_tab, reset,
545 metainfo, b_name.buf, name_b_tab, reset, fraginfo);
546 print_line_count(o->file, lc_a);
547 fprintf(o->file, " +");
548 print_line_count(o->file, lc_b);
549 fprintf(o->file, " @@%s\n", reset);
6973dcae 550 if (lc_a)
d91ba8fa 551 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
6973dcae 552 if (lc_b)
d91ba8fa 553 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
b76c056b 554 if (textconv_one)
aed6ca52 555 free((char *)data_one);
b76c056b 556 if (textconv_two)
aed6ca52 557 free((char *)data_two);
6973dcae
JH
558}
559
f59a59e2
JS
560struct diff_words_buffer {
561 mmfile_t text;
562 long alloc;
2e5d2003
JS
563 struct diff_words_orig {
564 const char *begin, *end;
565 } *orig;
566 int orig_nr, orig_alloc;
f59a59e2
JS
567};
568
569static void diff_words_append(char *line, unsigned long len,
570 struct diff_words_buffer *buffer)
571{
23c1575f 572 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
f59a59e2
JS
573 line++;
574 len--;
575 memcpy(buffer->text.ptr + buffer->text.size, line, len);
576 buffer->text.size += len;
2b6a5417 577 buffer->text.ptr[buffer->text.size] = '\0';
f59a59e2
JS
578}
579
580struct diff_words_data {
f59a59e2 581 struct diff_words_buffer minus, plus;
2e5d2003 582 const char *current_plus;
c0c77734 583 FILE *file;
2b6a5417 584 regex_t *word_regex;
f59a59e2
JS
585};
586
f59a59e2 587static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
f59a59e2 588{
f59a59e2 589 struct diff_words_data *diff_words = priv;
2e5d2003
JS
590 int minus_first, minus_len, plus_first, plus_len;
591 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
f59a59e2 592
2e5d2003
JS
593 if (line[0] != '@' || parse_hunk_header(line, len,
594 &minus_first, &minus_len, &plus_first, &plus_len))
f59a59e2
JS
595 return;
596
2e5d2003
JS
597 /* POSIX requires that first be decremented by one if len == 0... */
598 if (minus_len) {
599 minus_begin = diff_words->minus.orig[minus_first].begin;
600 minus_end =
601 diff_words->minus.orig[minus_first + minus_len - 1].end;
602 } else
603 minus_begin = minus_end =
604 diff_words->minus.orig[minus_first].end;
605
606 if (plus_len) {
607 plus_begin = diff_words->plus.orig[plus_first].begin;
608 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
609 } else
610 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
611
612 if (diff_words->current_plus != plus_begin)
613 fwrite(diff_words->current_plus,
614 plus_begin - diff_words->current_plus, 1,
615 diff_words->file);
616 if (minus_begin != minus_end)
617 color_fwrite_lines(diff_words->file,
618 diff_get_color(1, DIFF_FILE_OLD),
619 minus_end - minus_begin, minus_begin);
620 if (plus_begin != plus_end)
621 color_fwrite_lines(diff_words->file,
622 diff_get_color(1, DIFF_FILE_NEW),
623 plus_end - plus_begin, plus_begin);
624
625 diff_words->current_plus = plus_end;
f59a59e2
JS
626}
627
2b6a5417
JS
628/* This function starts looking at *begin, and returns 0 iff a word was found. */
629static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
630 int *begin, int *end)
631{
632 if (word_regex && *begin < buffer->size) {
633 regmatch_t match[1];
634 if (!regexec(word_regex, buffer->ptr + *begin, 1, match, 0)) {
635 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
636 '\n', match[0].rm_eo - match[0].rm_so);
637 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
638 *begin += match[0].rm_so;
639 return *begin >= *end;
640 }
641 return -1;
f59a59e2
JS
642 }
643
2b6a5417
JS
644 /* find the next word */
645 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
646 (*begin)++;
647 if (*begin >= buffer->size)
648 return -1;
f59a59e2 649
2b6a5417
JS
650 /* find the end of the word */
651 *end = *begin + 1;
652 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
653 (*end)++;
654
655 return 0;
f59a59e2
JS
656}
657
23c1575f 658/*
2e5d2003
JS
659 * This function splits the words in buffer->text, stores the list with
660 * newline separator into out, and saves the offsets of the original words
661 * in buffer->orig.
23c1575f 662 */
2b6a5417
JS
663static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
664 regex_t *word_regex)
f59a59e2 665{
2e5d2003 666 int i, j;
2b6a5417 667 long alloc = 0;
f59a59e2 668
2e5d2003 669 out->size = 0;
2b6a5417 670 out->ptr = NULL;
f59a59e2 671
2e5d2003
JS
672 /* fake an empty "0th" word */
673 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
674 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
675 buffer->orig_nr = 1;
676
677 for (i = 0; i < buffer->text.size; i++) {
2b6a5417
JS
678 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
679 return;
2e5d2003
JS
680
681 /* store original boundaries */
682 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
683 buffer->orig_alloc);
684 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
685 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
686 buffer->orig_nr++;
687
688 /* store one word */
2b6a5417 689 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
2e5d2003
JS
690 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
691 out->ptr[out->size + j - i] = '\n';
692 out->size += j - i + 1;
693
694 i = j - 1;
f59a59e2
JS
695 }
696}
697
698/* this executes the word diff on the accumulated buffers */
699static void diff_words_show(struct diff_words_data *diff_words)
700{
701 xpparam_t xpp;
702 xdemitconf_t xecfg;
703 xdemitcb_t ecb;
704 mmfile_t minus, plus;
f59a59e2 705
2e5d2003
JS
706 /* special case: only removal */
707 if (!diff_words->plus.text.size) {
708 color_fwrite_lines(diff_words->file,
709 diff_get_color(1, DIFF_FILE_OLD),
710 diff_words->minus.text.size, diff_words->minus.text.ptr);
711 diff_words->minus.text.size = 0;
712 return;
713 }
714
715 diff_words->current_plus = diff_words->plus.text.ptr;
f59a59e2 716
9ccd0a88 717 memset(&xpp, 0, sizeof(xpp));
30b25010 718 memset(&xecfg, 0, sizeof(xecfg));
2b6a5417
JS
719 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
720 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
f59a59e2 721 xpp.flags = XDF_NEED_MINIMAL;
2b6a5417 722 /* as only the hunk header will be parsed, we need a 0-context */
2e5d2003 723 xecfg.ctxlen = 0;
8a3f524b
JH
724 xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
725 &xpp, &xecfg, &ecb);
f59a59e2
JS
726 free(minus.ptr);
727 free(plus.ptr);
2e5d2003
JS
728 if (diff_words->current_plus != diff_words->plus.text.ptr +
729 diff_words->plus.text.size)
730 fwrite(diff_words->current_plus,
731 diff_words->plus.text.ptr + diff_words->plus.text.size
732 - diff_words->current_plus, 1,
733 diff_words->file);
f59a59e2 734 diff_words->minus.text.size = diff_words->plus.text.size = 0;
f59a59e2
JS
735}
736
76fd2828
JH
737/* In "color-words" mode, show word-diff of words accumulated in the buffer */
738static void diff_words_flush(struct emit_callback *ecbdata)
739{
740 if (ecbdata->diff_words->minus.text.size ||
741 ecbdata->diff_words->plus.text.size)
742 diff_words_show(ecbdata->diff_words);
743}
744
f59a59e2
JS
745static void free_diff_words_data(struct emit_callback *ecbdata)
746{
747 if (ecbdata->diff_words) {
76fd2828 748 diff_words_flush(ecbdata);
8e0f7003 749 free (ecbdata->diff_words->minus.text.ptr);
2e5d2003 750 free (ecbdata->diff_words->minus.orig);
8e0f7003 751 free (ecbdata->diff_words->plus.text.ptr);
2e5d2003 752 free (ecbdata->diff_words->plus.orig);
2b6a5417 753 free(ecbdata->diff_words->word_regex);
f59a59e2
JS
754 free(ecbdata->diff_words);
755 ecbdata->diff_words = NULL;
756 }
757}
758
ce436973 759const char *diff_get_color(int diff_use_color, enum color_diff ix)
cd112cef
JS
760{
761 if (diff_use_color)
50f575fc
LT
762 return diff_colors[ix];
763 return "";
cd112cef
JS
764}
765
23707811
JH
766static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
767{
768 const char *cp;
769 unsigned long allot;
770 size_t l = len;
771
772 if (ecb->truncate)
773 return ecb->truncate(line, len);
774 cp = line;
775 allot = l;
776 while (0 < l) {
777 (void) utf8_width(&cp, &l);
778 if (!cp)
779 break; /* truncated in the middle? */
780 }
781 return allot - l;
782}
783
d68fe26f 784static void find_lno(const char *line, struct emit_callback *ecbdata)
690ed843 785{
d68fe26f
JH
786 const char *p;
787 ecbdata->lno_in_preimage = 0;
788 ecbdata->lno_in_postimage = 0;
789 p = strchr(line, '-');
690ed843 790 if (!p)
d68fe26f
JH
791 return; /* cannot happen */
792 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
793 p = strchr(p, '+');
794 if (!p)
795 return; /* cannot happen */
796 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
690ed843
JH
797}
798
cd112cef 799static void fn_out_consume(void *priv, char *line, unsigned long len)
6973dcae 800{
6973dcae 801 struct emit_callback *ecbdata = priv;
472ca780
JK
802 const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
803 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
ce436973 804 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
6973dcae 805
3e97c7c6
GB
806 if (ecbdata->header) {
807 fprintf(ecbdata->file, "%s", ecbdata->header->buf);
808 strbuf_reset(ecbdata->header);
809 ecbdata->header = NULL;
810 }
34a5e1a2
JS
811 *(ecbdata->found_changesp) = 1;
812
6973dcae 813 if (ecbdata->label_path[0]) {
1a9eb3b9
JH
814 const char *name_a_tab, *name_b_tab;
815
816 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
817 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
818
c0c77734
DB
819 fprintf(ecbdata->file, "%s--- %s%s%s\n",
820 meta, ecbdata->label_path[0], reset, name_a_tab);
821 fprintf(ecbdata->file, "%s+++ %s%s%s\n",
822 meta, ecbdata->label_path[1], reset, name_b_tab);
6973dcae
JH
823 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
824 }
cd112cef 825
a624eaa7
JM
826 if (diff_suppress_blank_empty
827 && len == 2 && line[0] == ' ' && line[1] == '\n') {
828 line[0] = '\n';
829 len = 1;
830 }
831
b8d9c1a6 832 if (line[0] == '@') {
76fd2828
JH
833 if (ecbdata->diff_words)
834 diff_words_flush(ecbdata);
23707811 835 len = sane_truncate_line(ecbdata, line, len);
d68fe26f 836 find_lno(line, ecbdata);
89cb73a1 837 emit_hunk_header(ecbdata, line, len);
23707811 838 if (line[len-1] != '\n')
c0c77734 839 putc('\n', ecbdata->file);
448c3ef1 840 return;
cd112cef 841 }
448c3ef1 842
b8d9c1a6 843 if (len < 1) {
c0c77734 844 emit_line(ecbdata->file, reset, reset, line, len);
448c3ef1 845 return;
cd112cef 846 }
448c3ef1 847
448c3ef1
JH
848 if (ecbdata->diff_words) {
849 if (line[0] == '-') {
850 diff_words_append(line, len,
851 &ecbdata->diff_words->minus);
852 return;
853 } else if (line[0] == '+') {
854 diff_words_append(line, len,
855 &ecbdata->diff_words->plus);
856 return;
857 }
76fd2828 858 diff_words_flush(ecbdata);
448c3ef1 859 line++;
50f575fc 860 len--;
c0c77734 861 emit_line(ecbdata->file, plain, reset, line, len);
448c3ef1
JH
862 return;
863 }
448c3ef1 864
690ed843
JH
865 if (line[0] != '+') {
866 const char *color =
867 diff_get_color(ecbdata->color_diff,
868 line[0] == '-' ? DIFF_FILE_OLD : DIFF_PLAIN);
869 ecbdata->lno_in_preimage++;
d68fe26f
JH
870 if (line[0] == ' ')
871 ecbdata->lno_in_postimage++;
690ed843 872 emit_line(ecbdata->file, color, reset, line, len);
d68fe26f
JH
873 } else {
874 ecbdata->lno_in_postimage++;
018cff70 875 emit_add_line(reset, ecbdata, line + 1, len - 1);
448c3ef1 876 }
6973dcae
JH
877}
878
879static char *pprint_rename(const char *a, const char *b)
880{
881 const char *old = a;
882 const char *new = b;
f285a2d7 883 struct strbuf name = STRBUF_INIT;
6973dcae
JH
884 int pfx_length, sfx_length;
885 int len_a = strlen(a);
886 int len_b = strlen(b);
663af342 887 int a_midlen, b_midlen;
e5bfbf9b
AJ
888 int qlen_a = quote_c_style(a, NULL, NULL, 0);
889 int qlen_b = quote_c_style(b, NULL, NULL, 0);
890
891 if (qlen_a || qlen_b) {
663af342
PH
892 quote_c_style(a, &name, NULL, 0);
893 strbuf_addstr(&name, " => ");
894 quote_c_style(b, &name, NULL, 0);
b315c5c0 895 return strbuf_detach(&name, NULL);
e5bfbf9b 896 }
6973dcae
JH
897
898 /* Find common prefix */
899 pfx_length = 0;
900 while (*old && *new && *old == *new) {
901 if (*old == '/')
902 pfx_length = old - a + 1;
903 old++;
904 new++;
905 }
906
907 /* Find common suffix */
908 old = a + len_a;
909 new = b + len_b;
910 sfx_length = 0;
911 while (a <= old && b <= new && *old == *new) {
912 if (*old == '/')
913 sfx_length = len_a - (old - a);
914 old--;
915 new--;
916 }
917
918 /*
919 * pfx{mid-a => mid-b}sfx
920 * {pfx-a => pfx-b}sfx
921 * pfx{sfx-a => sfx-b}
922 * name-a => name-b
923 */
663af342
PH
924 a_midlen = len_a - pfx_length - sfx_length;
925 b_midlen = len_b - pfx_length - sfx_length;
926 if (a_midlen < 0)
927 a_midlen = 0;
928 if (b_midlen < 0)
929 b_midlen = 0;
930
931 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
6973dcae 932 if (pfx_length + sfx_length) {
663af342
PH
933 strbuf_add(&name, a, pfx_length);
934 strbuf_addch(&name, '{');
6973dcae 935 }
663af342
PH
936 strbuf_add(&name, a + pfx_length, a_midlen);
937 strbuf_addstr(&name, " => ");
938 strbuf_add(&name, b + pfx_length, b_midlen);
939 if (pfx_length + sfx_length) {
940 strbuf_addch(&name, '}');
941 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
6973dcae 942 }
b315c5c0 943 return strbuf_detach(&name, NULL);
6973dcae
JH
944}
945
946struct diffstat_t {
6973dcae
JH
947 int nr;
948 int alloc;
949 struct diffstat_file {
f604652e 950 char *from_name;
6973dcae 951 char *name;
f604652e 952 char *print_name;
6973dcae
JH
953 unsigned is_unmerged:1;
954 unsigned is_binary:1;
955 unsigned is_renamed:1;
0974c117 956 uintmax_t added, deleted;
6973dcae
JH
957 } **files;
958};
959
960static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
961 const char *name_a,
962 const char *name_b)
963{
964 struct diffstat_file *x;
965 x = xcalloc(sizeof (*x), 1);
966 if (diffstat->nr == diffstat->alloc) {
967 diffstat->alloc = alloc_nr(diffstat->alloc);
968 diffstat->files = xrealloc(diffstat->files,
969 diffstat->alloc * sizeof(x));
970 }
971 diffstat->files[diffstat->nr++] = x;
972 if (name_b) {
f604652e
JH
973 x->from_name = xstrdup(name_a);
974 x->name = xstrdup(name_b);
6973dcae
JH
975 x->is_renamed = 1;
976 }
f604652e
JH
977 else {
978 x->from_name = NULL;
9befac47 979 x->name = xstrdup(name_a);
f604652e 980 }
6973dcae
JH
981 return x;
982}
983
984static void diffstat_consume(void *priv, char *line, unsigned long len)
985{
986 struct diffstat_t *diffstat = priv;
987 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
988
989 if (line[0] == '+')
990 x->added++;
991 else if (line[0] == '-')
992 x->deleted++;
993}
994
698ce6f8 995const char mime_boundary_leader[] = "------------";
6973dcae 996
a2540023
JH
997static int scale_linear(int it, int width, int max_change)
998{
999 /*
3ed74e60
JS
1000 * make sure that at least one '-' is printed if there were deletions,
1001 * and likewise for '+'.
a2540023 1002 */
3ed74e60
JS
1003 if (max_change < 2)
1004 return it;
1005 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
a2540023
JH
1006}
1007
c0c77734 1008static void show_name(FILE *file,
a408e0e6 1009 const char *prefix, const char *name, int len)
a2540023 1010{
a408e0e6 1011 fprintf(file, " %s%-*s |", prefix, len, name);
a2540023
JH
1012}
1013
c0c77734 1014static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
a2540023
JH
1015{
1016 if (cnt <= 0)
1017 return;
c0c77734 1018 fprintf(file, "%s", set);
a2540023 1019 while (cnt--)
c0c77734
DB
1020 putc(ch, file);
1021 fprintf(file, "%s", reset);
a2540023
JH
1022}
1023
f604652e
JH
1024static void fill_print_name(struct diffstat_file *file)
1025{
1026 char *pname;
1027
1028 if (file->print_name)
1029 return;
1030
1031 if (!file->is_renamed) {
f285a2d7 1032 struct strbuf buf = STRBUF_INIT;
f604652e
JH
1033 if (quote_c_style(file->name, &buf, NULL, 0)) {
1034 pname = strbuf_detach(&buf, NULL);
1035 } else {
1036 pname = file->name;
1037 strbuf_release(&buf);
1038 }
1039 } else {
1040 pname = pprint_rename(file->from_name, file->name);
1041 }
1042 file->print_name = pname;
1043}
1044
4b25d091 1045static void show_stats(struct diffstat_t *data, struct diff_options *options)
6973dcae 1046{
eb3a9dd3 1047 int i, len, add, del, adds = 0, dels = 0;
0974c117 1048 uintmax_t max_change = 0, max_len = 0;
6973dcae 1049 int total_files = data->nr;
a2540023 1050 int width, name_width;
785f7432 1051 const char *reset, *set, *add_c, *del_c;
6973dcae
JH
1052
1053 if (data->nr == 0)
1054 return;
1055
a2540023
JH
1056 width = options->stat_width ? options->stat_width : 80;
1057 name_width = options->stat_name_width ? options->stat_name_width : 50;
1058
1059 /* Sanity: give at least 5 columns to the graph,
1060 * but leave at least 10 columns for the name.
1061 */
861d1af3
OM
1062 if (width < 25)
1063 width = 25;
1064 if (name_width < 10)
1065 name_width = 10;
1066 else if (width < name_width + 15)
1067 name_width = width - 15;
a2540023
JH
1068
1069 /* Find the longest filename and max number of changes */
8f67f8ae
PH
1070 reset = diff_get_color_opt(options, DIFF_RESET);
1071 set = diff_get_color_opt(options, DIFF_PLAIN);
1072 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
1073 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
785f7432 1074
6973dcae
JH
1075 for (i = 0; i < data->nr; i++) {
1076 struct diffstat_file *file = data->files[i];
0974c117 1077 uintmax_t change = file->added + file->deleted;
f604652e
JH
1078 fill_print_name(file);
1079 len = strlen(file->print_name);
6973dcae
JH
1080 if (max_len < len)
1081 max_len = len;
1082
1083 if (file->is_binary || file->is_unmerged)
1084 continue;
a2540023
JH
1085 if (max_change < change)
1086 max_change = change;
6973dcae
JH
1087 }
1088
a2540023
JH
1089 /* Compute the width of the graph part;
1090 * 10 is for one blank at the beginning of the line plus
1091 * " | count " between the name and the graph.
1092 *
1093 * From here on, name_width is the width of the name area,
1094 * and width is the width of the graph area.
1095 */
1096 name_width = (name_width < max_len) ? name_width : max_len;
1097 if (width < (name_width + 10) + max_change)
1098 width = width - (name_width + 10);
1099 else
1100 width = max_change;
1101
6973dcae 1102 for (i = 0; i < data->nr; i++) {
d2543b8e 1103 const char *prefix = "";
f604652e 1104 char *name = data->files[i]->print_name;
0974c117
JK
1105 uintmax_t added = data->files[i]->added;
1106 uintmax_t deleted = data->files[i]->deleted;
a2540023 1107 int name_len;
6973dcae
JH
1108
1109 /*
1110 * "scale" the filename
1111 */
a2540023
JH
1112 len = name_width;
1113 name_len = strlen(name);
1114 if (name_width < name_len) {
6973dcae
JH
1115 char *slash;
1116 prefix = "...";
a2540023
JH
1117 len -= 3;
1118 name += name_len - len;
6973dcae
JH
1119 slash = strchr(name, '/');
1120 if (slash)
1121 name = slash;
1122 }
6973dcae
JH
1123
1124 if (data->files[i]->is_binary) {
a408e0e6 1125 show_name(options->file, prefix, name, len);
c0c77734 1126 fprintf(options->file, " Bin ");
0974c117
JK
1127 fprintf(options->file, "%s%"PRIuMAX"%s",
1128 del_c, deleted, reset);
c0c77734 1129 fprintf(options->file, " -> ");
0974c117
JK
1130 fprintf(options->file, "%s%"PRIuMAX"%s",
1131 add_c, added, reset);
c0c77734
DB
1132 fprintf(options->file, " bytes");
1133 fprintf(options->file, "\n");
f604652e 1134 continue;
6973dcae
JH
1135 }
1136 else if (data->files[i]->is_unmerged) {
a408e0e6 1137 show_name(options->file, prefix, name, len);
c0c77734 1138 fprintf(options->file, " Unmerged\n");
f604652e 1139 continue;
6973dcae
JH
1140 }
1141 else if (!data->files[i]->is_renamed &&
1142 (added + deleted == 0)) {
1143 total_files--;
f604652e 1144 continue;
6973dcae
JH
1145 }
1146
a2540023
JH
1147 /*
1148 * scale the add/delete
1149 */
6973dcae
JH
1150 add = added;
1151 del = deleted;
6973dcae
JH
1152 adds += add;
1153 dels += del;
1154
a2540023 1155 if (width <= max_change) {
a2540023 1156 add = scale_linear(add, width, max_change);
3ed74e60 1157 del = scale_linear(del, width, max_change);
6973dcae 1158 }
a408e0e6 1159 show_name(options->file, prefix, name, len);
0974c117 1160 fprintf(options->file, "%5"PRIuMAX"%s", added + deleted,
4d9b5359 1161 added + deleted ? " " : "");
c0c77734
DB
1162 show_graph(options->file, '+', add, add_c, reset);
1163 show_graph(options->file, '-', del, del_c, reset);
1164 fprintf(options->file, "\n");
1165 }
1166 fprintf(options->file,
a408e0e6
MH
1167 " %d files changed, %d insertions(+), %d deletions(-)\n",
1168 total_files, adds, dels);
6973dcae
JH
1169}
1170
2775d92c 1171static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
ebd124c6
NP
1172{
1173 int i, adds = 0, dels = 0, total_files = data->nr;
1174
1175 if (data->nr == 0)
1176 return;
1177
1178 for (i = 0; i < data->nr; i++) {
1179 if (!data->files[i]->is_binary &&
1180 !data->files[i]->is_unmerged) {
1181 int added = data->files[i]->added;
1182 int deleted= data->files[i]->deleted;
1183 if (!data->files[i]->is_renamed &&
1184 (added + deleted == 0)) {
1185 total_files--;
1186 } else {
1187 adds += added;
1188 dels += deleted;
1189 }
1190 }
ebd124c6 1191 }
c0c77734 1192 fprintf(options->file, " %d files changed, %d insertions(+), %d deletions(-)\n",
ebd124c6
NP
1193 total_files, adds, dels);
1194}
1195
4b25d091 1196static void show_numstat(struct diffstat_t *data, struct diff_options *options)
74e2abe5
JH
1197{
1198 int i;
1199
f604652e
JH
1200 if (data->nr == 0)
1201 return;
1202
74e2abe5
JH
1203 for (i = 0; i < data->nr; i++) {
1204 struct diffstat_file *file = data->files[i];
1205
bfddbc5e 1206 if (file->is_binary)
c0c77734 1207 fprintf(options->file, "-\t-\t");
bfddbc5e 1208 else
c0c77734 1209 fprintf(options->file,
0974c117
JK
1210 "%"PRIuMAX"\t%"PRIuMAX"\t",
1211 file->added, file->deleted);
f604652e
JH
1212 if (options->line_termination) {
1213 fill_print_name(file);
1214 if (!file->is_renamed)
c0c77734 1215 write_name_quoted(file->name, options->file,
f604652e
JH
1216 options->line_termination);
1217 else {
c0c77734
DB
1218 fputs(file->print_name, options->file);
1219 putc(options->line_termination, options->file);
f604652e 1220 }
663af342 1221 } else {
f604652e 1222 if (file->is_renamed) {
c0c77734
DB
1223 putc('\0', options->file);
1224 write_name_quoted(file->from_name, options->file, '\0');
f604652e 1225 }
c0c77734 1226 write_name_quoted(file->name, options->file, '\0');
663af342 1227 }
74e2abe5
JH
1228 }
1229}
1230
c04a7155
JH
1231struct dirstat_file {
1232 const char *name;
1233 unsigned long changed;
7df7c019
LT
1234};
1235
c04a7155
JH
1236struct dirstat_dir {
1237 struct dirstat_file *files;
1238 int alloc, nr, percent, cumulative;
1239};
1240
1241static long gather_dirstat(FILE *file, struct dirstat_dir *dir, unsigned long changed, const char *base, int baselen)
7df7c019
LT
1242{
1243 unsigned long this_dir = 0;
1244 unsigned int sources = 0;
1245
1246 while (dir->nr) {
c04a7155 1247 struct dirstat_file *f = dir->files;
7df7c019
LT
1248 int namelen = strlen(f->name);
1249 unsigned long this;
1250 char *slash;
1251
1252 if (namelen < baselen)
1253 break;
1254 if (memcmp(f->name, base, baselen))
1255 break;
1256 slash = strchr(f->name + baselen, '/');
1257 if (slash) {
1258 int newbaselen = slash + 1 - f->name;
c0c77734 1259 this = gather_dirstat(file, dir, changed, f->name, newbaselen);
7df7c019
LT
1260 sources++;
1261 } else {
c04a7155 1262 this = f->changed;
7df7c019
LT
1263 dir->files++;
1264 dir->nr--;
1265 sources += 2;
1266 }
1267 this_dir += this;
1268 }
1269
1270 /*
1271 * We don't report dirstat's for
1272 * - the top level
1273 * - or cases where everything came from a single directory
1274 * under this directory (sources == 1).
1275 */
1276 if (baselen && sources != 1) {
1277 int permille = this_dir * 1000 / changed;
1278 if (permille) {
1279 int percent = permille / 10;
1280 if (percent >= dir->percent) {
c0c77734 1281 fprintf(file, "%4d.%01d%% %.*s\n", percent, permille % 10, baselen, base);
7df7c019
LT
1282 if (!dir->cumulative)
1283 return 0;
1284 }
1285 }
1286 }
1287 return this_dir;
1288}
1289
441bca0b
LT
1290static int dirstat_compare(const void *_a, const void *_b)
1291{
1292 const struct dirstat_file *a = _a;
1293 const struct dirstat_file *b = _b;
1294 return strcmp(a->name, b->name);
1295}
1296
c04a7155 1297static void show_dirstat(struct diff_options *options)
7df7c019
LT
1298{
1299 int i;
1300 unsigned long changed;
c04a7155
JH
1301 struct dirstat_dir dir;
1302 struct diff_queue_struct *q = &diff_queued_diff;
1303
1304 dir.files = NULL;
1305 dir.alloc = 0;
1306 dir.nr = 0;
1307 dir.percent = options->dirstat_percent;
f88d225f 1308 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
7df7c019 1309
7df7c019 1310 changed = 0;
c04a7155
JH
1311 for (i = 0; i < q->nr; i++) {
1312 struct diff_filepair *p = q->queue[i];
1313 const char *name;
1314 unsigned long copied, added, damage;
1315
1316 name = p->one->path ? p->one->path : p->two->path;
1317
1318 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1319 diff_populate_filespec(p->one, 0);
1320 diff_populate_filespec(p->two, 0);
1321 diffcore_count_changes(p->one, p->two, NULL, NULL, 0,
1322 &copied, &added);
1323 diff_free_filespec_data(p->one);
1324 diff_free_filespec_data(p->two);
1325 } else if (DIFF_FILE_VALID(p->one)) {
1326 diff_populate_filespec(p->one, 1);
1327 copied = added = 0;
1328 diff_free_filespec_data(p->one);
1329 } else if (DIFF_FILE_VALID(p->two)) {
1330 diff_populate_filespec(p->two, 1);
1331 copied = 0;
1332 added = p->two->size;
1333 diff_free_filespec_data(p->two);
1334 } else
2b0b551d 1335 continue;
c04a7155
JH
1336
1337 /*
1338 * Original minus copied is the removed material,
1339 * added is the new material. They are both damages
fd33777b
HO
1340 * made to the preimage. In --dirstat-by-file mode, count
1341 * damaged files, not damaged lines. This is done by
1342 * counting only a single damaged line per file.
c04a7155
JH
1343 */
1344 damage = (p->one->size - copied) + added;
fd33777b
HO
1345 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE) && damage > 0)
1346 damage = 1;
c04a7155
JH
1347
1348 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1349 dir.files[dir.nr].name = name;
1350 dir.files[dir.nr].changed = damage;
1351 changed += damage;
1352 dir.nr++;
7df7c019
LT
1353 }
1354
1355 /* This can happen even with many files, if everything was renames */
1356 if (!changed)
1357 return;
1358
1359 /* Show all directories with more than x% of the changes */
441bca0b 1360 qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
c0c77734 1361 gather_dirstat(options->file, &dir, changed, "", 0);
7df7c019
LT
1362}
1363
f604652e
JH
1364static void free_diffstat_info(struct diffstat_t *diffstat)
1365{
1366 int i;
1367 for (i = 0; i < diffstat->nr; i++) {
1368 struct diffstat_file *f = diffstat->files[i];
1369 if (f->name != f->print_name)
1370 free(f->print_name);
1371 free(f->name);
1372 free(f->from_name);
1373 free(f);
1374 }
1375 free(diffstat->files);
1376}
1377
88246898 1378struct checkdiff_t {
88246898 1379 const char *filename;
1ba111d1 1380 int lineno;
a757c646 1381 int conflict_marker_size;
1ba111d1 1382 struct diff_options *o;
cf1b7869 1383 unsigned ws_rule;
62c64895 1384 unsigned status;
88246898
JS
1385};
1386
a757c646 1387static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
04954043
JH
1388{
1389 char firstchar;
1390 int cnt;
1391
a757c646 1392 if (len < marker_size + 1)
04954043
JH
1393 return 0;
1394 firstchar = line[0];
1395 switch (firstchar) {
a757c646 1396 case '=': case '>': case '<': case '|':
04954043
JH
1397 break;
1398 default:
1399 return 0;
1400 }
a757c646 1401 for (cnt = 1; cnt < marker_size; cnt++)
04954043
JH
1402 if (line[cnt] != firstchar)
1403 return 0;
a757c646
JH
1404 /* line[1] thru line[marker_size-1] are same as firstchar */
1405 if (len < marker_size + 1 || !isspace(line[marker_size]))
04954043 1406 return 0;
04954043
JH
1407 return 1;
1408}
1409
88246898
JS
1410static void checkdiff_consume(void *priv, char *line, unsigned long len)
1411{
1412 struct checkdiff_t *data = priv;
1ba111d1 1413 int color_diff = DIFF_OPT_TST(data->o, COLOR_DIFF);
a757c646 1414 int marker_size = data->conflict_marker_size;
1ba111d1
JH
1415 const char *ws = diff_get_color(color_diff, DIFF_WHITESPACE);
1416 const char *reset = diff_get_color(color_diff, DIFF_RESET);
1417 const char *set = diff_get_color(color_diff, DIFF_FILE_NEW);
c1795bb0 1418 char *err;
88246898
JS
1419
1420 if (line[0] == '+') {
18374e58 1421 unsigned bad;
0ef617f4 1422 data->lineno++;
a757c646 1423 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
04954043
JH
1424 data->status |= 1;
1425 fprintf(data->o->file,
1426 "%s:%d: leftover conflict marker\n",
1427 data->filename, data->lineno);
1428 }
8f8841e9 1429 bad = ws_check(line + 1, len - 1, data->ws_rule);
18374e58 1430 if (!bad)
c1795bb0 1431 return;
18374e58
JH
1432 data->status |= bad;
1433 err = whitespace_error_string(bad);
1ba111d1
JH
1434 fprintf(data->o->file, "%s:%d: %s.\n",
1435 data->filename, data->lineno, err);
c1795bb0 1436 free(err);
1ba111d1 1437 emit_line(data->o->file, set, reset, line, 1);
8f8841e9 1438 ws_check_emit(line + 1, len - 1, data->ws_rule,
1ba111d1 1439 data->o->file, set, reset, ws);
877f23cc 1440 } else if (line[0] == ' ') {
88246898 1441 data->lineno++;
877f23cc 1442 } else if (line[0] == '@') {
88246898
JS
1443 char *plus = strchr(line, '+');
1444 if (plus)
0ef617f4 1445 data->lineno = strtol(plus, NULL, 10) - 1;
88246898
JS
1446 else
1447 die("invalid diff");
1448 }
1449}
1450
0660626c
JH
1451static unsigned char *deflate_it(char *data,
1452 unsigned long size,
1453 unsigned long *result_size)
051308f6 1454{
0660626c
JH
1455 int bound;
1456 unsigned char *deflated;
1457 z_stream stream;
1458
1459 memset(&stream, 0, sizeof(stream));
12f6c308 1460 deflateInit(&stream, zlib_compression_level);
0660626c
JH
1461 bound = deflateBound(&stream, size);
1462 deflated = xmalloc(bound);
1463 stream.next_out = deflated;
1464 stream.avail_out = bound;
1465
1466 stream.next_in = (unsigned char *)data;
1467 stream.avail_in = size;
1468 while (deflate(&stream, Z_FINISH) == Z_OK)
1469 ; /* nothing */
1470 deflateEnd(&stream);
1471 *result_size = stream.total_out;
1472 return deflated;
051308f6
JH
1473}
1474
c0c77734 1475static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two)
051308f6 1476{
0660626c
JH
1477 void *cp;
1478 void *delta;
1479 void *deflated;
1480 void *data;
1481 unsigned long orig_size;
1482 unsigned long delta_size;
1483 unsigned long deflate_size;
1484 unsigned long data_size;
051308f6 1485
0660626c
JH
1486 /* We could do deflated delta, or we could do just deflated two,
1487 * whichever is smaller.
051308f6 1488 */
0660626c
JH
1489 delta = NULL;
1490 deflated = deflate_it(two->ptr, two->size, &deflate_size);
1491 if (one->size && two->size) {
1492 delta = diff_delta(one->ptr, one->size,
1493 two->ptr, two->size,
1494 &delta_size, deflate_size);
1495 if (delta) {
1496 void *to_free = delta;
1497 orig_size = delta_size;
1498 delta = deflate_it(delta, delta_size, &delta_size);
1499 free(to_free);
051308f6
JH
1500 }
1501 }
051308f6 1502
0660626c 1503 if (delta && delta_size < deflate_size) {
c0c77734 1504 fprintf(file, "delta %lu\n", orig_size);
0660626c
JH
1505 free(deflated);
1506 data = delta;
1507 data_size = delta_size;
1508 }
1509 else {
c0c77734 1510 fprintf(file, "literal %lu\n", two->size);
0660626c
JH
1511 free(delta);
1512 data = deflated;
1513 data_size = deflate_size;
1514 }
051308f6 1515
0660626c
JH
1516 /* emit data encoded in base85 */
1517 cp = data;
1518 while (data_size) {
1519 int bytes = (52 < data_size) ? 52 : data_size;
051308f6 1520 char line[70];
0660626c 1521 data_size -= bytes;
051308f6
JH
1522 if (bytes <= 26)
1523 line[0] = bytes + 'A' - 1;
1524 else
1525 line[0] = bytes - 26 + 'a' - 1;
1526 encode_85(line + 1, cp, bytes);
1d7f171c 1527 cp = (char *) cp + bytes;
c0c77734
DB
1528 fputs(line, file);
1529 fputc('\n', file);
051308f6 1530 }
c0c77734 1531 fprintf(file, "\n");
0660626c 1532 free(data);
051308f6
JH
1533}
1534
c0c77734 1535static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two)
d4c452f0 1536{
c0c77734
DB
1537 fprintf(file, "GIT binary patch\n");
1538 emit_binary_diff_body(file, one, two);
1539 emit_binary_diff_body(file, two, one);
d4c452f0
JH
1540}
1541
72cf4841 1542static void diff_filespec_load_driver(struct diff_filespec *one)
6973dcae 1543{
122aa6f9
JK
1544 if (!one->driver)
1545 one->driver = userdiff_find_by_path(one->path);
1546 if (!one->driver)
1547 one->driver = userdiff_find_by_name("default");
29a3eefd
JH
1548}
1549
1550int diff_filespec_is_binary(struct diff_filespec *one)
1551{
122aa6f9
JK
1552 if (one->is_binary == -1) {
1553 diff_filespec_load_driver(one);
1554 if (one->driver->binary != -1)
1555 one->is_binary = one->driver->binary;
1556 else {
1557 if (!one->data && DIFF_FILE_VALID(one))
1558 diff_populate_filespec(one, 0);
1559 if (one->data)
1560 one->is_binary = buffer_is_binary(one->data,
1561 one->size);
1562 if (one->is_binary == -1)
1563 one->is_binary = 0;
1564 }
1565 }
29a3eefd 1566 return one->is_binary;
6973dcae
JH
1567}
1568
be58e70d 1569static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
f258475a 1570{
122aa6f9
JK
1571 diff_filespec_load_driver(one);
1572 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
f258475a
JH
1573}
1574
80c49c3d
TR
1575static const char *userdiff_word_regex(struct diff_filespec *one)
1576{
1577 diff_filespec_load_driver(one);
1578 return one->driver->word_regex;
1579}
1580
a5a818ee
JH
1581void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
1582{
1583 if (!options->a_prefix)
1584 options->a_prefix = a;
1585 if (!options->b_prefix)
1586 options->b_prefix = b;
1587}
1588
04427ac8
JK
1589static const char *get_textconv(struct diff_filespec *one)
1590{
1591 if (!DIFF_FILE_VALID(one))
1592 return NULL;
2675773a
JK
1593 if (!S_ISREG(one->mode))
1594 return NULL;
04427ac8
JK
1595 diff_filespec_load_driver(one);
1596 return one->driver->textconv;
1597}
1598
6973dcae
JH
1599static void builtin_diff(const char *name_a,
1600 const char *name_b,
1601 struct diff_filespec *one,
1602 struct diff_filespec *two,
1603 const char *xfrm_msg,
051308f6 1604 struct diff_options *o,
6973dcae
JH
1605 int complete_rewrite)
1606{
1607 mmfile_t mf1, mf2;
1608 const char *lbl[2];
1609 char *a_one, *b_two;
8f67f8ae
PH
1610 const char *set = diff_get_color_opt(o, DIFF_METAINFO);
1611 const char *reset = diff_get_color_opt(o, DIFF_RESET);
a5a818ee 1612 const char *a_prefix, *b_prefix;
c7534ef4 1613 const char *textconv_one = NULL, *textconv_two = NULL;
3e97c7c6 1614 struct strbuf header = STRBUF_INIT;
a5a818ee 1615
752c0c24
JS
1616 if (DIFF_OPT_TST(o, SUBMODULE_LOG) &&
1617 (!one->mode || S_ISGITLINK(one->mode)) &&
1618 (!two->mode || S_ISGITLINK(two->mode))) {
1619 const char *del = diff_get_color_opt(o, DIFF_FILE_OLD);
1620 const char *add = diff_get_color_opt(o, DIFF_FILE_NEW);
1621 show_submodule_summary(o->file, one ? one->path : two->path,
721ceec1 1622 one->sha1, two->sha1, two->dirty_submodule,
752c0c24
JS
1623 del, add, reset);
1624 return;
1625 }
1626
3aa1f7ca
JK
1627 if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
1628 textconv_one = get_textconv(one);
1629 textconv_two = get_textconv(two);
1630 }
1631
a5a818ee
JH
1632 diff_set_mnemonic_prefix(o, "a/", "b/");
1633 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
1634 a_prefix = o->b_prefix;
1635 b_prefix = o->a_prefix;
1636 } else {
1637 a_prefix = o->a_prefix;
1638 b_prefix = o->b_prefix;
1639 }
6973dcae 1640
71b989e7
LT
1641 /* Never use a non-valid filename anywhere if at all possible */
1642 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
1643 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
1644
a5a818ee
JH
1645 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
1646 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
6973dcae
JH
1647 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1648 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3e97c7c6 1649 strbuf_addf(&header, "%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
6973dcae
JH
1650 if (lbl[0][0] == '/') {
1651 /* /dev/null */
3e97c7c6 1652 strbuf_addf(&header, "%snew file mode %06o%s\n", set, two->mode, reset);
50f575fc 1653 if (xfrm_msg && xfrm_msg[0])
3e97c7c6 1654 strbuf_addf(&header, "%s%s%s\n", set, xfrm_msg, reset);
6973dcae
JH
1655 }
1656 else if (lbl[1][0] == '/') {
3e97c7c6 1657 strbuf_addf(&header, "%sdeleted file mode %06o%s\n", set, one->mode, reset);
50f575fc 1658 if (xfrm_msg && xfrm_msg[0])
3e97c7c6 1659 strbuf_addf(&header, "%s%s%s\n", set, xfrm_msg, reset);
6973dcae
JH
1660 }
1661 else {
1662 if (one->mode != two->mode) {
3e97c7c6
GB
1663 strbuf_addf(&header, "%sold mode %06o%s\n", set, one->mode, reset);
1664 strbuf_addf(&header, "%snew mode %06o%s\n", set, two->mode, reset);
cd112cef 1665 }
50f575fc 1666 if (xfrm_msg && xfrm_msg[0])
3e97c7c6
GB
1667 strbuf_addf(&header, "%s%s%s\n", set, xfrm_msg, reset);
1668
6973dcae
JH
1669 /*
1670 * we do not run diff between different kind
1671 * of objects.
1672 */
1673 if ((one->mode ^ two->mode) & S_IFMT)
1674 goto free_ab_and_return;
0c01857d 1675 if (complete_rewrite &&
3aa1f7ca
JK
1676 (textconv_one || !diff_filespec_is_binary(one)) &&
1677 (textconv_two || !diff_filespec_is_binary(two))) {
3e97c7c6
GB
1678 fprintf(o->file, "%s", header.buf);
1679 strbuf_reset(&header);
3aa1f7ca
JK
1680 emit_rewrite_diff(name_a, name_b, one, two,
1681 textconv_one, textconv_two, o);
34a5e1a2 1682 o->found_changes = 1;
6973dcae
JH
1683 goto free_ab_and_return;
1684 }
1685 }
1686
1687 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1688 die("unable to read files to diff");
1689
8f67f8ae 1690 if (!DIFF_OPT_TST(o, TEXT) &&
04427ac8
JK
1691 ( (diff_filespec_is_binary(one) && !textconv_one) ||
1692 (diff_filespec_is_binary(two) && !textconv_two) )) {
0660626c
JH
1693 /* Quite common confusing case */
1694 if (mf1.size == mf2.size &&
1695 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1696 goto free_ab_and_return;
3e97c7c6
GB
1697 fprintf(o->file, "%s", header.buf);
1698 strbuf_reset(&header);
8f67f8ae 1699 if (DIFF_OPT_TST(o, BINARY))
c0c77734 1700 emit_binary_diff(o->file, &mf1, &mf2);
051308f6 1701 else
c0c77734
DB
1702 fprintf(o->file, "Binary files %s and %s differ\n",
1703 lbl[0], lbl[1]);
34a5e1a2 1704 o->found_changes = 1;
051308f6 1705 }
6973dcae
JH
1706 else {
1707 /* Crazy xdl interfaces.. */
1708 const char *diffopts = getenv("GIT_DIFF_OPTS");
1709 xpparam_t xpp;
1710 xdemitconf_t xecfg;
1711 xdemitcb_t ecb;
1712 struct emit_callback ecbdata;
be58e70d 1713 const struct userdiff_funcname *pe;
f258475a 1714
3e97c7c6
GB
1715 if (!DIFF_XDL_TST(o, WHITESPACE_FLAGS)) {
1716 fprintf(o->file, "%s", header.buf);
1717 strbuf_reset(&header);
1718 }
1719
04427ac8
JK
1720 if (textconv_one) {
1721 size_t size;
1722 mf1.ptr = run_textconv(textconv_one, one, &size);
1723 if (!mf1.ptr)
1724 die("unable to read files to diff");
1725 mf1.size = size;
1726 }
1727 if (textconv_two) {
1728 size_t size;
1729 mf2.ptr = run_textconv(textconv_two, two, &size);
1730 if (!mf2.ptr)
1731 die("unable to read files to diff");
1732 mf2.size = size;
1733 }
1734
45e7ca0f
BC
1735 pe = diff_funcname_pattern(one);
1736 if (!pe)
1737 pe = diff_funcname_pattern(two);
6973dcae 1738
9ccd0a88 1739 memset(&xpp, 0, sizeof(xpp));
30b25010 1740 memset(&xecfg, 0, sizeof(xecfg));
cd112cef 1741 memset(&ecbdata, 0, sizeof(ecbdata));
6973dcae 1742 ecbdata.label_path = lbl;
8f67f8ae 1743 ecbdata.color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
34a5e1a2 1744 ecbdata.found_changesp = &o->found_changes;
cf1b7869 1745 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
690ed843 1746 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
d68fe26f 1747 check_blank_at_eof(&mf1, &mf2, &ecbdata);
c0c77734 1748 ecbdata.file = o->file;
3e97c7c6 1749 ecbdata.header = header.len ? &header : NULL;
0d21efa5 1750 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
ee1e5412 1751 xecfg.ctxlen = o->context;
6d0e674a 1752 xecfg.interhunkctxlen = o->interhunkcontext;
6973dcae 1753 xecfg.flags = XDL_EMIT_FUNCNAMES;
45e7ca0f 1754 if (pe)
a013585b 1755 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
6973dcae
JH
1756 if (!diffopts)
1757 ;
cc44c765 1758 else if (!prefixcmp(diffopts, "--unified="))
6973dcae 1759 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
cc44c765 1760 else if (!prefixcmp(diffopts, "-u"))
6973dcae 1761 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
c0c77734 1762 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS)) {
f59a59e2
JS
1763 ecbdata.diff_words =
1764 xcalloc(1, sizeof(struct diff_words_data));
c0c77734 1765 ecbdata.diff_words->file = o->file;
80c49c3d
TR
1766 if (!o->word_regex)
1767 o->word_regex = userdiff_word_regex(one);
1768 if (!o->word_regex)
1769 o->word_regex = userdiff_word_regex(two);
98a4d87b
BSSJ
1770 if (!o->word_regex)
1771 o->word_regex = diff_word_regex_cfg;
2b6a5417
JS
1772 if (o->word_regex) {
1773 ecbdata.diff_words->word_regex = (regex_t *)
1774 xmalloc(sizeof(regex_t));
1775 if (regcomp(ecbdata.diff_words->word_regex,
bf82940d
TR
1776 o->word_regex,
1777 REG_EXTENDED | REG_NEWLINE))
2b6a5417
JS
1778 die ("Invalid regular expression: %s",
1779 o->word_regex);
1780 }
c0c77734 1781 }
8a3f524b
JH
1782 xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
1783 &xpp, &xecfg, &ecb);
8f67f8ae 1784 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS))
f59a59e2 1785 free_diff_words_data(&ecbdata);
04427ac8
JK
1786 if (textconv_one)
1787 free(mf1.ptr);
1788 if (textconv_two)
1789 free(mf2.ptr);
8cfe5f1c 1790 xdiff_clear_find_func(&xecfg);
6973dcae
JH
1791 }
1792
1793 free_ab_and_return:
3e97c7c6 1794 strbuf_release(&header);
fc3abdf5
JH
1795 diff_free_filespec_data(one);
1796 diff_free_filespec_data(two);
6973dcae
JH
1797 free(a_one);
1798 free(b_two);
1799 return;
1800}
1801
1802static void builtin_diffstat(const char *name_a, const char *name_b,
1803 struct diff_filespec *one,
1804 struct diff_filespec *two,
710158e3 1805 struct diffstat_t *diffstat,
0d21efa5 1806 struct diff_options *o,
710158e3 1807 int complete_rewrite)
6973dcae
JH
1808{
1809 mmfile_t mf1, mf2;
1810 struct diffstat_file *data;
1811
1812 data = diffstat_add(diffstat, name_a, name_b);
1813
1814 if (!one || !two) {
1815 data->is_unmerged = 1;
1816 return;
1817 }
710158e3
JH
1818 if (complete_rewrite) {
1819 diff_populate_filespec(one, 0);
1820 diff_populate_filespec(two, 0);
1821 data->deleted = count_lines(one->data, one->size);
1822 data->added = count_lines(two->data, two->size);
fc3abdf5 1823 goto free_and_return;
710158e3 1824 }
6973dcae
JH
1825 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1826 die("unable to read files to diff");
1827
29a3eefd 1828 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
6973dcae 1829 data->is_binary = 1;
b1882587
AP
1830 data->added = mf2.size;
1831 data->deleted = mf1.size;
1832 } else {
6973dcae
JH
1833 /* Crazy xdl interfaces.. */
1834 xpparam_t xpp;
1835 xdemitconf_t xecfg;
1836 xdemitcb_t ecb;
1837
9ccd0a88 1838 memset(&xpp, 0, sizeof(xpp));
30b25010 1839 memset(&xecfg, 0, sizeof(xecfg));
0d21efa5 1840 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
8a3f524b
JH
1841 xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
1842 &xpp, &xecfg, &ecb);
6973dcae 1843 }
fc3abdf5
JH
1844
1845 free_and_return:
1846 diff_free_filespec_data(one);
1847 diff_free_filespec_data(two);
6973dcae
JH
1848}
1849
88246898 1850static void builtin_checkdiff(const char *name_a, const char *name_b,
cd676a51 1851 const char *attr_path,
5ff10dd6
JH
1852 struct diff_filespec *one,
1853 struct diff_filespec *two,
1854 struct diff_options *o)
88246898
JS
1855{
1856 mmfile_t mf1, mf2;
1857 struct checkdiff_t data;
1858
1859 if (!two)
1860 return;
1861
1862 memset(&data, 0, sizeof(data));
88246898
JS
1863 data.filename = name_b ? name_b : name_a;
1864 data.lineno = 0;
1ba111d1 1865 data.o = o;
cd676a51 1866 data.ws_rule = whitespace_rule(attr_path);
a757c646 1867 data.conflict_marker_size = ll_merge_marker_size(attr_path);
88246898
JS
1868
1869 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1870 die("unable to read files to diff");
1871
5ff10dd6
JH
1872 /*
1873 * All the other codepaths check both sides, but not checking
1874 * the "old" side here is deliberate. We are checking the newly
1875 * introduced changes, and as long as the "new" side is text, we
1876 * can and should check what it introduces.
1877 */
29a3eefd 1878 if (diff_filespec_is_binary(two))
fc3abdf5 1879 goto free_and_return;
88246898
JS
1880 else {
1881 /* Crazy xdl interfaces.. */
1882 xpparam_t xpp;
1883 xdemitconf_t xecfg;
1884 xdemitcb_t ecb;
1885
9ccd0a88 1886 memset(&xpp, 0, sizeof(xpp));
30b25010 1887 memset(&xecfg, 0, sizeof(xecfg));
c35539eb 1888 xecfg.ctxlen = 1; /* at least one context line */
88246898 1889 xpp.flags = XDF_NEED_MINIMAL;
8a3f524b
JH
1890 xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
1891 &xpp, &xecfg, &ecb);
877f23cc 1892
467babf8 1893 if (data.ws_rule & WS_BLANK_AT_EOF) {
d68fe26f
JH
1894 struct emit_callback ecbdata;
1895 int blank_at_eof;
1896
1897 ecbdata.ws_rule = data.ws_rule;
1898 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1899 blank_at_eof = ecbdata.blank_at_eof_in_preimage;
1900
467babf8
JH
1901 if (blank_at_eof) {
1902 static char *err;
1903 if (!err)
1904 err = whitespace_error_string(WS_BLANK_AT_EOF);
1905 fprintf(o->file, "%s:%d: %s.\n",
1906 data.filename, blank_at_eof, err);
1907 data.status = 1; /* report errors */
1908 }
877f23cc 1909 }
88246898 1910 }
fc3abdf5
JH
1911 free_and_return:
1912 diff_free_filespec_data(one);
1913 diff_free_filespec_data(two);
62c64895
WC
1914 if (data.status)
1915 DIFF_OPT_SET(o, CHECK_FAILED);
88246898
JS
1916}
1917
6973dcae
JH
1918struct diff_filespec *alloc_filespec(const char *path)
1919{
1920 int namelen = strlen(path);
1921 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1922
1923 memset(spec, 0, sizeof(*spec));
1924 spec->path = (char *)(spec + 1);
1925 memcpy(spec->path, path, namelen+1);
9fb88419 1926 spec->count = 1;
122aa6f9 1927 spec->is_binary = -1;
6973dcae
JH
1928 return spec;
1929}
1930
9fb88419
LT
1931void free_filespec(struct diff_filespec *spec)
1932{
1933 if (!--spec->count) {
1934 diff_free_filespec_data(spec);
1935 free(spec);
1936 }
1937}
1938
6973dcae
JH
1939void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1940 unsigned short mode)
1941{
1942 if (mode) {
1943 spec->mode = canon_mode(mode);
e702496e 1944 hashcpy(spec->sha1, sha1);
0bef57ee 1945 spec->sha1_valid = !is_null_sha1(sha1);
6973dcae
JH
1946 }
1947}
1948
1949/*
5adf317b 1950 * Given a name and sha1 pair, if the index tells us the file in
6973dcae
JH
1951 * the work tree has that object contents, return true, so that
1952 * prepare_temp_file() does not have to inflate and extract.
1953 */
1510fea7 1954static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
6973dcae
JH
1955{
1956 struct cache_entry *ce;
1957 struct stat st;
1958 int pos, len;
1959
150115ad
JH
1960 /*
1961 * We do not read the cache ourselves here, because the
6973dcae
JH
1962 * benchmark with my previous version that always reads cache
1963 * shows that it makes things worse for diff-tree comparing
1964 * two linux-2.6 kernel trees in an already checked out work
1965 * tree. This is because most diff-tree comparisons deal with
1966 * only a small number of files, while reading the cache is
1967 * expensive for a large project, and its cost outweighs the
1968 * savings we get by not inflating the object to a temporary
1969 * file. Practically, this code only helps when we are used
1970 * by diff-cache --cached, which does read the cache before
1971 * calling us.
1972 */
1973 if (!active_cache)
1974 return 0;
1975
1510fea7
SP
1976 /* We want to avoid the working directory if our caller
1977 * doesn't need the data in a normal file, this system
1978 * is rather slow with its stat/open/mmap/close syscalls,
1979 * and the object is contained in a pack file. The pack
1980 * is probably already open and will be faster to obtain
1981 * the data through than the working directory. Loose
1982 * objects however would tend to be slower as they need
1983 * to be individually opened and inflated.
1984 */
cd673c1f 1985 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1))
1510fea7
SP
1986 return 0;
1987
6973dcae
JH
1988 len = strlen(name);
1989 pos = cache_name_pos(name, len);
1990 if (pos < 0)
1991 return 0;
1992 ce = active_cache[pos];
eadb5831
JH
1993
1994 /*
1995 * This is not the sha1 we are looking for, or
1996 * unreusable because it is not a regular file.
1997 */
1998 if (hashcmp(sha1, ce->sha1) || !S_ISREG(ce->ce_mode))
6973dcae 1999 return 0;
eadb5831 2000
150115ad
JH
2001 /*
2002 * If ce is marked as "assume unchanged", there is no
2003 * guarantee that work tree matches what we are looking for.
2004 */
b4d1690d 2005 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
150115ad
JH
2006 return 0;
2007
eadb5831
JH
2008 /*
2009 * If ce matches the file in the work tree, we can reuse it.
6973dcae 2010 */
eadb5831
JH
2011 if (ce_uptodate(ce) ||
2012 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
2013 return 1;
2014
2015 return 0;
6973dcae
JH
2016}
2017
3afaa72d
JH
2018static int populate_from_stdin(struct diff_filespec *s)
2019{
f285a2d7 2020 struct strbuf buf = STRBUF_INIT;
c32f749f 2021 size_t size = 0;
af6eb822 2022
f1696ee3 2023 if (strbuf_read(&buf, 0, 0) < 0)
af6eb822 2024 return error("error while reading from stdin %s",
3afaa72d 2025 strerror(errno));
af6eb822 2026
3afaa72d 2027 s->should_munmap = 0;
c32f749f
RS
2028 s->data = strbuf_detach(&buf, &size);
2029 s->size = size;
3afaa72d
JH
2030 s->should_free = 1;
2031 return 0;
2032}
2033
04786756
LT
2034static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
2035{
2036 int len;
8e08b419
JH
2037 char *data = xmalloc(100), *dirty = "";
2038
2039 /* Are we looking at the work tree? */
85adbf2f 2040 if (s->dirty_submodule)
8e08b419
JH
2041 dirty = "-dirty";
2042
04786756 2043 len = snprintf(data, 100,
8e08b419 2044 "Subproject commit %s%s\n", sha1_to_hex(s->sha1), dirty);
04786756
LT
2045 s->data = data;
2046 s->size = len;
2047 s->should_free = 1;
2048 if (size_only) {
2049 s->data = NULL;
2050 free(data);
2051 }
2052 return 0;
2053}
2054
6973dcae
JH
2055/*
2056 * While doing rename detection and pickaxe operation, we may need to
2057 * grab the data for the blob (or file) for our own in-core comparison.
2058 * diff_filespec has data and size fields for this purpose.
2059 */
2060int diff_populate_filespec(struct diff_filespec *s, int size_only)
2061{
2062 int err = 0;
2063 if (!DIFF_FILE_VALID(s))
2064 die("internal error: asking to populate invalid file.");
2065 if (S_ISDIR(s->mode))
2066 return -1;
2067
6973dcae 2068 if (s->data)
fc3abdf5 2069 return 0;
04786756 2070
6e0b8ed6
JH
2071 if (size_only && 0 < s->size)
2072 return 0;
2073
302b9282 2074 if (S_ISGITLINK(s->mode))
04786756
LT
2075 return diff_populate_gitlink(s, size_only);
2076
6973dcae 2077 if (!s->sha1_valid ||
1510fea7 2078 reuse_worktree_file(s->path, s->sha1, 0)) {
f285a2d7 2079 struct strbuf buf = STRBUF_INIT;
6973dcae
JH
2080 struct stat st;
2081 int fd;
6c510bee 2082
3afaa72d
JH
2083 if (!strcmp(s->path, "-"))
2084 return populate_from_stdin(s);
2085
6973dcae
JH
2086 if (lstat(s->path, &st) < 0) {
2087 if (errno == ENOENT) {
2088 err_empty:
2089 err = -1;
2090 empty:
d2543b8e 2091 s->data = (char *)"";
6973dcae
JH
2092 s->size = 0;
2093 return err;
2094 }
2095 }
dc49cd76 2096 s->size = xsize_t(st.st_size);
6973dcae
JH
2097 if (!s->size)
2098 goto empty;
6973dcae 2099 if (S_ISLNK(st.st_mode)) {
cf219d8c
LT
2100 struct strbuf sb = STRBUF_INIT;
2101
2102 if (strbuf_readlink(&sb, s->path, s->size))
6973dcae 2103 goto err_empty;
0956a6db
RS
2104 s->size = sb.len;
2105 s->data = strbuf_detach(&sb, NULL);
cf219d8c 2106 s->should_free = 1;
6973dcae
JH
2107 return 0;
2108 }
cf219d8c
LT
2109 if (size_only)
2110 return 0;
6973dcae
JH
2111 fd = open(s->path, O_RDONLY);
2112 if (fd < 0)
2113 goto err_empty;
c4712e45 2114 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
6973dcae 2115 close(fd);
6973dcae 2116 s->should_munmap = 1;
6c510bee
LT
2117
2118 /*
2119 * Convert from working tree format to canonical git format
2120 */
21e5ad50 2121 if (convert_to_git(s->path, s->data, s->size, &buf, safe_crlf)) {
c32f749f 2122 size_t size = 0;
6c510bee
LT
2123 munmap(s->data, s->size);
2124 s->should_munmap = 0;
c32f749f
RS
2125 s->data = strbuf_detach(&buf, &size);
2126 s->size = size;
6c510bee
LT
2127 s->should_free = 1;
2128 }
6973dcae
JH
2129 }
2130 else {
21666f1a 2131 enum object_type type;
6e0b8ed6 2132 if (size_only)
21666f1a 2133 type = sha1_object_info(s->sha1, &s->size);
6973dcae 2134 else {
21666f1a 2135 s->data = read_sha1_file(s->sha1, &type, &s->size);
6973dcae
JH
2136 s->should_free = 1;
2137 }
2138 }
2139 return 0;
2140}
2141
8ae92e63 2142void diff_free_filespec_blob(struct diff_filespec *s)
6973dcae
JH
2143{
2144 if (s->should_free)
2145 free(s->data);
2146 else if (s->should_munmap)
2147 munmap(s->data, s->size);
fc3abdf5
JH
2148
2149 if (s->should_free || s->should_munmap) {
2150 s->should_free = s->should_munmap = 0;
2151 s->data = NULL;
2152 }
eede7b7d
JK
2153}
2154
2155void diff_free_filespec_data(struct diff_filespec *s)
2156{
8ae92e63 2157 diff_free_filespec_blob(s);
6973dcae
JH
2158 free(s->cnt_data);
2159 s->cnt_data = NULL;
2160}
2161
4e218f54 2162static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
6973dcae
JH
2163 void *blob,
2164 unsigned long size,
2165 const unsigned char *sha1,
2166 int mode)
2167{
2168 int fd;
4e218f54 2169 struct strbuf buf = STRBUF_INIT;
003b33a8
DA
2170 struct strbuf template = STRBUF_INIT;
2171 char *path_dup = xstrdup(path);
2172 const char *base = basename(path_dup);
6973dcae 2173
003b33a8
DA
2174 /* Generate "XXXXXX_basename.ext" */
2175 strbuf_addstr(&template, "XXXXXX_");
2176 strbuf_addstr(&template, base);
2177
2178 fd = git_mkstemps(temp->tmp_path, PATH_MAX, template.buf,
2179 strlen(base) + 1);
6973dcae 2180 if (fd < 0)
d824cbba 2181 die_errno("unable to create temp-file");
4e218f54
JS
2182 if (convert_to_working_tree(path,
2183 (const char *)blob, (size_t)size, &buf)) {
2184 blob = buf.buf;
2185 size = buf.len;
2186 }
93822c22 2187 if (write_in_full(fd, blob, size) != size)
0721c314 2188 die_errno("unable to write temp-file");
6973dcae
JH
2189 close(fd);
2190 temp->name = temp->tmp_path;
2191 strcpy(temp->hex, sha1_to_hex(sha1));
2192 temp->hex[40] = 0;
2193 sprintf(temp->mode, "%06o", mode);
4e218f54 2194 strbuf_release(&buf);
003b33a8
DA
2195 strbuf_release(&template);
2196 free(path_dup);
6973dcae
JH
2197}
2198
479b0ae8
JK
2199static struct diff_tempfile *prepare_temp_file(const char *name,
2200 struct diff_filespec *one)
6973dcae 2201{
479b0ae8
JK
2202 struct diff_tempfile *temp = claim_diff_tempfile();
2203
6973dcae
JH
2204 if (!DIFF_FILE_VALID(one)) {
2205 not_a_valid_file:
2206 /* A '-' entry produces this for file-2, and
2207 * a '+' entry produces this for file-1.
2208 */
2209 temp->name = "/dev/null";
2210 strcpy(temp->hex, ".");
2211 strcpy(temp->mode, ".");
479b0ae8
JK
2212 return temp;
2213 }
2214
2215 if (!remove_tempfile_installed) {
2216 atexit(remove_tempfile);
57b235a4 2217 sigchain_push_common(remove_tempfile_on_signal);
479b0ae8 2218 remove_tempfile_installed = 1;
6973dcae
JH
2219 }
2220
2221 if (!one->sha1_valid ||
1510fea7 2222 reuse_worktree_file(name, one->sha1, 1)) {
6973dcae
JH
2223 struct stat st;
2224 if (lstat(name, &st) < 0) {
2225 if (errno == ENOENT)
2226 goto not_a_valid_file;
d824cbba 2227 die_errno("stat(%s)", name);
6973dcae
JH
2228 }
2229 if (S_ISLNK(st.st_mode)) {
3cd7388d
JK
2230 struct strbuf sb = STRBUF_INIT;
2231 if (strbuf_readlink(&sb, name, st.st_size) < 0)
0721c314 2232 die_errno("readlink(%s)", name);
3cd7388d 2233 prep_temp_blob(name, temp, sb.buf, sb.len,
6973dcae
JH
2234 (one->sha1_valid ?
2235 one->sha1 : null_sha1),
2236 (one->sha1_valid ?
2237 one->mode : S_IFLNK));
3cd7388d 2238 strbuf_release(&sb);
6973dcae
JH
2239 }
2240 else {
2241 /* we can borrow from the file in the work tree */
2242 temp->name = name;
2243 if (!one->sha1_valid)
2244 strcpy(temp->hex, sha1_to_hex(null_sha1));
2245 else
2246 strcpy(temp->hex, sha1_to_hex(one->sha1));
2247 /* Even though we may sometimes borrow the
2248 * contents from the work tree, we always want
2249 * one->mode. mode is trustworthy even when
2250 * !(one->sha1_valid), as long as
2251 * DIFF_FILE_VALID(one).
2252 */
2253 sprintf(temp->mode, "%06o", one->mode);
2254 }
479b0ae8 2255 return temp;
6973dcae
JH
2256 }
2257 else {
2258 if (diff_populate_filespec(one, 0))
2259 die("cannot read data blob for %s", one->path);
4e218f54 2260 prep_temp_blob(name, temp, one->data, one->size,
6973dcae
JH
2261 one->sha1, one->mode);
2262 }
479b0ae8 2263 return temp;
6973dcae
JH
2264}
2265
6973dcae
JH
2266/* An external diff command takes:
2267 *
2268 * diff-cmd name infile1 infile1-sha1 infile1-mode \
2269 * infile2 infile2-sha1 infile2-mode [ rename-to ]
2270 *
2271 */
2272static void run_external_diff(const char *pgm,
2273 const char *name,
2274 const char *other,
2275 struct diff_filespec *one,
2276 struct diff_filespec *two,
2277 const char *xfrm_msg,
2278 int complete_rewrite)
2279{
2280 const char *spawn_arg[10];
6973dcae 2281 int retval;
6973dcae
JH
2282 const char **arg = &spawn_arg[0];
2283
6973dcae 2284 if (one && two) {
479b0ae8
JK
2285 struct diff_tempfile *temp_one, *temp_two;
2286 const char *othername = (other ? other : name);
2287 temp_one = prepare_temp_file(name, one);
2288 temp_two = prepare_temp_file(othername, two);
6973dcae
JH
2289 *arg++ = pgm;
2290 *arg++ = name;
479b0ae8
JK
2291 *arg++ = temp_one->name;
2292 *arg++ = temp_one->hex;
2293 *arg++ = temp_one->mode;
2294 *arg++ = temp_two->name;
2295 *arg++ = temp_two->hex;
2296 *arg++ = temp_two->mode;
6973dcae
JH
2297 if (other) {
2298 *arg++ = other;
2299 *arg++ = xfrm_msg;
2300 }
2301 } else {
2302 *arg++ = pgm;
2303 *arg++ = name;
2304 }
2305 *arg = NULL;
d5535ec7 2306 fflush(NULL);
7ed7fac4 2307 retval = run_command_v_opt(spawn_arg, RUN_USING_SHELL);
6973dcae
JH
2308 remove_tempfile();
2309 if (retval) {
2310 fprintf(stderr, "external diff died, stopping at %s.\n", name);
2311 exit(1);
2312 }
2313}
2314
b67b9612
JH
2315static int similarity_index(struct diff_filepair *p)
2316{
2317 return p->score * 100 / MAX_SCORE;
2318}
2319
2320static void fill_metainfo(struct strbuf *msg,
2321 const char *name,
2322 const char *other,
2323 struct diff_filespec *one,
2324 struct diff_filespec *two,
2325 struct diff_options *o,
2326 struct diff_filepair *p)
2327{
2328 strbuf_init(msg, PATH_MAX * 2 + 300);
2329 switch (p->status) {
2330 case DIFF_STATUS_COPIED:
2331 strbuf_addf(msg, "similarity index %d%%", similarity_index(p));
2332 strbuf_addstr(msg, "\ncopy from ");
2333 quote_c_style(name, msg, NULL, 0);
2334 strbuf_addstr(msg, "\ncopy to ");
2335 quote_c_style(other, msg, NULL, 0);
2336 strbuf_addch(msg, '\n');
2337 break;
2338 case DIFF_STATUS_RENAMED:
2339 strbuf_addf(msg, "similarity index %d%%", similarity_index(p));
2340 strbuf_addstr(msg, "\nrename from ");
2341 quote_c_style(name, msg, NULL, 0);
2342 strbuf_addstr(msg, "\nrename to ");
2343 quote_c_style(other, msg, NULL, 0);
2344 strbuf_addch(msg, '\n');
2345 break;
2346 case DIFF_STATUS_MODIFIED:
2347 if (p->score) {
2348 strbuf_addf(msg, "dissimilarity index %d%%\n",
2349 similarity_index(p));
2350 break;
2351 }
2352 /* fallthru */
2353 default:
2354 /* nothing */
2355 ;
2356 }
2357 if (one && two && hashcmp(one->sha1, two->sha1)) {
2358 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
2359
2360 if (DIFF_OPT_TST(o, BINARY)) {
2361 mmfile_t mf;
2362 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
2363 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
2364 abbrev = 40;
2365 }
2366 strbuf_addf(msg, "index %.*s..%.*s",
2367 abbrev, sha1_to_hex(one->sha1),
2368 abbrev, sha1_to_hex(two->sha1));
2369 if (one->mode == two->mode)
2370 strbuf_addf(msg, " %06o", one->mode);
2371 strbuf_addch(msg, '\n');
2372 }
2373 if (msg->len)
2374 strbuf_setlen(msg, msg->len - 1);
2375}
2376
6973dcae
JH
2377static void run_diff_cmd(const char *pgm,
2378 const char *name,
2379 const char *other,
cd676a51 2380 const char *attr_path,
6973dcae
JH
2381 struct diff_filespec *one,
2382 struct diff_filespec *two,
b67b9612 2383 struct strbuf *msg,
051308f6 2384 struct diff_options *o,
b67b9612 2385 struct diff_filepair *p)
6973dcae 2386{
b67b9612
JH
2387 const char *xfrm_msg = NULL;
2388 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
2389
2390 if (msg) {
2391 fill_metainfo(msg, name, other, one, two, o, p);
2392 xfrm_msg = msg->len ? msg->buf : NULL;
2393 }
2394
8f67f8ae 2395 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
f1af60bd
JH
2396 pgm = NULL;
2397 else {
be58e70d
JK
2398 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
2399 if (drv && drv->external)
2400 pgm = drv->external;
f1af60bd
JH
2401 }
2402
6973dcae
JH
2403 if (pgm) {
2404 run_external_diff(pgm, name, other, one, two, xfrm_msg,
2405 complete_rewrite);
2406 return;
2407 }
2408 if (one && two)
2409 builtin_diff(name, other ? other : name,
051308f6 2410 one, two, xfrm_msg, o, complete_rewrite);
6973dcae 2411 else
c0c77734 2412 fprintf(o->file, "* Unmerged path %s\n", name);
6973dcae
JH
2413}
2414
2415static void diff_fill_sha1_info(struct diff_filespec *one)
2416{
2417 if (DIFF_FILE_VALID(one)) {
2418 if (!one->sha1_valid) {
2419 struct stat st;
5332b2af
JS
2420 if (!strcmp(one->path, "-")) {
2421 hashcpy(one->sha1, null_sha1);
2422 return;
2423 }
6973dcae 2424 if (lstat(one->path, &st) < 0)
0721c314 2425 die_errno("stat '%s'", one->path);
6973dcae 2426 if (index_path(one->sha1, one->path, &st, 0))
d7530708 2427 die("cannot hash %s", one->path);
6973dcae
JH
2428 }
2429 }
2430 else
e702496e 2431 hashclr(one->sha1);
6973dcae
JH
2432}
2433
cd676a51
JH
2434static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
2435{
2436 /* Strip the prefix but do not molest /dev/null and absolute paths */
2437 if (*namep && **namep != '/')
2438 *namep += prefix_length;
2439 if (*otherp && **otherp != '/')
2440 *otherp += prefix_length;
2441}
2442
6973dcae
JH
2443static void run_diff(struct diff_filepair *p, struct diff_options *o)
2444{
2445 const char *pgm = external_diff();
663af342 2446 struct strbuf msg;
663af342
PH
2447 struct diff_filespec *one = p->one;
2448 struct diff_filespec *two = p->two;
6973dcae
JH
2449 const char *name;
2450 const char *other;
cd676a51 2451 const char *attr_path;
663af342 2452
cd676a51
JH
2453 name = p->one->path;
2454 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2455 attr_path = name;
2456 if (o->prefix_length)
2457 strip_prefix(o->prefix_length, &name, &other);
6973dcae
JH
2458
2459 if (DIFF_PAIR_UNMERGED(p)) {
cd676a51 2460 run_diff_cmd(pgm, name, NULL, attr_path,
b67b9612 2461 NULL, NULL, NULL, o, p);
6973dcae
JH
2462 return;
2463 }
2464
6973dcae
JH
2465 diff_fill_sha1_info(one);
2466 diff_fill_sha1_info(two);
2467
6973dcae
JH
2468 if (!pgm &&
2469 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
2470 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
b67b9612
JH
2471 /*
2472 * a filepair that changes between file and symlink
6973dcae
JH
2473 * needs to be split into deletion and creation.
2474 */
2475 struct diff_filespec *null = alloc_filespec(two->path);
cd676a51 2476 run_diff_cmd(NULL, name, other, attr_path,
b67b9612 2477 one, null, &msg, o, p);
6973dcae 2478 free(null);
b67b9612
JH
2479 strbuf_release(&msg);
2480
6973dcae 2481 null = alloc_filespec(one->path);
cd676a51 2482 run_diff_cmd(NULL, name, other, attr_path,
b67b9612 2483 null, two, &msg, o, p);
6973dcae
JH
2484 free(null);
2485 }
2486 else
cd676a51 2487 run_diff_cmd(pgm, name, other, attr_path,
b67b9612 2488 one, two, &msg, o, p);
6973dcae 2489
663af342 2490 strbuf_release(&msg);
6973dcae
JH
2491}
2492
2493static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
2494 struct diffstat_t *diffstat)
2495{
2496 const char *name;
2497 const char *other;
710158e3 2498 int complete_rewrite = 0;
6973dcae
JH
2499
2500 if (DIFF_PAIR_UNMERGED(p)) {
2501 /* unmerged */
0d21efa5 2502 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
6973dcae
JH
2503 return;
2504 }
2505
2506 name = p->one->path;
2507 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2508
cd676a51
JH
2509 if (o->prefix_length)
2510 strip_prefix(o->prefix_length, &name, &other);
2511
6973dcae
JH
2512 diff_fill_sha1_info(p->one);
2513 diff_fill_sha1_info(p->two);
2514
710158e3
JH
2515 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2516 complete_rewrite = 1;
0d21efa5 2517 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
6973dcae
JH
2518}
2519
88246898
JS
2520static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
2521{
2522 const char *name;
2523 const char *other;
cd676a51 2524 const char *attr_path;
88246898
JS
2525
2526 if (DIFF_PAIR_UNMERGED(p)) {
2527 /* unmerged */
2528 return;
2529 }
2530
2531 name = p->one->path;
2532 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
cd676a51
JH
2533 attr_path = other ? other : name;
2534
2535 if (o->prefix_length)
2536 strip_prefix(o->prefix_length, &name, &other);
88246898
JS
2537
2538 diff_fill_sha1_info(p->one);
2539 diff_fill_sha1_info(p->two);
2540
cd676a51 2541 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
88246898
JS
2542}
2543
6973dcae
JH
2544void diff_setup(struct diff_options *options)
2545{
2546 memset(options, 0, sizeof(*options));
c0c77734
DB
2547
2548 options->file = stdout;
2549
6973dcae
JH
2550 options->line_termination = '\n';
2551 options->break_opt = -1;
2552 options->rename_limit = -1;
7df7c019 2553 options->dirstat_percent = 3;
ee1e5412 2554 options->context = 3;
6973dcae
JH
2555
2556 options->change = diff_change;
2557 options->add_remove = diff_addremove;
6b2f2d98 2558 if (diff_use_color_default > 0)
8f67f8ae 2559 DIFF_OPT_SET(options, COLOR_DIFF);
b68ea12e 2560 options->detect_rename = diff_detect_rename_default;
eab9a40b 2561
a5a818ee
JH
2562 if (!diff_mnemonic_prefix) {
2563 options->a_prefix = "a/";
2564 options->b_prefix = "b/";
2565 }
6973dcae
JH
2566}
2567
2568int diff_setup_done(struct diff_options *options)
2569{
d7de00f7
TH
2570 int count = 0;
2571
2572 if (options->output_format & DIFF_FORMAT_NAME)
2573 count++;
2574 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
2575 count++;
2576 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
2577 count++;
2578 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
2579 count++;
2580 if (count > 1)
2581 die("--name-only, --name-status, --check and -s are mutually exclusive");
2582
f245194f
JH
2583 /*
2584 * Most of the time we can say "there are changes"
2585 * only by checking if there are changed paths, but
2586 * --ignore-whitespace* options force us to look
97bf2a08 2587 * inside contents.
f245194f
JH
2588 */
2589
2590 if (DIFF_XDL_TST(options, IGNORE_WHITESPACE) ||
2591 DIFF_XDL_TST(options, IGNORE_WHITESPACE_CHANGE) ||
2592 DIFF_XDL_TST(options, IGNORE_WHITESPACE_AT_EOL))
2593 DIFF_OPT_SET(options, DIFF_FROM_CONTENTS);
2594 else
2595 DIFF_OPT_CLR(options, DIFF_FROM_CONTENTS);
2596
8f67f8ae 2597 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
03b9d560
JH
2598 options->detect_rename = DIFF_DETECT_COPY;
2599
cd676a51
JH
2600 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
2601 options->prefix = NULL;
2602 if (options->prefix)
2603 options->prefix_length = strlen(options->prefix);
2604 else
2605 options->prefix_length = 0;
2606
c6744349
TH
2607 if (options->output_format & (DIFF_FORMAT_NAME |
2608 DIFF_FORMAT_NAME_STATUS |
2609 DIFF_FORMAT_CHECKDIFF |
2610 DIFF_FORMAT_NO_OUTPUT))
2611 options->output_format &= ~(DIFF_FORMAT_RAW |
74e2abe5 2612 DIFF_FORMAT_NUMSTAT |
c6744349 2613 DIFF_FORMAT_DIFFSTAT |
ebd124c6 2614 DIFF_FORMAT_SHORTSTAT |
7df7c019 2615 DIFF_FORMAT_DIRSTAT |
c6744349
TH
2616 DIFF_FORMAT_SUMMARY |
2617 DIFF_FORMAT_PATCH);
2618
6973dcae
JH
2619 /*
2620 * These cases always need recursive; we do not drop caller-supplied
2621 * recursive bits for other formats here.
2622 */
c6744349 2623 if (options->output_format & (DIFF_FORMAT_PATCH |
74e2abe5 2624 DIFF_FORMAT_NUMSTAT |
c6744349 2625 DIFF_FORMAT_DIFFSTAT |
ebd124c6 2626 DIFF_FORMAT_SHORTSTAT |
7df7c019 2627 DIFF_FORMAT_DIRSTAT |
d7014dc0 2628 DIFF_FORMAT_SUMMARY |
c6744349 2629 DIFF_FORMAT_CHECKDIFF))
8f67f8ae 2630 DIFF_OPT_SET(options, RECURSIVE);
5e363541 2631 /*
3969cf7d 2632 * Also pickaxe would not work very well if you do not say recursive
5e363541 2633 */
3969cf7d 2634 if (options->pickaxe)
8f67f8ae 2635 DIFF_OPT_SET(options, RECURSIVE);
ae6d5c1b
JL
2636 /*
2637 * When patches are generated, submodules diffed against the work tree
2638 * must be checked for dirtiness too so it can be shown in the output
2639 */
2640 if (options->output_format & DIFF_FORMAT_PATCH)
2641 DIFF_OPT_SET(options, DIRTY_SUBMODULES);
5e363541 2642
6973dcae
JH
2643 if (options->detect_rename && options->rename_limit < 0)
2644 options->rename_limit = diff_rename_limit_default;
2645 if (options->setup & DIFF_SETUP_USE_CACHE) {
2646 if (!active_cache)
2647 /* read-cache does not die even when it fails
2648 * so it is safe for us to do this here. Also
2649 * it does not smudge active_cache or active_nr
2650 * when it fails, so we do not have to worry about
2651 * cleaning it up ourselves either.
2652 */
2653 read_cache();
2654 }
6973dcae
JH
2655 if (options->abbrev <= 0 || 40 < options->abbrev)
2656 options->abbrev = 40; /* full */
2657
68aacb2f
JH
2658 /*
2659 * It does not make sense to show the first hit we happened
2660 * to have found. It does not make sense not to return with
2661 * exit code in such a case either.
2662 */
90b19941 2663 if (DIFF_OPT_TST(options, QUICK)) {
68aacb2f 2664 options->output_format = DIFF_FORMAT_NO_OUTPUT;
8f67f8ae 2665 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
68aacb2f
JH
2666 }
2667
6973dcae
JH
2668 return 0;
2669}
2670
d2543b8e 2671static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
ee1e5412
LT
2672{
2673 char c, *eq;
2674 int len;
2675
2676 if (*arg != '-')
2677 return 0;
2678 c = *++arg;
2679 if (!c)
2680 return 0;
2681 if (c == arg_short) {
2682 c = *++arg;
2683 if (!c)
2684 return 1;
2685 if (val && isdigit(c)) {
2686 char *end;
2687 int n = strtoul(arg, &end, 10);
2688 if (*end)
2689 return 0;
2690 *val = n;
2691 return 1;
2692 }
2693 return 0;
2694 }
2695 if (c != '-')
2696 return 0;
2697 arg++;
2698 eq = strchr(arg, '=');
2699 if (eq)
2700 len = eq - arg;
2701 else
2702 len = strlen(arg);
2703 if (!len || strncmp(arg, arg_long, len))
2704 return 0;
2705 if (eq) {
2706 int n;
2707 char *end;
2708 if (!isdigit(*++eq))
2709 return 0;
2710 n = strtoul(eq, &end, 10);
2711 if (*end)
2712 return 0;
2713 *val = n;
2714 }
2715 return 1;
2716}
2717
16befb8b
JH
2718static int diff_scoreopt_parse(const char *opt);
2719
6973dcae
JH
2720int diff_opt_parse(struct diff_options *options, const char **av, int ac)
2721{
2722 const char *arg = av[0];
d054680c
PH
2723
2724 /* Output format options */
6973dcae 2725 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
c6744349 2726 options->output_format |= DIFF_FORMAT_PATCH;
ee1e5412 2727 else if (opt_arg(arg, 'U', "unified", &options->context))
c6744349 2728 options->output_format |= DIFF_FORMAT_PATCH;
a610786f
TH
2729 else if (!strcmp(arg, "--raw"))
2730 options->output_format |= DIFF_FORMAT_RAW;
8f67f8ae 2731 else if (!strcmp(arg, "--patch-with-raw"))
c6744349 2732 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
8f67f8ae 2733 else if (!strcmp(arg, "--numstat"))
74e2abe5 2734 options->output_format |= DIFF_FORMAT_NUMSTAT;
8f67f8ae 2735 else if (!strcmp(arg, "--shortstat"))
ebd124c6 2736 options->output_format |= DIFF_FORMAT_SHORTSTAT;
7df7c019
LT
2737 else if (opt_arg(arg, 'X', "dirstat", &options->dirstat_percent))
2738 options->output_format |= DIFF_FORMAT_DIRSTAT;
f88d225f
JH
2739 else if (!strcmp(arg, "--cumulative")) {
2740 options->output_format |= DIFF_FORMAT_DIRSTAT;
2741 DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
fd33777b
HO
2742 } else if (opt_arg(arg, 0, "dirstat-by-file",
2743 &options->dirstat_percent)) {
2744 options->output_format |= DIFF_FORMAT_DIRSTAT;
2745 DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
f88d225f 2746 }
d054680c
PH
2747 else if (!strcmp(arg, "--check"))
2748 options->output_format |= DIFF_FORMAT_CHECKDIFF;
2749 else if (!strcmp(arg, "--summary"))
2750 options->output_format |= DIFF_FORMAT_SUMMARY;
2751 else if (!strcmp(arg, "--patch-with-stat"))
2752 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2753 else if (!strcmp(arg, "--name-only"))
2754 options->output_format |= DIFF_FORMAT_NAME;
2755 else if (!strcmp(arg, "--name-status"))
2756 options->output_format |= DIFF_FORMAT_NAME_STATUS;
2757 else if (!strcmp(arg, "-s"))
2758 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
cc44c765 2759 else if (!prefixcmp(arg, "--stat")) {
5c5b2ea9
LT
2760 char *end;
2761 int width = options->stat_width;
2762 int name_width = options->stat_name_width;
2763 arg += 6;
2764 end = (char *)arg;
2765
2766 switch (*arg) {
2767 case '-':
cc44c765 2768 if (!prefixcmp(arg, "-width="))
5c5b2ea9 2769 width = strtoul(arg + 7, &end, 10);
cc44c765 2770 else if (!prefixcmp(arg, "-name-width="))
5c5b2ea9
LT
2771 name_width = strtoul(arg + 12, &end, 10);
2772 break;
2773 case '=':
2774 width = strtoul(arg+1, &end, 10);
2775 if (*end == ',')
2776 name_width = strtoul(end+1, &end, 10);
2777 }
2778
2779 /* Important! This checks all the error cases! */
2780 if (*end)
2781 return 0;
c6744349 2782 options->output_format |= DIFF_FORMAT_DIFFSTAT;
5c5b2ea9
LT
2783 options->stat_name_width = name_width;
2784 options->stat_width = width;
a2540023 2785 }
d054680c
PH
2786
2787 /* renames options */
cc44c765 2788 else if (!prefixcmp(arg, "-B")) {
8f67f8ae 2789 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
6973dcae
JH
2790 return -1;
2791 }
cc44c765 2792 else if (!prefixcmp(arg, "-M")) {
8f67f8ae 2793 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
6973dcae
JH
2794 return -1;
2795 options->detect_rename = DIFF_DETECT_RENAME;
2796 }
cc44c765 2797 else if (!prefixcmp(arg, "-C")) {
ca6c0970 2798 if (options->detect_rename == DIFF_DETECT_COPY)
8f67f8ae
PH
2799 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2800 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
6973dcae
JH
2801 return -1;
2802 options->detect_rename = DIFF_DETECT_COPY;
2803 }
d054680c
PH
2804 else if (!strcmp(arg, "--no-renames"))
2805 options->detect_rename = 0;
cd676a51
JH
2806 else if (!strcmp(arg, "--relative"))
2807 DIFF_OPT_SET(options, RELATIVE_NAME);
c0cb4a06
JH
2808 else if (!prefixcmp(arg, "--relative=")) {
2809 DIFF_OPT_SET(options, RELATIVE_NAME);
2810 options->prefix = arg + 11;
2811 }
d054680c
PH
2812
2813 /* xdiff options */
2814 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
628d5c2b 2815 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
d054680c 2816 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
628d5c2b 2817 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
d054680c 2818 else if (!strcmp(arg, "--ignore-space-at-eol"))
628d5c2b 2819 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
34292bdd 2820 else if (!strcmp(arg, "--patience"))
628d5c2b 2821 DIFF_XDL_SET(options, PATIENCE_DIFF);
d054680c
PH
2822
2823 /* flags options */
2824 else if (!strcmp(arg, "--binary")) {
2825 options->output_format |= DIFF_FORMAT_PATCH;
2826 DIFF_OPT_SET(options, BINARY);
2827 }
2828 else if (!strcmp(arg, "--full-index"))
2829 DIFF_OPT_SET(options, FULL_INDEX);
2830 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
2831 DIFF_OPT_SET(options, TEXT);
2832 else if (!strcmp(arg, "-R"))
2833 DIFF_OPT_SET(options, REVERSE_DIFF);
6973dcae 2834 else if (!strcmp(arg, "--find-copies-harder"))
8f67f8ae 2835 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
750f7b66 2836 else if (!strcmp(arg, "--follow"))
8f67f8ae 2837 DIFF_OPT_SET(options, FOLLOW_RENAMES);
cd112cef 2838 else if (!strcmp(arg, "--color"))
8f67f8ae 2839 DIFF_OPT_SET(options, COLOR_DIFF);
73e9da01
ML
2840 else if (!prefixcmp(arg, "--color=")) {
2841 int value = git_config_colorbool(NULL, arg+8, -1);
2842 if (value == 0)
2843 DIFF_OPT_CLR(options, COLOR_DIFF);
2844 else if (value > 0)
2845 DIFF_OPT_SET(options, COLOR_DIFF);
2846 else
2847 return error("option `color' expects \"always\", \"auto\", or \"never\"");
2848 }
fef88bb0 2849 else if (!strcmp(arg, "--no-color"))
8f67f8ae 2850 DIFF_OPT_CLR(options, COLOR_DIFF);
628d5c2b
KC
2851 else if (!strcmp(arg, "--color-words")) {
2852 DIFF_OPT_SET(options, COLOR_DIFF);
2853 DIFF_OPT_SET(options, COLOR_DIFF_WORDS);
2854 }
2b6a5417 2855 else if (!prefixcmp(arg, "--color-words=")) {
628d5c2b
KC
2856 DIFF_OPT_SET(options, COLOR_DIFF);
2857 DIFF_OPT_SET(options, COLOR_DIFF_WORDS);
2b6a5417
JS
2858 options->word_regex = arg + 14;
2859 }
41bbf9d5 2860 else if (!strcmp(arg, "--exit-code"))
8f67f8ae 2861 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
68aacb2f 2862 else if (!strcmp(arg, "--quiet"))
90b19941 2863 DIFF_OPT_SET(options, QUICK);
72909bef 2864 else if (!strcmp(arg, "--ext-diff"))
8f67f8ae 2865 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
72909bef 2866 else if (!strcmp(arg, "--no-ext-diff"))
8f67f8ae 2867 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
e10ea812
JK
2868 else if (!strcmp(arg, "--textconv"))
2869 DIFF_OPT_SET(options, ALLOW_TEXTCONV);
2870 else if (!strcmp(arg, "--no-textconv"))
2871 DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
50fd9bd8
JS
2872 else if (!strcmp(arg, "--ignore-submodules"))
2873 DIFF_OPT_SET(options, IGNORE_SUBMODULES);
752c0c24
JS
2874 else if (!strcmp(arg, "--submodule"))
2875 DIFF_OPT_SET(options, SUBMODULE_LOG);
2876 else if (!prefixcmp(arg, "--submodule=")) {
2877 if (!strcmp(arg + 12, "log"))
2878 DIFF_OPT_SET(options, SUBMODULE_LOG);
2879 }
d054680c
PH
2880
2881 /* misc options */
2882 else if (!strcmp(arg, "-z"))
2883 options->line_termination = 0;
2884 else if (!prefixcmp(arg, "-l"))
2885 options->rename_limit = strtoul(arg+2, NULL, 10);
2886 else if (!prefixcmp(arg, "-S"))
2887 options->pickaxe = arg + 2;
2888 else if (!strcmp(arg, "--pickaxe-all"))
2889 options->pickaxe_opts = DIFF_PICKAXE_ALL;
2890 else if (!strcmp(arg, "--pickaxe-regex"))
2891 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2892 else if (!prefixcmp(arg, "-O"))
2893 options->orderfile = arg + 2;
2894 else if (!prefixcmp(arg, "--diff-filter="))
2895 options->filter = arg + 14;
2896 else if (!strcmp(arg, "--abbrev"))
2897 options->abbrev = DEFAULT_ABBREV;
2898 else if (!prefixcmp(arg, "--abbrev=")) {
2899 options->abbrev = strtoul(arg + 9, NULL, 10);
2900 if (options->abbrev < MINIMUM_ABBREV)
2901 options->abbrev = MINIMUM_ABBREV;
2902 else if (40 < options->abbrev)
2903 options->abbrev = 40;
2904 }
eab9a40b
JS
2905 else if (!prefixcmp(arg, "--src-prefix="))
2906 options->a_prefix = arg + 13;
2907 else if (!prefixcmp(arg, "--dst-prefix="))
2908 options->b_prefix = arg + 13;
2909 else if (!strcmp(arg, "--no-prefix"))
2910 options->a_prefix = options->b_prefix = "";
6d0e674a
RS
2911 else if (opt_arg(arg, '\0', "inter-hunk-context",
2912 &options->interhunkcontext))
2913 ;
c0c77734
DB
2914 else if (!prefixcmp(arg, "--output=")) {
2915 options->file = fopen(arg + strlen("--output="), "w");
8324b977
LA
2916 if (!options->file)
2917 die_errno("Could not open '%s'", arg + strlen("--output="));
c0c77734
DB
2918 options->close_file = 1;
2919 } else
6973dcae
JH
2920 return 0;
2921 return 1;
2922}
2923
2924static int parse_num(const char **cp_p)
2925{
2926 unsigned long num, scale;
2927 int ch, dot;
2928 const char *cp = *cp_p;
2929
2930 num = 0;
2931 scale = 1;
2932 dot = 0;
eeefa7c9 2933 for (;;) {
6973dcae
JH
2934 ch = *cp;
2935 if ( !dot && ch == '.' ) {
2936 scale = 1;
2937 dot = 1;
2938 } else if ( ch == '%' ) {
2939 scale = dot ? scale*100 : 100;
2940 cp++; /* % is always at the end */
2941 break;
2942 } else if ( ch >= '0' && ch <= '9' ) {
2943 if ( scale < 100000 ) {
2944 scale *= 10;
2945 num = (num*10) + (ch-'0');
2946 }
2947 } else {
2948 break;
2949 }
2950 cp++;
2951 }
2952 *cp_p = cp;
2953
2954 /* user says num divided by scale and we say internally that
2955 * is MAX_SCORE * num / scale.
2956 */
dc49cd76 2957 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
6973dcae
JH
2958}
2959
16befb8b 2960static int diff_scoreopt_parse(const char *opt)
6973dcae
JH
2961{
2962 int opt1, opt2, cmd;
2963
2964 if (*opt++ != '-')
2965 return -1;
2966 cmd = *opt++;
2967 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2968 return -1; /* that is not a -M, -C nor -B option */
2969
2970 opt1 = parse_num(&opt);
2971 if (cmd != 'B')
2972 opt2 = 0;
2973 else {
2974 if (*opt == 0)
2975 opt2 = 0;
2976 else if (*opt != '/')
2977 return -1; /* we expect -B80/99 or -B80 */
2978 else {
2979 opt++;
2980 opt2 = parse_num(&opt);
2981 }
2982 }
2983 if (*opt != 0)
2984 return -1;
2985 return opt1 | (opt2 << 16);
2986}
2987
2988struct diff_queue_struct diff_queued_diff;
2989
2990void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2991{
2992 if (queue->alloc <= queue->nr) {
2993 queue->alloc = alloc_nr(queue->alloc);
2994 queue->queue = xrealloc(queue->queue,
2995 sizeof(dp) * queue->alloc);
2996 }
2997 queue->queue[queue->nr++] = dp;
2998}
2999
3000struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
3001 struct diff_filespec *one,
3002 struct diff_filespec *two)
3003{
ef677686 3004 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
6973dcae
JH
3005 dp->one = one;
3006 dp->two = two;
6973dcae
JH
3007 if (queue)
3008 diff_q(queue, dp);
3009 return dp;
3010}
3011
3012void diff_free_filepair(struct diff_filepair *p)
3013{
9fb88419
LT
3014 free_filespec(p->one);
3015 free_filespec(p->two);
6973dcae
JH
3016 free(p);
3017}
3018
3019/* This is different from find_unique_abbrev() in that
3020 * it stuffs the result with dots for alignment.
3021 */
3022const char *diff_unique_abbrev(const unsigned char *sha1, int len)
3023{
3024 int abblen;
3025 const char *abbrev;
3026 if (len == 40)
3027 return sha1_to_hex(sha1);
3028
3029 abbrev = find_unique_abbrev(sha1, len);
6973dcae
JH
3030 abblen = strlen(abbrev);
3031 if (abblen < 37) {
3032 static char hex[41];
3033 if (len < abblen && abblen <= len + 2)
3034 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
3035 else
3036 sprintf(hex, "%s...", abbrev);
3037 return hex;
3038 }
3039 return sha1_to_hex(sha1);
3040}
3041
663af342 3042static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
6973dcae 3043{
663af342
PH
3044 int line_termination = opt->line_termination;
3045 int inter_name_termination = line_termination ? '\t' : '\0';
6973dcae 3046
663af342 3047 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
c0c77734
DB
3048 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
3049 diff_unique_abbrev(p->one->sha1, opt->abbrev));
3050 fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
6973dcae 3051 }
663af342 3052 if (p->score) {
c0c77734
DB
3053 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
3054 inter_name_termination);
663af342 3055 } else {
c0c77734 3056 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
6973dcae 3057 }
6973dcae 3058
cd676a51
JH
3059 if (p->status == DIFF_STATUS_COPIED ||
3060 p->status == DIFF_STATUS_RENAMED) {
3061 const char *name_a, *name_b;
3062 name_a = p->one->path;
3063 name_b = p->two->path;
3064 strip_prefix(opt->prefix_length, &name_a, &name_b);
c0c77734
DB
3065 write_name_quoted(name_a, opt->file, inter_name_termination);
3066 write_name_quoted(name_b, opt->file, line_termination);
663af342 3067 } else {
cd676a51
JH
3068 const char *name_a, *name_b;
3069 name_a = p->one->mode ? p->one->path : p->two->path;
3070 name_b = NULL;
3071 strip_prefix(opt->prefix_length, &name_a, &name_b);
c0c77734 3072 write_name_quoted(name_a, opt->file, line_termination);
663af342 3073 }
6973dcae
JH
3074}
3075
3076int diff_unmodified_pair(struct diff_filepair *p)
3077{
3078 /* This function is written stricter than necessary to support
3079 * the currently implemented transformers, but the idea is to
3080 * let transformers to produce diff_filepairs any way they want,
3081 * and filter and clean them up here before producing the output.
3082 */
663af342 3083 struct diff_filespec *one = p->one, *two = p->two;
6973dcae
JH
3084
3085 if (DIFF_PAIR_UNMERGED(p))
3086 return 0; /* unmerged is interesting */
3087
6973dcae
JH
3088 /* deletion, addition, mode or type change
3089 * and rename are all interesting.
3090 */
3091 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
3092 DIFF_PAIR_MODE_CHANGED(p) ||
3093 strcmp(one->path, two->path))
3094 return 0;
3095
3096 /* both are valid and point at the same path. that is, we are
3097 * dealing with a change.
3098 */
3099 if (one->sha1_valid && two->sha1_valid &&
85adbf2f
JL
3100 !hashcmp(one->sha1, two->sha1) &&
3101 !one->dirty_submodule && !two->dirty_submodule)
6973dcae
JH
3102 return 1; /* no change */
3103 if (!one->sha1_valid && !two->sha1_valid)
3104 return 1; /* both look at the same file on the filesystem. */
3105 return 0;
3106}
3107
3108static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
3109{
3110 if (diff_unmodified_pair(p))
3111 return;
3112
3113 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3114 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3115 return; /* no tree diffs in patch format */
3116
3117 run_diff(p, o);
3118}
3119
3120static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
3121 struct diffstat_t *diffstat)
3122{
3123 if (diff_unmodified_pair(p))
3124 return;
3125
3126 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3127 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3128 return; /* no tree diffs in patch format */
3129
3130 run_diffstat(p, o, diffstat);
3131}
3132
88246898
JS
3133static void diff_flush_checkdiff(struct diff_filepair *p,
3134 struct diff_options *o)
3135{
3136 if (diff_unmodified_pair(p))
3137 return;
3138
3139 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3140 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3141 return; /* no tree diffs in patch format */
3142
3143 run_checkdiff(p, o);
3144}
3145
6973dcae
JH
3146int diff_queue_is_empty(void)
3147{
3148 struct diff_queue_struct *q = &diff_queued_diff;
3149 int i;
3150 for (i = 0; i < q->nr; i++)
3151 if (!diff_unmodified_pair(q->queue[i]))
3152 return 0;
3153 return 1;
3154}
3155
3156#if DIFF_DEBUG
3157void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
3158{
3159 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
3160 x, one ? one : "",
3161 s->path,
3162 DIFF_FILE_VALID(s) ? "valid" : "invalid",
3163 s->mode,
3164 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
3165 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
3166 x, one ? one : "",
3167 s->size, s->xfrm_flags);
3168}
3169
3170void diff_debug_filepair(const struct diff_filepair *p, int i)
3171{
3172 diff_debug_filespec(p->one, i, "one");
3173 diff_debug_filespec(p->two, i, "two");
64479711 3174 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
6973dcae 3175 p->score, p->status ? p->status : '?',
64479711 3176 p->one->rename_used, p->broken_pair);
6973dcae
JH
3177}
3178
3179void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
3180{
3181 int i;
3182 if (msg)
3183 fprintf(stderr, "%s\n", msg);
3184 fprintf(stderr, "q->nr = %d\n", q->nr);
3185 for (i = 0; i < q->nr; i++) {
3186 struct diff_filepair *p = q->queue[i];
3187 diff_debug_filepair(p, i);
3188 }
3189}
3190#endif
3191
3192static void diff_resolve_rename_copy(void)
3193{
64479711
LT
3194 int i;
3195 struct diff_filepair *p;
6973dcae
JH
3196 struct diff_queue_struct *q = &diff_queued_diff;
3197
3198 diff_debug_queue("resolve-rename-copy", q);
3199
3200 for (i = 0; i < q->nr; i++) {
3201 p = q->queue[i];
3202 p->status = 0; /* undecided */
3203 if (DIFF_PAIR_UNMERGED(p))
3204 p->status = DIFF_STATUS_UNMERGED;
3205 else if (!DIFF_FILE_VALID(p->one))
3206 p->status = DIFF_STATUS_ADDED;
3207 else if (!DIFF_FILE_VALID(p->two))
3208 p->status = DIFF_STATUS_DELETED;
3209 else if (DIFF_PAIR_TYPE_CHANGED(p))
3210 p->status = DIFF_STATUS_TYPE_CHANGED;
3211
3212 /* from this point on, we are dealing with a pair
3213 * whose both sides are valid and of the same type, i.e.
3214 * either in-place edit or rename/copy edit.
3215 */
3216 else if (DIFF_PAIR_RENAME(p)) {
64479711
LT
3217 /*
3218 * A rename might have re-connected a broken
3219 * pair up, causing the pathnames to be the
3220 * same again. If so, that's not a rename at
3221 * all, just a modification..
3222 *
3223 * Otherwise, see if this source was used for
3224 * multiple renames, in which case we decrement
3225 * the count, and call it a copy.
6973dcae 3226 */
64479711
LT
3227 if (!strcmp(p->one->path, p->two->path))
3228 p->status = DIFF_STATUS_MODIFIED;
3229 else if (--p->one->rename_used > 0)
6973dcae 3230 p->status = DIFF_STATUS_COPIED;
64479711 3231 else
6973dcae
JH
3232 p->status = DIFF_STATUS_RENAMED;
3233 }
a89fccd2 3234 else if (hashcmp(p->one->sha1, p->two->sha1) ||
d516c2d1 3235 p->one->mode != p->two->mode ||
85adbf2f
JL
3236 p->one->dirty_submodule ||
3237 p->two->dirty_submodule ||
d516c2d1 3238 is_null_sha1(p->one->sha1))
6973dcae
JH
3239 p->status = DIFF_STATUS_MODIFIED;
3240 else {
3241 /* This is a "no-change" entry and should not
3242 * happen anymore, but prepare for broken callers.
3243 */
3244 error("feeding unmodified %s to diffcore",
3245 p->one->path);
3246 p->status = DIFF_STATUS_UNKNOWN;
3247 }
3248 }
3249 diff_debug_queue("resolve-rename-copy done", q);
3250}
3251
c6744349 3252static int check_pair_status(struct diff_filepair *p)
6973dcae 3253{
6973dcae
JH
3254 switch (p->status) {
3255 case DIFF_STATUS_UNKNOWN:
c6744349 3256 return 0;
6973dcae
JH
3257 case 0:
3258 die("internal error in diff-resolve-rename-copy");
6973dcae 3259 default:
c6744349 3260 return 1;
6973dcae
JH
3261 }
3262}
3263
c6744349
TH
3264static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
3265{
3266 int fmt = opt->output_format;
3267
3268 if (fmt & DIFF_FORMAT_CHECKDIFF)
3269 diff_flush_checkdiff(p, opt);
3270 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
3271 diff_flush_raw(p, opt);
cd676a51
JH
3272 else if (fmt & DIFF_FORMAT_NAME) {
3273 const char *name_a, *name_b;
3274 name_a = p->two->path;
3275 name_b = NULL;
3276 strip_prefix(opt->prefix_length, &name_a, &name_b);
c0c77734 3277 write_name_quoted(name_a, opt->file, opt->line_termination);
cd676a51 3278 }
c6744349
TH
3279}
3280
c0c77734 3281static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
4bbd261b
SE
3282{
3283 if (fs->mode)
c0c77734 3284 fprintf(file, " %s mode %06o ", newdelete, fs->mode);
4bbd261b 3285 else
c0c77734
DB
3286 fprintf(file, " %s ", newdelete);
3287 write_name_quoted(fs->path, file, '\n');
4bbd261b
SE
3288}
3289
3290
c0c77734 3291static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name)
4bbd261b
SE
3292{
3293 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
c0c77734 3294 fprintf(file, " mode change %06o => %06o%c", p->one->mode, p->two->mode,
663af342 3295 show_name ? ' ' : '\n');
0d26a64e 3296 if (show_name) {
c0c77734 3297 write_name_quoted(p->two->path, file, '\n');
0d26a64e 3298 }
4bbd261b
SE
3299 }
3300}
3301
c0c77734 3302static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p)
4bbd261b 3303{
b9f44164 3304 char *names = pprint_rename(p->one->path, p->two->path);
4bbd261b 3305
c0c77734 3306 fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
b9f44164 3307 free(names);
c0c77734 3308 show_mode_change(file, p, 0);
4bbd261b
SE
3309}
3310
c0c77734 3311static void diff_summary(FILE *file, struct diff_filepair *p)
4bbd261b
SE
3312{
3313 switch(p->status) {
3314 case DIFF_STATUS_DELETED:
c0c77734 3315 show_file_mode_name(file, "delete", p->one);
4bbd261b
SE
3316 break;
3317 case DIFF_STATUS_ADDED:
c0c77734 3318 show_file_mode_name(file, "create", p->two);
4bbd261b
SE
3319 break;
3320 case DIFF_STATUS_COPIED:
c0c77734 3321 show_rename_copy(file, "copy", p);
4bbd261b
SE
3322 break;
3323 case DIFF_STATUS_RENAMED:
c0c77734 3324 show_rename_copy(file, "rename", p);
4bbd261b
SE
3325 break;
3326 default:
3327 if (p->score) {
c0c77734
DB
3328 fputs(" rewrite ", file);
3329 write_name_quoted(p->two->path, file, ' ');
3330 fprintf(file, "(%d%%)\n", similarity_index(p));
663af342 3331 }
c0c77734 3332 show_mode_change(file, p, !p->score);
4bbd261b
SE
3333 break;
3334 }
3335}
3336
fcb3d0ad 3337struct patch_id_t {
9126f009 3338 git_SHA_CTX *ctx;
fcb3d0ad
JS
3339 int patchlen;
3340};
3341
3342static int remove_space(char *line, int len)
3343{
3344 int i;
663af342
PH
3345 char *dst = line;
3346 unsigned char c;
fcb3d0ad 3347
663af342
PH
3348 for (i = 0; i < len; i++)
3349 if (!isspace((c = line[i])))
3350 *dst++ = c;
fcb3d0ad 3351
663af342 3352 return dst - line;
fcb3d0ad
JS
3353}
3354
3355static void patch_id_consume(void *priv, char *line, unsigned long len)
3356{
3357 struct patch_id_t *data = priv;
3358 int new_len;
3359
3360 /* Ignore line numbers when computing the SHA1 of the patch */
cc44c765 3361 if (!prefixcmp(line, "@@ -"))
fcb3d0ad
JS
3362 return;
3363
3364 new_len = remove_space(line, len);
3365
9126f009 3366 git_SHA1_Update(data->ctx, line, new_len);
fcb3d0ad
JS
3367 data->patchlen += new_len;
3368}
3369
3370/* returns 0 upon success, and writes result into sha1 */
3371static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
3372{
3373 struct diff_queue_struct *q = &diff_queued_diff;
3374 int i;
9126f009 3375 git_SHA_CTX ctx;
fcb3d0ad
JS
3376 struct patch_id_t data;
3377 char buffer[PATH_MAX * 4 + 20];
3378
9126f009 3379 git_SHA1_Init(&ctx);
fcb3d0ad
JS
3380 memset(&data, 0, sizeof(struct patch_id_t));
3381 data.ctx = &ctx;
fcb3d0ad
JS
3382
3383 for (i = 0; i < q->nr; i++) {
3384 xpparam_t xpp;
3385 xdemitconf_t xecfg;
3386 xdemitcb_t ecb;
3387 mmfile_t mf1, mf2;
3388 struct diff_filepair *p = q->queue[i];
3389 int len1, len2;
3390
9ccd0a88 3391 memset(&xpp, 0, sizeof(xpp));
30b25010 3392 memset(&xecfg, 0, sizeof(xecfg));
fcb3d0ad
JS
3393 if (p->status == 0)
3394 return error("internal diff status error");
3395 if (p->status == DIFF_STATUS_UNKNOWN)
3396 continue;
3397 if (diff_unmodified_pair(p))
3398 continue;
3399 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3400 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3401 continue;
3402 if (DIFF_PAIR_UNMERGED(p))
3403 continue;
3404
3405 diff_fill_sha1_info(p->one);
3406 diff_fill_sha1_info(p->two);
3407 if (fill_mmfile(&mf1, p->one) < 0 ||
3408 fill_mmfile(&mf2, p->two) < 0)
3409 return error("unable to read files to diff");
3410
fcb3d0ad
JS
3411 len1 = remove_space(p->one->path, strlen(p->one->path));
3412 len2 = remove_space(p->two->path, strlen(p->two->path));
3413 if (p->one->mode == 0)
3414 len1 = snprintf(buffer, sizeof(buffer),
3415 "diff--gita/%.*sb/%.*s"
3416 "newfilemode%06o"
3417 "---/dev/null"
3418 "+++b/%.*s",
3419 len1, p->one->path,
3420 len2, p->two->path,
3421 p->two->mode,
3422 len2, p->two->path);
3423 else if (p->two->mode == 0)
3424 len1 = snprintf(buffer, sizeof(buffer),
3425 "diff--gita/%.*sb/%.*s"
3426 "deletedfilemode%06o"
3427 "---a/%.*s"
3428 "+++/dev/null",
3429 len1, p->one->path,
3430 len2, p->two->path,
3431 p->one->mode,
3432 len1, p->one->path);
3433 else
3434 len1 = snprintf(buffer, sizeof(buffer),
3435 "diff--gita/%.*sb/%.*s"
3436 "---a/%.*s"
3437 "+++b/%.*s",
3438 len1, p->one->path,
3439 len2, p->two->path,
3440 len1, p->one->path,
3441 len2, p->two->path);
9126f009 3442 git_SHA1_Update(&ctx, buffer, len1);
fcb3d0ad
JS
3443
3444 xpp.flags = XDF_NEED_MINIMAL;
3445 xecfg.ctxlen = 3;
9fdc3bb5 3446 xecfg.flags = XDL_EMIT_FUNCNAMES;
8a3f524b
JH
3447 xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
3448 &xpp, &xecfg, &ecb);
fcb3d0ad
JS
3449 }
3450
9126f009 3451 git_SHA1_Final(sha1, &ctx);
fcb3d0ad
JS
3452 return 0;
3453}
3454
3455int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
3456{
3457 struct diff_queue_struct *q = &diff_queued_diff;
3458 int i;
3459 int result = diff_get_patch_id(options, sha1);
3460
3461 for (i = 0; i < q->nr; i++)
3462 diff_free_filepair(q->queue[i]);
3463
3464 free(q->queue);
3465 q->queue = NULL;
3466 q->nr = q->alloc = 0;
3467
3468 return result;
3469}
3470
946c3784 3471static int is_summary_empty(const struct diff_queue_struct *q)
6973dcae 3472{
6973dcae 3473 int i;
6973dcae 3474
946c3784
TH
3475 for (i = 0; i < q->nr; i++) {
3476 const struct diff_filepair *p = q->queue[i];
3477
3478 switch (p->status) {
3479 case DIFF_STATUS_DELETED:
3480 case DIFF_STATUS_ADDED:
3481 case DIFF_STATUS_COPIED:
3482 case DIFF_STATUS_RENAMED:
3483 return 0;
3484 default:
3485 if (p->score)
3486 return 0;
3487 if (p->one->mode && p->two->mode &&
3488 p->one->mode != p->two->mode)
3489 return 0;
3490 break;
3491 }
6973dcae 3492 }
946c3784
TH
3493 return 1;
3494}
3495
6973dcae
JH
3496void diff_flush(struct diff_options *options)
3497{
3498 struct diff_queue_struct *q = &diff_queued_diff;
c6744349 3499 int i, output_format = options->output_format;
946c3784 3500 int separator = 0;
6973dcae 3501
c6744349
TH
3502 /*
3503 * Order: raw, stat, summary, patch
3504 * or: name/name-status/checkdiff (other bits clear)
3505 */
946c3784
TH
3506 if (!q->nr)
3507 goto free_queue;
6973dcae 3508
c6744349
TH
3509 if (output_format & (DIFF_FORMAT_RAW |
3510 DIFF_FORMAT_NAME |
3511 DIFF_FORMAT_NAME_STATUS |
3512 DIFF_FORMAT_CHECKDIFF)) {
6973dcae
JH
3513 for (i = 0; i < q->nr; i++) {
3514 struct diff_filepair *p = q->queue[i];
c6744349
TH
3515 if (check_pair_status(p))
3516 flush_one_pair(p, options);
6973dcae 3517 }
946c3784 3518 separator++;
6973dcae 3519 }
c6744349 3520
c04a7155 3521 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
5e2b0636 3522 struct diffstat_t diffstat;
c6744349 3523
5e2b0636 3524 memset(&diffstat, 0, sizeof(struct diffstat_t));
6973dcae
JH
3525 for (i = 0; i < q->nr; i++) {
3526 struct diff_filepair *p = q->queue[i];
c6744349 3527 if (check_pair_status(p))
5e2b0636 3528 diff_flush_stat(p, options, &diffstat);
6973dcae 3529 }
74e2abe5
JH
3530 if (output_format & DIFF_FORMAT_NUMSTAT)
3531 show_numstat(&diffstat, options);
3532 if (output_format & DIFF_FORMAT_DIFFSTAT)
3533 show_stats(&diffstat, options);
f604652e 3534 if (output_format & DIFF_FORMAT_SHORTSTAT)
c0c77734 3535 show_shortstats(&diffstat, options);
f604652e 3536 free_diffstat_info(&diffstat);
3969cf7d 3537 separator++;
6973dcae 3538 }
c04a7155
JH
3539 if (output_format & DIFF_FORMAT_DIRSTAT)
3540 show_dirstat(options);
6973dcae 3541
946c3784 3542 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
c6744349 3543 for (i = 0; i < q->nr; i++)
c0c77734 3544 diff_summary(options->file, q->queue[i]);
3969cf7d 3545 separator++;
6973dcae
JH
3546 }
3547
6977c250
LA
3548 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
3549 DIFF_OPT_TST(options, EXIT_WITH_STATUS) &&
3550 DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
3551 /*
3552 * run diff_flush_patch for the exit status. setting
3553 * options->file to /dev/null should be safe, becaue we
3554 * aren't supposed to produce any output anyway.
3555 */
3556 if (options->close_file)
3557 fclose(options->file);
3558 options->file = fopen("/dev/null", "w");
3559 if (!options->file)
3560 die_errno("Could not open /dev/null");
3561 options->close_file = 1;
3562 for (i = 0; i < q->nr; i++) {
3563 struct diff_filepair *p = q->queue[i];
3564 if (check_pair_status(p))
3565 diff_flush_patch(p, options);
3566 if (options->found_changes)
3567 break;
3568 }
3569 }
3570
c6744349 3571 if (output_format & DIFF_FORMAT_PATCH) {
946c3784 3572 if (separator) {
6b2fbaaf 3573 putc(options->line_termination, options->file);
946c3784
TH
3574 if (options->stat_sep) {
3575 /* attach patch instead of inline */
c0c77734 3576 fputs(options->stat_sep, options->file);
946c3784 3577 }
c6744349
TH
3578 }
3579
3580 for (i = 0; i < q->nr; i++) {
3581 struct diff_filepair *p = q->queue[i];
3582 if (check_pair_status(p))
3583 diff_flush_patch(p, options);
3584 }
4bbd261b
SE
3585 }
3586
04245581
JK
3587 if (output_format & DIFF_FORMAT_CALLBACK)
3588 options->format_callback(q, options, options->format_callback_data);
3589
c6744349
TH
3590 for (i = 0; i < q->nr; i++)
3591 diff_free_filepair(q->queue[i]);
946c3784 3592free_queue:
6973dcae
JH
3593 free(q->queue);
3594 q->queue = NULL;
3595 q->nr = q->alloc = 0;
c0c77734
DB
3596 if (options->close_file)
3597 fclose(options->file);
f245194f
JH
3598
3599 /*
97bf2a08 3600 * Report the content-level differences with HAS_CHANGES;
f245194f
JH
3601 * diff_addremove/diff_change does not set the bit when
3602 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
3603 */
3604 if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
3605 if (options->found_changes)
3606 DIFF_OPT_SET(options, HAS_CHANGES);
3607 else
3608 DIFF_OPT_CLR(options, HAS_CHANGES);
3609 }
6973dcae
JH
3610}
3611
3612static void diffcore_apply_filter(const char *filter)
3613{
3614 int i;
3615 struct diff_queue_struct *q = &diff_queued_diff;
3616 struct diff_queue_struct outq;
3617 outq.queue = NULL;
3618 outq.nr = outq.alloc = 0;
3619
3620 if (!filter)
3621 return;
3622
3623 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
3624 int found;
3625 for (i = found = 0; !found && i < q->nr; i++) {
3626 struct diff_filepair *p = q->queue[i];
3627 if (((p->status == DIFF_STATUS_MODIFIED) &&
3628 ((p->score &&
3629 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3630 (!p->score &&
3631 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3632 ((p->status != DIFF_STATUS_MODIFIED) &&
3633 strchr(filter, p->status)))
3634 found++;
3635 }
3636 if (found)
3637 return;
3638
3639 /* otherwise we will clear the whole queue
3640 * by copying the empty outq at the end of this
3641 * function, but first clear the current entries
3642 * in the queue.
3643 */
3644 for (i = 0; i < q->nr; i++)
3645 diff_free_filepair(q->queue[i]);
3646 }
3647 else {
3648 /* Only the matching ones */
3649 for (i = 0; i < q->nr; i++) {
3650 struct diff_filepair *p = q->queue[i];
3651
3652 if (((p->status == DIFF_STATUS_MODIFIED) &&
3653 ((p->score &&
3654 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3655 (!p->score &&
3656 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3657 ((p->status != DIFF_STATUS_MODIFIED) &&
3658 strchr(filter, p->status)))
3659 diff_q(&outq, p);
3660 else
3661 diff_free_filepair(p);