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