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