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