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