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