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