]> git.ipfire.org Git - thirdparty/git.git/blame - diff.c
completion: consolidate test_completion*() tests
[thirdparty/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 else if (!strcmp(arg, "-R"))
3587 DIFF_OPT_SET(options, REVERSE_DIFF);
6973dcae 3588 else if (!strcmp(arg, "--find-copies-harder"))
8f67f8ae 3589 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
750f7b66 3590 else if (!strcmp(arg, "--follow"))
8f67f8ae 3591 DIFF_OPT_SET(options, FOLLOW_RENAMES);
cd112cef 3592 else if (!strcmp(arg, "--color"))
f1c96261 3593 options->use_color = 1;
73e9da01 3594 else if (!prefixcmp(arg, "--color=")) {
e269eb79 3595 int value = git_config_colorbool(NULL, arg+8);
daa0c3d9 3596 if (value < 0)
73e9da01 3597 return error("option `color' expects \"always\", \"auto\", or \"never\"");
daa0c3d9 3598 options->use_color = value;
73e9da01 3599 }
fef88bb0 3600 else if (!strcmp(arg, "--no-color"))
f1c96261 3601 options->use_color = 0;
628d5c2b 3602 else if (!strcmp(arg, "--color-words")) {
f1c96261 3603 options->use_color = 1;
882749a0 3604 options->word_diff = DIFF_WORDS_COLOR;
628d5c2b 3605 }
2b6a5417 3606 else if (!prefixcmp(arg, "--color-words=")) {
f1c96261 3607 options->use_color = 1;
882749a0 3608 options->word_diff = DIFF_WORDS_COLOR;
2b6a5417
JS
3609 options->word_regex = arg + 14;
3610 }
882749a0
TR
3611 else if (!strcmp(arg, "--word-diff")) {
3612 if (options->word_diff == DIFF_WORDS_NONE)
3613 options->word_diff = DIFF_WORDS_PLAIN;
3614 }
3615 else if (!prefixcmp(arg, "--word-diff=")) {
3616 const char *type = arg + 12;
3617 if (!strcmp(type, "plain"))
3618 options->word_diff = DIFF_WORDS_PLAIN;
3619 else if (!strcmp(type, "color")) {
f1c96261 3620 options->use_color = 1;
882749a0
TR
3621 options->word_diff = DIFF_WORDS_COLOR;
3622 }
3623 else if (!strcmp(type, "porcelain"))
3624 options->word_diff = DIFF_WORDS_PORCELAIN;
3625 else if (!strcmp(type, "none"))
3626 options->word_diff = DIFF_WORDS_NONE;
3627 else
3628 die("bad --word-diff argument: %s", type);
3629 }
dea007fb 3630 else if ((argcount = parse_long_opt("word-diff-regex", av, &optarg))) {
882749a0
TR
3631 if (options->word_diff == DIFF_WORDS_NONE)
3632 options->word_diff = DIFF_WORDS_PLAIN;
dea007fb
MM
3633 options->word_regex = optarg;
3634 return argcount;
882749a0 3635 }
41bbf9d5 3636 else if (!strcmp(arg, "--exit-code"))
8f67f8ae 3637 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
68aacb2f 3638 else if (!strcmp(arg, "--quiet"))
90b19941 3639 DIFF_OPT_SET(options, QUICK);
72909bef 3640 else if (!strcmp(arg, "--ext-diff"))
8f67f8ae 3641 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
72909bef 3642 else if (!strcmp(arg, "--no-ext-diff"))
8f67f8ae 3643 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
e10ea812
JK
3644 else if (!strcmp(arg, "--textconv"))
3645 DIFF_OPT_SET(options, ALLOW_TEXTCONV);
3646 else if (!strcmp(arg, "--no-textconv"))
3647 DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
aee9c7d6
JL
3648 else if (!strcmp(arg, "--ignore-submodules")) {
3649 DIFF_OPT_SET(options, OVERRIDE_SUBMODULE_CONFIG);
46a958b3 3650 handle_ignore_submodules_arg(options, "all");
aee9c7d6
JL
3651 } else if (!prefixcmp(arg, "--ignore-submodules=")) {
3652 DIFF_OPT_SET(options, OVERRIDE_SUBMODULE_CONFIG);
46a958b3 3653 handle_ignore_submodules_arg(options, arg + 20);
aee9c7d6 3654 } else if (!strcmp(arg, "--submodule"))
752c0c24
JS
3655 DIFF_OPT_SET(options, SUBMODULE_LOG);
3656 else if (!prefixcmp(arg, "--submodule=")) {
3657 if (!strcmp(arg + 12, "log"))
3658 DIFF_OPT_SET(options, SUBMODULE_LOG);
3659 }
d054680c
PH
3660
3661 /* misc options */
3662 else if (!strcmp(arg, "-z"))
3663 options->line_termination = 0;
dea007fb
MM
3664 else if ((argcount = short_opt('l', av, &optarg))) {
3665 options->rename_limit = strtoul(optarg, NULL, 10);
3666 return argcount;
3667 }
3668 else if ((argcount = short_opt('S', av, &optarg))) {
3669 options->pickaxe = optarg;
f506b8e8
JH
3670 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
3671 return argcount;
3672 } else if ((argcount = short_opt('G', av, &optarg))) {
3673 options->pickaxe = optarg;
3674 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
dea007fb
MM
3675 return argcount;
3676 }
d054680c 3677 else if (!strcmp(arg, "--pickaxe-all"))
f506b8e8 3678 options->pickaxe_opts |= DIFF_PICKAXE_ALL;
d054680c 3679 else if (!strcmp(arg, "--pickaxe-regex"))
f506b8e8 3680 options->pickaxe_opts |= DIFF_PICKAXE_REGEX;
dea007fb
MM
3681 else if ((argcount = short_opt('O', av, &optarg))) {
3682 options->orderfile = optarg;
3683 return argcount;
3684 }
3685 else if ((argcount = parse_long_opt("diff-filter", av, &optarg))) {
3686 options->filter = optarg;
3687 return argcount;
3688 }
d054680c
PH
3689 else if (!strcmp(arg, "--abbrev"))
3690 options->abbrev = DEFAULT_ABBREV;
3691 else if (!prefixcmp(arg, "--abbrev=")) {
3692 options->abbrev = strtoul(arg + 9, NULL, 10);
3693 if (options->abbrev < MINIMUM_ABBREV)
3694 options->abbrev = MINIMUM_ABBREV;
3695 else if (40 < options->abbrev)
3696 options->abbrev = 40;
3697 }
dea007fb
MM
3698 else if ((argcount = parse_long_opt("src-prefix", av, &optarg))) {
3699 options->a_prefix = optarg;
3700 return argcount;
3701 }
3702 else if ((argcount = parse_long_opt("dst-prefix", av, &optarg))) {
3703 options->b_prefix = optarg;
3704 return argcount;
3705 }
eab9a40b
JS
3706 else if (!strcmp(arg, "--no-prefix"))
3707 options->a_prefix = options->b_prefix = "";
6d0e674a
RS
3708 else if (opt_arg(arg, '\0', "inter-hunk-context",
3709 &options->interhunkcontext))
3710 ;
14937c2c
RS
3711 else if (!strcmp(arg, "-W"))
3712 DIFF_OPT_SET(options, FUNCCONTEXT);
3713 else if (!strcmp(arg, "--function-context"))
3714 DIFF_OPT_SET(options, FUNCCONTEXT);
3715 else if (!strcmp(arg, "--no-function-context"))
3716 DIFF_OPT_CLR(options, FUNCCONTEXT);
dea007fb
MM
3717 else if ((argcount = parse_long_opt("output", av, &optarg))) {
3718 options->file = fopen(optarg, "w");
8324b977 3719 if (!options->file)
9ec26eb7 3720 die_errno("Could not open '%s'", optarg);
c0c77734 3721 options->close_file = 1;
dea007fb 3722 return argcount;
c0c77734 3723 } else
6973dcae
JH
3724 return 0;
3725 return 1;
3726}
3727
10ae7526 3728int parse_rename_score(const char **cp_p)
6973dcae
JH
3729{
3730 unsigned long num, scale;
3731 int ch, dot;
3732 const char *cp = *cp_p;
3733
3734 num = 0;
3735 scale = 1;
3736 dot = 0;
eeefa7c9 3737 for (;;) {
6973dcae
JH
3738 ch = *cp;
3739 if ( !dot && ch == '.' ) {
3740 scale = 1;
3741 dot = 1;
3742 } else if ( ch == '%' ) {
3743 scale = dot ? scale*100 : 100;
3744 cp++; /* % is always at the end */
3745 break;
3746 } else if ( ch >= '0' && ch <= '9' ) {
3747 if ( scale < 100000 ) {
3748 scale *= 10;
3749 num = (num*10) + (ch-'0');
3750 }
3751 } else {
3752 break;
3753 }
3754 cp++;
3755 }
3756 *cp_p = cp;
3757
3758 /* user says num divided by scale and we say internally that
3759 * is MAX_SCORE * num / scale.
3760 */
dc49cd76 3761 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
6973dcae
JH
3762}
3763
16befb8b 3764static int diff_scoreopt_parse(const char *opt)
6973dcae
JH
3765{
3766 int opt1, opt2, cmd;
3767
3768 if (*opt++ != '-')
3769 return -1;
3770 cmd = *opt++;
37ab5156
KB
3771 if (cmd == '-') {
3772 /* convert the long-form arguments into short-form versions */
3773 if (!prefixcmp(opt, "break-rewrites")) {
3774 opt += strlen("break-rewrites");
3775 if (*opt == 0 || *opt++ == '=')
3776 cmd = 'B';
f611ddc7
YD
3777 } else if (!prefixcmp(opt, "find-copies")) {
3778 opt += strlen("find-copies");
37ab5156
KB
3779 if (*opt == 0 || *opt++ == '=')
3780 cmd = 'C';
f611ddc7
YD
3781 } else if (!prefixcmp(opt, "find-renames")) {
3782 opt += strlen("find-renames");
37ab5156
KB
3783 if (*opt == 0 || *opt++ == '=')
3784 cmd = 'M';
3785 }
3786 }
6973dcae
JH
3787 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
3788 return -1; /* that is not a -M, -C nor -B option */
3789
10ae7526 3790 opt1 = parse_rename_score(&opt);
6973dcae
JH
3791 if (cmd != 'B')
3792 opt2 = 0;
3793 else {
3794 if (*opt == 0)
3795 opt2 = 0;
3796 else if (*opt != '/')
3797 return -1; /* we expect -B80/99 or -B80 */
3798 else {
3799 opt++;
10ae7526 3800 opt2 = parse_rename_score(&opt);
6973dcae
JH
3801 }
3802 }
3803 if (*opt != 0)
3804 return -1;
3805 return opt1 | (opt2 << 16);
3806}
3807
3808struct diff_queue_struct diff_queued_diff;
3809
3810void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
3811{
3812 if (queue->alloc <= queue->nr) {
3813 queue->alloc = alloc_nr(queue->alloc);
3814 queue->queue = xrealloc(queue->queue,
3815 sizeof(dp) * queue->alloc);
3816 }
3817 queue->queue[queue->nr++] = dp;
3818}
3819
3820struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
3821 struct diff_filespec *one,
3822 struct diff_filespec *two)
3823{
ef677686 3824 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
6973dcae
JH
3825 dp->one = one;
3826 dp->two = two;
6973dcae
JH
3827 if (queue)
3828 diff_q(queue, dp);
3829 return dp;
3830}
3831
3832void diff_free_filepair(struct diff_filepair *p)
3833{
9fb88419
LT
3834 free_filespec(p->one);
3835 free_filespec(p->two);
6973dcae
JH
3836 free(p);
3837}
3838
3839/* This is different from find_unique_abbrev() in that
3840 * it stuffs the result with dots for alignment.
3841 */
3842const char *diff_unique_abbrev(const unsigned char *sha1, int len)
3843{
3844 int abblen;
3845 const char *abbrev;
3846 if (len == 40)
3847 return sha1_to_hex(sha1);
3848
3849 abbrev = find_unique_abbrev(sha1, len);
6973dcae
JH
3850 abblen = strlen(abbrev);
3851 if (abblen < 37) {
3852 static char hex[41];
3853 if (len < abblen && abblen <= len + 2)
3854 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
3855 else
3856 sprintf(hex, "%s...", abbrev);
3857 return hex;
3858 }
3859 return sha1_to_hex(sha1);
3860}
3861
663af342 3862static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
6973dcae 3863{
663af342
PH
3864 int line_termination = opt->line_termination;
3865 int inter_name_termination = line_termination ? '\t' : '\0';
7be57610
BY
3866 if (opt->output_prefix) {
3867 struct strbuf *msg = NULL;
3868 msg = opt->output_prefix(opt, opt->output_prefix_data);
3869 fprintf(opt->file, "%s", msg->buf);
3870 }
6973dcae 3871
663af342 3872 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
c0c77734
DB
3873 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
3874 diff_unique_abbrev(p->one->sha1, opt->abbrev));
3875 fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
6973dcae 3876 }
663af342 3877 if (p->score) {
c0c77734
DB
3878 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
3879 inter_name_termination);
663af342 3880 } else {
c0c77734 3881 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
6973dcae 3882 }
6973dcae 3883
cd676a51
JH
3884 if (p->status == DIFF_STATUS_COPIED ||
3885 p->status == DIFF_STATUS_RENAMED) {
3886 const char *name_a, *name_b;
3887 name_a = p->one->path;
3888 name_b = p->two->path;
3889 strip_prefix(opt->prefix_length, &name_a, &name_b);
c0c77734
DB
3890 write_name_quoted(name_a, opt->file, inter_name_termination);
3891 write_name_quoted(name_b, opt->file, line_termination);
663af342 3892 } else {
cd676a51
JH
3893 const char *name_a, *name_b;
3894 name_a = p->one->mode ? p->one->path : p->two->path;
3895 name_b = NULL;
3896 strip_prefix(opt->prefix_length, &name_a, &name_b);
c0c77734 3897 write_name_quoted(name_a, opt->file, line_termination);
663af342 3898 }
6973dcae
JH
3899}
3900
3901int diff_unmodified_pair(struct diff_filepair *p)
3902{
3903 /* This function is written stricter than necessary to support
3904 * the currently implemented transformers, but the idea is to
3905 * let transformers to produce diff_filepairs any way they want,
3906 * and filter and clean them up here before producing the output.
3907 */
663af342 3908 struct diff_filespec *one = p->one, *two = p->two;
6973dcae
JH
3909
3910 if (DIFF_PAIR_UNMERGED(p))
3911 return 0; /* unmerged is interesting */
3912
6973dcae
JH
3913 /* deletion, addition, mode or type change
3914 * and rename are all interesting.
3915 */
3916 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
3917 DIFF_PAIR_MODE_CHANGED(p) ||
3918 strcmp(one->path, two->path))
3919 return 0;
3920
3921 /* both are valid and point at the same path. that is, we are
3922 * dealing with a change.
3923 */
3924 if (one->sha1_valid && two->sha1_valid &&
85adbf2f
JL
3925 !hashcmp(one->sha1, two->sha1) &&
3926 !one->dirty_submodule && !two->dirty_submodule)
6973dcae
JH
3927 return 1; /* no change */
3928 if (!one->sha1_valid && !two->sha1_valid)
3929 return 1; /* both look at the same file on the filesystem. */
3930 return 0;
3931}
3932
3933static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
3934{
3935 if (diff_unmodified_pair(p))
3936 return;
3937
3938 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3939 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3940 return; /* no tree diffs in patch format */
3941
3942 run_diff(p, o);
3943}
3944
3945static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
3946 struct diffstat_t *diffstat)
3947{
3948 if (diff_unmodified_pair(p))
3949 return;
3950
3951 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3952 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
c3fced64 3953 return; /* no useful stat for tree diffs */
6973dcae
JH
3954
3955 run_diffstat(p, o, diffstat);
3956}
3957
88246898
JS
3958static void diff_flush_checkdiff(struct diff_filepair *p,
3959 struct diff_options *o)
3960{
3961 if (diff_unmodified_pair(p))
3962 return;
3963
3964 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3965 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
c3fced64 3966 return; /* nothing to check in tree diffs */
88246898
JS
3967
3968 run_checkdiff(p, o);
3969}
3970
6973dcae
JH
3971int diff_queue_is_empty(void)
3972{
3973 struct diff_queue_struct *q = &diff_queued_diff;
3974 int i;
3975 for (i = 0; i < q->nr; i++)
3976 if (!diff_unmodified_pair(q->queue[i]))
3977 return 0;
3978 return 1;
3979}
3980
3981#if DIFF_DEBUG
3982void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
3983{
3984 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
3985 x, one ? one : "",
3986 s->path,
3987 DIFF_FILE_VALID(s) ? "valid" : "invalid",
3988 s->mode,
3989 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
3990 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
3991 x, one ? one : "",
3992 s->size, s->xfrm_flags);
3993}
3994
3995void diff_debug_filepair(const struct diff_filepair *p, int i)
3996{
3997 diff_debug_filespec(p->one, i, "one");
3998 diff_debug_filespec(p->two, i, "two");
64479711 3999 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
6973dcae 4000 p->score, p->status ? p->status : '?',
64479711 4001 p->one->rename_used, p->broken_pair);
6973dcae
JH
4002}
4003
4004void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
4005{
4006 int i;
4007 if (msg)
4008 fprintf(stderr, "%s\n", msg);
4009 fprintf(stderr, "q->nr = %d\n", q->nr);
4010 for (i = 0; i < q->nr; i++) {
4011 struct diff_filepair *p = q->queue[i];
4012 diff_debug_filepair(p, i);
4013 }
4014}
4015#endif
4016
4017static void diff_resolve_rename_copy(void)
4018{
64479711
LT
4019 int i;
4020 struct diff_filepair *p;
6973dcae
JH
4021 struct diff_queue_struct *q = &diff_queued_diff;
4022
4023 diff_debug_queue("resolve-rename-copy", q);
4024
4025 for (i = 0; i < q->nr; i++) {
4026 p = q->queue[i];
4027 p->status = 0; /* undecided */
4028 if (DIFF_PAIR_UNMERGED(p))
4029 p->status = DIFF_STATUS_UNMERGED;
4030 else if (!DIFF_FILE_VALID(p->one))
4031 p->status = DIFF_STATUS_ADDED;
4032 else if (!DIFF_FILE_VALID(p->two))
4033 p->status = DIFF_STATUS_DELETED;
4034 else if (DIFF_PAIR_TYPE_CHANGED(p))
4035 p->status = DIFF_STATUS_TYPE_CHANGED;
4036
4037 /* from this point on, we are dealing with a pair
4038 * whose both sides are valid and of the same type, i.e.
4039 * either in-place edit or rename/copy edit.
4040 */
4041 else if (DIFF_PAIR_RENAME(p)) {
64479711
LT
4042 /*
4043 * A rename might have re-connected a broken
4044 * pair up, causing the pathnames to be the
4045 * same again. If so, that's not a rename at
4046 * all, just a modification..
4047 *
4048 * Otherwise, see if this source was used for
4049 * multiple renames, in which case we decrement
4050 * the count, and call it a copy.
6973dcae 4051 */
64479711
LT
4052 if (!strcmp(p->one->path, p->two->path))
4053 p->status = DIFF_STATUS_MODIFIED;
4054 else if (--p->one->rename_used > 0)
6973dcae 4055 p->status = DIFF_STATUS_COPIED;
64479711 4056 else
6973dcae
JH
4057 p->status = DIFF_STATUS_RENAMED;
4058 }
a89fccd2 4059 else if (hashcmp(p->one->sha1, p->two->sha1) ||
d516c2d1 4060 p->one->mode != p->two->mode ||
85adbf2f
JL
4061 p->one->dirty_submodule ||
4062 p->two->dirty_submodule ||
d516c2d1 4063 is_null_sha1(p->one->sha1))
6973dcae
JH
4064 p->status = DIFF_STATUS_MODIFIED;
4065 else {
4066 /* This is a "no-change" entry and should not
4067 * happen anymore, but prepare for broken callers.
4068 */
4069 error("feeding unmodified %s to diffcore",
4070 p->one->path);
4071 p->status = DIFF_STATUS_UNKNOWN;
4072 }
4073 }
4074 diff_debug_queue("resolve-rename-copy done", q);
4075}
4076
c6744349 4077static int check_pair_status(struct diff_filepair *p)
6973dcae 4078{
6973dcae
JH
4079 switch (p->status) {
4080 case DIFF_STATUS_UNKNOWN:
c6744349 4081 return 0;
6973dcae
JH
4082 case 0:
4083 die("internal error in diff-resolve-rename-copy");
6973dcae 4084 default:
c6744349 4085 return 1;
6973dcae
JH
4086 }
4087}
4088
c6744349
TH
4089static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
4090{
4091 int fmt = opt->output_format;
4092
4093 if (fmt & DIFF_FORMAT_CHECKDIFF)
4094 diff_flush_checkdiff(p, opt);
4095 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
4096 diff_flush_raw(p, opt);
cd676a51
JH
4097 else if (fmt & DIFF_FORMAT_NAME) {
4098 const char *name_a, *name_b;
4099 name_a = p->two->path;
4100 name_b = NULL;
4101 strip_prefix(opt->prefix_length, &name_a, &name_b);
c0c77734 4102 write_name_quoted(name_a, opt->file, opt->line_termination);
cd676a51 4103 }
c6744349
TH
4104}
4105
c0c77734 4106static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
4bbd261b
SE
4107{
4108 if (fs->mode)
c0c77734 4109 fprintf(file, " %s mode %06o ", newdelete, fs->mode);
4bbd261b 4110 else
c0c77734
DB
4111 fprintf(file, " %s ", newdelete);
4112 write_name_quoted(fs->path, file, '\n');
4bbd261b
SE
4113}
4114
4115
7be57610
BY
4116static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name,
4117 const char *line_prefix)
4bbd261b
SE
4118{
4119 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
7be57610
BY
4120 fprintf(file, "%s mode change %06o => %06o%c", line_prefix, p->one->mode,
4121 p->two->mode, show_name ? ' ' : '\n');
0d26a64e 4122 if (show_name) {
c0c77734 4123 write_name_quoted(p->two->path, file, '\n');
0d26a64e 4124 }
4bbd261b
SE
4125 }
4126}
4127
7be57610
BY
4128static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p,
4129 const char *line_prefix)
4bbd261b 4130{
b9f44164 4131 char *names = pprint_rename(p->one->path, p->two->path);
4bbd261b 4132
c0c77734 4133 fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
b9f44164 4134 free(names);
7be57610 4135 show_mode_change(file, p, 0, line_prefix);
4bbd261b
SE
4136}
4137
7be57610 4138static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
4bbd261b 4139{
7be57610
BY
4140 FILE *file = opt->file;
4141 char *line_prefix = "";
4142
4143 if (opt->output_prefix) {
4144 struct strbuf *buf = opt->output_prefix(opt, opt->output_prefix_data);
4145 line_prefix = buf->buf;
4146 }
4147
4bbd261b
SE
4148 switch(p->status) {
4149 case DIFF_STATUS_DELETED:
7be57610 4150 fputs(line_prefix, file);
c0c77734 4151 show_file_mode_name(file, "delete", p->one);
4bbd261b
SE
4152 break;
4153 case DIFF_STATUS_ADDED:
7be57610 4154 fputs(line_prefix, file);
c0c77734 4155 show_file_mode_name(file, "create", p->two);
4bbd261b
SE
4156 break;
4157 case DIFF_STATUS_COPIED:
7be57610
BY
4158 fputs(line_prefix, file);
4159 show_rename_copy(file, "copy", p, line_prefix);
4bbd261b
SE
4160 break;
4161 case DIFF_STATUS_RENAMED:
7be57610
BY
4162 fputs(line_prefix, file);
4163 show_rename_copy(file, "rename", p, line_prefix);
4bbd261b
SE
4164 break;
4165 default:
4166 if (p->score) {
7be57610 4167 fprintf(file, "%s rewrite ", line_prefix);
c0c77734
DB
4168 write_name_quoted(p->two->path, file, ' ');
4169 fprintf(file, "(%d%%)\n", similarity_index(p));
663af342 4170 }
7be57610 4171 show_mode_change(file, p, !p->score, line_prefix);
4bbd261b
SE
4172 break;
4173 }
4174}
4175
fcb3d0ad 4176struct patch_id_t {
9126f009 4177 git_SHA_CTX *ctx;
fcb3d0ad
JS
4178 int patchlen;
4179};
4180
4181static int remove_space(char *line, int len)
4182{
4183 int i;
663af342
PH
4184 char *dst = line;
4185 unsigned char c;
fcb3d0ad 4186
663af342
PH
4187 for (i = 0; i < len; i++)
4188 if (!isspace((c = line[i])))
4189 *dst++ = c;
fcb3d0ad 4190
663af342 4191 return dst - line;
fcb3d0ad
JS
4192}
4193
4194static void patch_id_consume(void *priv, char *line, unsigned long len)
4195{
4196 struct patch_id_t *data = priv;
4197 int new_len;
4198
4199 /* Ignore line numbers when computing the SHA1 of the patch */
cc44c765 4200 if (!prefixcmp(line, "@@ -"))
fcb3d0ad
JS
4201 return;
4202
4203 new_len = remove_space(line, len);
4204
9126f009 4205 git_SHA1_Update(data->ctx, line, new_len);
fcb3d0ad
JS
4206 data->patchlen += new_len;
4207}
4208
4209/* returns 0 upon success, and writes result into sha1 */
4210static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
4211{
4212 struct diff_queue_struct *q = &diff_queued_diff;
4213 int i;
9126f009 4214 git_SHA_CTX ctx;
fcb3d0ad
JS
4215 struct patch_id_t data;
4216 char buffer[PATH_MAX * 4 + 20];
4217
9126f009 4218 git_SHA1_Init(&ctx);
fcb3d0ad
JS
4219 memset(&data, 0, sizeof(struct patch_id_t));
4220 data.ctx = &ctx;
fcb3d0ad
JS
4221
4222 for (i = 0; i < q->nr; i++) {
4223 xpparam_t xpp;
4224 xdemitconf_t xecfg;
fcb3d0ad
JS
4225 mmfile_t mf1, mf2;
4226 struct diff_filepair *p = q->queue[i];
4227 int len1, len2;
4228
9ccd0a88 4229 memset(&xpp, 0, sizeof(xpp));
30b25010 4230 memset(&xecfg, 0, sizeof(xecfg));
fcb3d0ad
JS
4231 if (p->status == 0)
4232 return error("internal diff status error");
4233 if (p->status == DIFF_STATUS_UNKNOWN)
4234 continue;
4235 if (diff_unmodified_pair(p))
4236 continue;
4237 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4238 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4239 continue;
4240 if (DIFF_PAIR_UNMERGED(p))
4241 continue;
4242
4243 diff_fill_sha1_info(p->one);
4244 diff_fill_sha1_info(p->two);
4245 if (fill_mmfile(&mf1, p->one) < 0 ||
4246 fill_mmfile(&mf2, p->two) < 0)
4247 return error("unable to read files to diff");
4248
fcb3d0ad
JS
4249 len1 = remove_space(p->one->path, strlen(p->one->path));
4250 len2 = remove_space(p->two->path, strlen(p->two->path));
4251 if (p->one->mode == 0)
4252 len1 = snprintf(buffer, sizeof(buffer),
4253 "diff--gita/%.*sb/%.*s"
4254 "newfilemode%06o"
4255 "---/dev/null"
4256 "+++b/%.*s",
4257 len1, p->one->path,
4258 len2, p->two->path,
4259 p->two->mode,
4260 len2, p->two->path);
4261 else if (p->two->mode == 0)
4262 len1 = snprintf(buffer, sizeof(buffer),
4263 "diff--gita/%.*sb/%.*s"
4264 "deletedfilemode%06o"
4265 "---a/%.*s"
4266 "+++/dev/null",
4267 len1, p->one->path,
4268 len2, p->two->path,
4269 p->one->mode,
4270 len1, p->one->path);
4271 else
4272 len1 = snprintf(buffer, sizeof(buffer),
4273 "diff--gita/%.*sb/%.*s"
4274 "---a/%.*s"
4275 "+++b/%.*s",
4276 len1, p->one->path,
4277 len2, p->two->path,
4278 len1, p->one->path,
4279 len2, p->two->path);
9126f009 4280 git_SHA1_Update(&ctx, buffer, len1);
fcb3d0ad 4281
34597c1f
CB
4282 if (diff_filespec_is_binary(p->one) ||
4283 diff_filespec_is_binary(p->two)) {
4284 git_SHA1_Update(&ctx, sha1_to_hex(p->one->sha1), 40);
4285 git_SHA1_Update(&ctx, sha1_to_hex(p->two->sha1), 40);
4286 continue;
4287 }
4288
582aa00b 4289 xpp.flags = 0;
fcb3d0ad 4290 xecfg.ctxlen = 3;
ad14b450 4291 xecfg.flags = 0;
8a3f524b 4292 xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
dfea7900 4293 &xpp, &xecfg);
fcb3d0ad
JS
4294 }
4295
9126f009 4296 git_SHA1_Final(sha1, &ctx);
fcb3d0ad
JS
4297 return 0;
4298}
4299
4300int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
4301{
4302 struct diff_queue_struct *q = &diff_queued_diff;
4303 int i;
4304 int result = diff_get_patch_id(options, sha1);
4305
4306 for (i = 0; i < q->nr; i++)
4307 diff_free_filepair(q->queue[i]);
4308
4309 free(q->queue);
9ca5df90 4310 DIFF_QUEUE_CLEAR(q);
fcb3d0ad
JS
4311
4312 return result;
4313}
4314
946c3784 4315static int is_summary_empty(const struct diff_queue_struct *q)
6973dcae 4316{
6973dcae 4317 int i;
6973dcae 4318
946c3784
TH
4319 for (i = 0; i < q->nr; i++) {
4320 const struct diff_filepair *p = q->queue[i];
4321
4322 switch (p->status) {
4323 case DIFF_STATUS_DELETED:
4324 case DIFF_STATUS_ADDED:
4325 case DIFF_STATUS_COPIED:
4326 case DIFF_STATUS_RENAMED:
4327 return 0;
4328 default:
4329 if (p->score)
4330 return 0;
4331 if (p->one->mode && p->two->mode &&
4332 p->one->mode != p->two->mode)
4333 return 0;
4334 break;
4335 }
6973dcae 4336 }
946c3784
TH
4337 return 1;
4338}
4339
f31027c9
JH
4340static const char rename_limit_warning[] =
4341"inexact rename detection was skipped due to too many files.";
4342
4343static const char degrade_cc_to_c_warning[] =
4344"only found copies from modified paths due to too many files.";
4345
4346static const char rename_limit_advice[] =
4347"you may want to set your %s variable to at least "
4348"%d and retry the command.";
4349
4350void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
4351{
4352 if (degraded_cc)
4353 warning(degrade_cc_to_c_warning);
4354 else if (needed)
4355 warning(rename_limit_warning);
4356 else
4357 return;
4358 if (0 < needed && needed < 32767)
4359 warning(rename_limit_advice, varname, needed);
4360}
4361
6973dcae
JH
4362void diff_flush(struct diff_options *options)
4363{
4364 struct diff_queue_struct *q = &diff_queued_diff;
c6744349 4365 int i, output_format = options->output_format;
946c3784 4366 int separator = 0;
1c57a627 4367 int dirstat_by_line = 0;
6973dcae 4368
c6744349
TH
4369 /*
4370 * Order: raw, stat, summary, patch
4371 * or: name/name-status/checkdiff (other bits clear)
4372 */
946c3784
TH
4373 if (!q->nr)
4374 goto free_queue;
6973dcae 4375
c6744349
TH
4376 if (output_format & (DIFF_FORMAT_RAW |
4377 DIFF_FORMAT_NAME |
4378 DIFF_FORMAT_NAME_STATUS |
4379 DIFF_FORMAT_CHECKDIFF)) {
6973dcae
JH
4380 for (i = 0; i < q->nr; i++) {
4381 struct diff_filepair *p = q->queue[i];
c6744349
TH
4382 if (check_pair_status(p))
4383 flush_one_pair(p, options);
6973dcae 4384 }
946c3784 4385 separator++;
6973dcae 4386 }
c6744349 4387
1c57a627
JH
4388 if (output_format & DIFF_FORMAT_DIRSTAT && DIFF_OPT_TST(options, DIRSTAT_BY_LINE))
4389 dirstat_by_line = 1;
4390
4391 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
4392 dirstat_by_line) {
5e2b0636 4393 struct diffstat_t diffstat;
c6744349 4394
5e2b0636 4395 memset(&diffstat, 0, sizeof(struct diffstat_t));
6973dcae
JH
4396 for (i = 0; i < q->nr; i++) {
4397 struct diff_filepair *p = q->queue[i];
c6744349 4398 if (check_pair_status(p))
5e2b0636 4399 diff_flush_stat(p, options, &diffstat);
6973dcae 4400 }
74e2abe5
JH
4401 if (output_format & DIFF_FORMAT_NUMSTAT)
4402 show_numstat(&diffstat, options);
4403 if (output_format & DIFF_FORMAT_DIFFSTAT)
4404 show_stats(&diffstat, options);
f604652e 4405 if (output_format & DIFF_FORMAT_SHORTSTAT)
c0c77734 4406 show_shortstats(&diffstat, options);
1c57a627
JH
4407 if (output_format & DIFF_FORMAT_DIRSTAT)
4408 show_dirstat_by_line(&diffstat, options);
f604652e 4409 free_diffstat_info(&diffstat);
3969cf7d 4410 separator++;
6973dcae 4411 }
1c57a627 4412 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
c04a7155 4413 show_dirstat(options);
6973dcae 4414
946c3784 4415 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
7be57610
BY
4416 for (i = 0; i < q->nr; i++) {
4417 diff_summary(options, q->queue[i]);
4418 }
3969cf7d 4419 separator++;
6973dcae
JH
4420 }
4421
6977c250
LA
4422 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
4423 DIFF_OPT_TST(options, EXIT_WITH_STATUS) &&
4424 DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
4425 /*
4426 * run diff_flush_patch for the exit status. setting
4427 * options->file to /dev/null should be safe, becaue we
4428 * aren't supposed to produce any output anyway.
4429 */
4430 if (options->close_file)
4431 fclose(options->file);
4432 options->file = fopen("/dev/null", "w");
4433 if (!options->file)
4434 die_errno("Could not open /dev/null");
4435 options->close_file = 1;
4436 for (i = 0; i < q->nr; i++) {
4437 struct diff_filepair *p = q->queue[i];
4438 if (check_pair_status(p))
4439 diff_flush_patch(p, options);
4440 if (options->found_changes)
4441 break;
4442 }
4443 }
4444
c6744349 4445 if (output_format & DIFF_FORMAT_PATCH) {
946c3784 4446 if (separator) {
b18e97ce
LP
4447 if (options->output_prefix) {
4448 struct strbuf *msg = NULL;
4449 msg = options->output_prefix(options,
4450 options->output_prefix_data);
4451 fwrite(msg->buf, msg->len, 1, stdout);
4452 }
6b2fbaaf 4453 putc(options->line_termination, options->file);
946c3784
TH
4454 if (options->stat_sep) {
4455 /* attach patch instead of inline */
c0c77734 4456 fputs(options->stat_sep, options->file);
946c3784 4457 }
c6744349
TH
4458 }
4459
4460 for (i = 0; i < q->nr; i++) {
4461 struct diff_filepair *p = q->queue[i];
4462 if (check_pair_status(p))
4463 diff_flush_patch(p, options);
4464 }
4bbd261b
SE
4465 }
4466
04245581
JK
4467 if (output_format & DIFF_FORMAT_CALLBACK)
4468 options->format_callback(q, options, options->format_callback_data);
4469
c6744349
TH
4470 for (i = 0; i < q->nr; i++)
4471 diff_free_filepair(q->queue[i]);
946c3784 4472free_queue:
6973dcae 4473 free(q->queue);
9ca5df90 4474 DIFF_QUEUE_CLEAR(q);
c0c77734
DB
4475 if (options->close_file)
4476 fclose(options->file);
f245194f
JH
4477
4478 /*
97bf2a08 4479 * Report the content-level differences with HAS_CHANGES;
f245194f
JH
4480 * diff_addremove/diff_change does not set the bit when
4481 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
4482 */
4483 if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
4484 if (options->found_changes)
4485 DIFF_OPT_SET(options, HAS_CHANGES);
4486 else
4487 DIFF_OPT_CLR(options, HAS_CHANGES);
4488 }
6973dcae
JH
4489}
4490
4491static void diffcore_apply_filter(const char *filter)
4492{
4493 int i;
4494 struct diff_queue_struct *q = &diff_queued_diff;
4495 struct diff_queue_struct outq;
9ca5df90 4496 DIFF_QUEUE_CLEAR(&outq);
6973dcae
JH
4497
4498 if (!filter)
4499 return;
4500
4501 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
4502 int found;
4503 for (i = found = 0; !found && i < q->nr; i++) {
4504 struct diff_filepair *p = q->queue[i];
4505 if (((p->status == DIFF_STATUS_MODIFIED) &&
4506 ((p->score &&
4507 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
4508 (!p->score &&
4509 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
4510 ((p->status != DIFF_STATUS_MODIFIED) &&
4511 strchr(filter, p->status)))
4512 found++;
4513 }
4514 if (found)
4515 return;
4516
4517 /* otherwise we will clear the whole queue
4518 * by copying the empty outq at the end of this
4519 * function, but first clear the current entries
4520 * in the queue.
4521 */
4522 for (i = 0; i < q->nr; i++)
4523 diff_free_filepair(q->queue[i]);
4524 }
4525 else {
4526 /* Only the matching ones */
4527 for (i = 0; i < q->nr; i++) {
4528 struct diff_filepair *p = q->queue[i];
4529
4530 if (((p->status == DIFF_STATUS_MODIFIED) &&
4531 ((p->score &&
4532 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
4533 (!p->score &&
4534 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
4535 ((p->status != DIFF_STATUS_MODIFIED) &&
4536 strchr(filter, p->status)))
4537 diff_q(&outq, p);
4538 else
4539 diff_free_filepair(p);
4540 }
4541 }
4542 free(q->queue);
4543 *q = outq;
4544}
4545
5701115a
SV
4546/* Check whether two filespecs with the same mode and size are identical */
4547static int diff_filespec_is_identical(struct diff_filespec *one,
4548 struct diff_filespec *two)
4549{
2b459b48
JH
4550 if (S_ISGITLINK(one->mode))
4551 return 0;
5701115a
SV
4552 if (diff_populate_filespec(one, 0))
4553 return 0;
4554 if (diff_populate_filespec(two, 0))
4555 return 0;
4556 return !memcmp(one->data, two->data, one->size);
4557}
4558
fb13227e
JH
4559static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
4560{
4561 int i;
4562 struct diff_queue_struct *q = &diff_queued_diff;
4563 struct diff_queue_struct outq;
9ca5df90 4564 DIFF_QUEUE_CLEAR(&outq);
fb13227e
JH
4565
4566 for (i = 0; i < q->nr; i++) {
4567 struct diff_filepair *p = q->queue[i];
4568
4569 /*
9517e6b8 4570 * 1. Entries that come from stat info dirtiness
fb13227e
JH
4571 * always have both sides (iow, not create/delete),
4572 * one side of the object name is unknown, with
4573 * the same mode and size. Keep the ones that
4574 * do not match these criteria. They have real
4575 * differences.
4576 *
4577 * 2. At this point, the file is known to be modified,
4578 * with the same mode and size, and the object
4579 * name of one side is unknown. Need to inspect
4580 * the identical contents.
4581 */
4582 if (!DIFF_FILE_VALID(p->one) || /* (1) */
4583 !DIFF_FILE_VALID(p->two) ||
4584 (p->one->sha1_valid && p->two->sha1_valid) ||
4585 (p->one->mode != p->two->mode) ||
4586 diff_populate_filespec(p->one, 1) ||
4587 diff_populate_filespec(p->two, 1) ||
4588 (p->one->size != p->two->size) ||
5701115a 4589 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
fb13227e
JH
4590 diff_q(&outq, p);
4591 else {
4592 /*
4593 * The caller can subtract 1 from skip_stat_unmatch
4594 * to determine how many paths were dirty only
4595 * due to stat info mismatch.
4596 */
8f67f8ae 4597 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
6d2d9e86 4598 diffopt->skip_stat_unmatch++;
fb13227e
JH
4599 diff_free_filepair(p);
4600 }
4601 }
4602 free(q->queue);
4603 *q = outq;
4604}
4605
730f7284
JH
4606static int diffnamecmp(const void *a_, const void *b_)
4607{
4608 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
4609 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
4610 const char *name_a, *name_b;
4611
4612 name_a = a->one ? a->one->path : a->two->path;
4613 name_b = b->one ? b->one->path : b->two->path;
4614 return strcmp(name_a, name_b);
4615}
4616
4617void diffcore_fix_diff_index(struct diff_options *options)
4618{
4619 struct diff_queue_struct *q = &diff_queued_diff;
4620 qsort(q->queue, q->nr, sizeof(q->queue[0]), diffnamecmp);
4621}
4622
6973dcae
JH
4623void diffcore_std(struct diff_options *options)
4624{
9d865356 4625 if (options->skip_stat_unmatch)
fb13227e 4626 diffcore_skip_stat_unmatch(options);
44c48a90
JH
4627 if (!options->found_follow) {
4628 /* See try_to_follow_renames() in tree-diff.c */
4629 if (options->break_opt != -1)
4630 diffcore_break(options->break_opt);
4631 if (options->detect_rename)
4632 diffcore_rename(options);
4633 if (options->break_opt != -1)
4634 diffcore_merge_broken();
4635 }
6973dcae 4636 if (options->pickaxe)
382f013b 4637 diffcore_pickaxe(options);
6973dcae
JH
4638 if (options->orderfile)
4639 diffcore_order(options->orderfile);
44c48a90
JH
4640 if (!options->found_follow)
4641 /* See try_to_follow_renames() in tree-diff.c */
4642 diff_resolve_rename_copy();
6973dcae 4643 diffcore_apply_filter(options->filter);
68aacb2f 4644
f245194f 4645 if (diff_queued_diff.nr && !DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
8f67f8ae
PH
4646 DIFF_OPT_SET(options, HAS_CHANGES);
4647 else
4648 DIFF_OPT_CLR(options, HAS_CHANGES);
1da6175d 4649
44c48a90 4650 options->found_follow = 0;
6973dcae
JH
4651}
4652
da31b358
JH
4653int diff_result_code(struct diff_options *opt, int status)
4654{
4655 int result = 0;
f31027c9
JH
4656
4657 diff_warn_rename_limit("diff.renamelimit",
4658 opt->needed_rename_limit,
4659 opt->degraded_cc_to_c);
da31b358
JH
4660 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
4661 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
4662 return status;
4663 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
4664 DIFF_OPT_TST(opt, HAS_CHANGES))
4665 result |= 01;
4666 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
4667 DIFF_OPT_TST(opt, CHECK_FAILED))
4668 result |= 02;
4669 return result;
4670}
6973dcae 4671
28b9264d
JH
4672int diff_can_quit_early(struct diff_options *opt)
4673{
4674 return (DIFF_OPT_TST(opt, QUICK) &&
4675 !opt->filter &&
4676 DIFF_OPT_TST(opt, HAS_CHANGES));
4677}
4678
aee9c7d6
JL
4679/*
4680 * Shall changes to this submodule be ignored?
4681 *
4682 * Submodule changes can be configured to be ignored separately for each path,
4683 * but that configuration can be overridden from the command line.
4684 */
4685static int is_submodule_ignored(const char *path, struct diff_options *options)
4686{
4687 int ignored = 0;
4688 unsigned orig_flags = options->flags;
4689 if (!DIFF_OPT_TST(options, OVERRIDE_SUBMODULE_CONFIG))
4690 set_diffopt_flags_from_submodule_config(options, path);
4691 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES))
4692 ignored = 1;
4693 options->flags = orig_flags;
4694 return ignored;
4695}
4696
6973dcae
JH
4697void diff_addremove(struct diff_options *options,
4698 int addremove, unsigned mode,
4699 const unsigned char *sha1,
e5450100 4700 int sha1_valid,
e3d42c47 4701 const char *concatpath, unsigned dirty_submodule)
6973dcae 4702{
6973dcae
JH
4703 struct diff_filespec *one, *two;
4704
aee9c7d6 4705 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
50fd9bd8
JS
4706 return;
4707
6973dcae
JH
4708 /* This may look odd, but it is a preparation for
4709 * feeding "there are unchanged files which should
4710 * not produce diffs, but when you are doing copy
4711 * detection you would need them, so here they are"
4712 * entries to the diff-core. They will be prefixed
4713 * with something like '=' or '*' (I haven't decided
4714 * which but should not make any difference).
a6080a0a 4715 * Feeding the same new and old to diff_change()
6973dcae
JH
4716 * also has the same effect.
4717 * Before the final output happens, they are pruned after
4718 * merged into rename/copy pairs as appropriate.
4719 */
8f67f8ae 4720 if (DIFF_OPT_TST(options, REVERSE_DIFF))
6973dcae
JH
4721 addremove = (addremove == '+' ? '-' :
4722 addremove == '-' ? '+' : addremove);
4723
cd676a51
JH
4724 if (options->prefix &&
4725 strncmp(concatpath, options->prefix, options->prefix_length))
4726 return;
4727
6973dcae
JH
4728 one = alloc_filespec(concatpath);
4729 two = alloc_filespec(concatpath);
4730
4731 if (addremove != '+')
e5450100 4732 fill_filespec(one, sha1, sha1_valid, mode);
e3d42c47 4733 if (addremove != '-') {
e5450100 4734 fill_filespec(two, sha1, sha1_valid, mode);
e3d42c47
JL
4735 two->dirty_submodule = dirty_submodule;
4736 }
6973dcae
JH
4737
4738 diff_queue(&diff_queued_diff, one, two);
f245194f
JH
4739 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
4740 DIFF_OPT_SET(options, HAS_CHANGES);
6973dcae
JH
4741}
4742
4743void diff_change(struct diff_options *options,
4744 unsigned old_mode, unsigned new_mode,
4745 const unsigned char *old_sha1,
4746 const unsigned char *new_sha1,
e5450100 4747 int old_sha1_valid, int new_sha1_valid,
e3d42c47
JL
4748 const char *concatpath,
4749 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
6973dcae 4750{
6973dcae
JH
4751 struct diff_filespec *one, *two;
4752
aee9c7d6
JL
4753 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
4754 is_submodule_ignored(concatpath, options))
50fd9bd8
JS
4755 return;
4756
8f67f8ae 4757 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
6973dcae
JH
4758 unsigned tmp;
4759 const unsigned char *tmp_c;
4760 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
4761 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
e5450100
JK
4762 tmp = old_sha1_valid; old_sha1_valid = new_sha1_valid;
4763 new_sha1_valid = tmp;
e3d42c47
JL
4764 tmp = old_dirty_submodule; old_dirty_submodule = new_dirty_submodule;
4765 new_dirty_submodule = tmp;
6973dcae 4766 }
cd676a51
JH
4767
4768 if (options->prefix &&
4769 strncmp(concatpath, options->prefix, options->prefix_length))
4770 return;
4771
6973dcae
JH
4772 one = alloc_filespec(concatpath);
4773 two = alloc_filespec(concatpath);
e5450100
JK
4774 fill_filespec(one, old_sha1, old_sha1_valid, old_mode);
4775 fill_filespec(two, new_sha1, new_sha1_valid, new_mode);
e3d42c47
JL
4776 one->dirty_submodule = old_dirty_submodule;
4777 two->dirty_submodule = new_dirty_submodule;
6973dcae
JH
4778
4779 diff_queue(&diff_queued_diff, one, two);
f245194f
JH
4780 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
4781 DIFF_OPT_SET(options, HAS_CHANGES);
6973dcae
JH
4782}
4783
fa7b2908 4784struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
6973dcae 4785{
76399c01 4786 struct diff_filepair *pair;
6973dcae 4787 struct diff_filespec *one, *two;
cd676a51
JH
4788
4789 if (options->prefix &&
4790 strncmp(path, options->prefix, options->prefix_length))
76399c01 4791 return NULL;
cd676a51 4792
6973dcae
JH
4793 one = alloc_filespec(path);
4794 two = alloc_filespec(path);
76399c01
JH
4795 pair = diff_queue(&diff_queued_diff, one, two);
4796 pair->is_unmerged = 1;
4797 return pair;
6973dcae 4798}
9cb92c39
JK
4799
4800static char *run_textconv(const char *pgm, struct diff_filespec *spec,
4801 size_t *outsize)
4802{
479b0ae8 4803 struct diff_tempfile *temp;
9cb92c39
JK
4804 const char *argv[3];
4805 const char **arg = argv;
4806 struct child_process child;
4807 struct strbuf buf = STRBUF_INIT;
da1fbed3 4808 int err = 0;
9cb92c39 4809
479b0ae8 4810 temp = prepare_temp_file(spec->path, spec);
9cb92c39 4811 *arg++ = pgm;
479b0ae8 4812 *arg++ = temp->name;
9cb92c39
JK
4813 *arg = NULL;
4814
4815 memset(&child, 0, sizeof(child));
41a457e4 4816 child.use_shell = 1;
9cb92c39
JK
4817 child.argv = argv;
4818 child.out = -1;
da1fbed3 4819 if (start_command(&child)) {
479b0ae8 4820 remove_tempfile();
9cb92c39
JK
4821 return NULL;
4822 }
da1fbed3
JS
4823
4824 if (strbuf_read(&buf, child.out, 0) < 0)
4825 err = error("error reading from textconv command '%s'", pgm);
70d70999 4826 close(child.out);
da1fbed3
JS
4827
4828 if (finish_command(&child) || err) {
4829 strbuf_release(&buf);
4830 remove_tempfile();
4831 return NULL;
4832 }
479b0ae8 4833 remove_tempfile();
9cb92c39
JK
4834
4835 return strbuf_detach(&buf, outsize);
4836}
840383b2 4837
a788d7d5
AB
4838size_t fill_textconv(struct userdiff_driver *driver,
4839 struct diff_filespec *df,
4840 char **outbuf)
840383b2
JK
4841{
4842 size_t size;
4843
d9bae1a1 4844 if (!driver || !driver->textconv) {
840383b2
JK
4845 if (!DIFF_FILE_VALID(df)) {
4846 *outbuf = "";
4847 return 0;
4848 }
4849 if (diff_populate_filespec(df, 0))
4850 die("unable to read files to diff");
4851 *outbuf = df->data;
4852 return df->size;
4853 }
4854
9ec09b04 4855 if (driver->textconv_cache && df->sha1_valid) {
d9bae1a1
JK
4856 *outbuf = notes_cache_get(driver->textconv_cache, df->sha1,
4857 &size);
4858 if (*outbuf)
4859 return size;
4860 }
4861
4862 *outbuf = run_textconv(driver->textconv, df, &size);
840383b2
JK
4863 if (!*outbuf)
4864 die("unable to read files to diff");
d9bae1a1 4865
9ec09b04 4866 if (driver->textconv_cache && df->sha1_valid) {
d9bae1a1
JK
4867 /* ignore errors, as we might be in a readonly repository */
4868 notes_cache_put(driver->textconv_cache, df->sha1, *outbuf,
4869 size);
4870 /*
4871 * we could save up changes and flush them all at the end,
4872 * but we would need an extra call after all diffing is done.
4873 * Since generating a cache entry is the slow path anyway,
4874 * this extra overhead probably isn't a big deal.
4875 */
4876 notes_cache_write(driver->textconv_cache);
4877 }
4878
840383b2
JK
4879 return size;
4880}