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