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