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