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