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