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