]> git.ipfire.org Git - thirdparty/git.git/blame - diff.c
diff: introduce diff.submodule configuration variable
[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
c47ef57c
RR
124static int parse_submodule_params(struct diff_options *options, const char *value)
125{
126 if (!strcmp(value, "log"))
127 DIFF_OPT_SET(options, SUBMODULE_LOG);
128 else if (!strcmp(value, "short"))
129 DIFF_OPT_CLR(options, SUBMODULE_LOG);
130 else
131 return -1;
132 return 0;
133}
134
cced5fbc
LT
135static int git_config_rename(const char *var, const char *value)
136{
137 if (!value)
138 return DIFF_DETECT_RENAME;
139 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
140 return DIFF_DETECT_COPY;
141 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
142}
143
83ad63cf
JH
144/*
145 * These are to give UI layer defaults.
146 * The core-level commands such as git-diff-files should
147 * never be affected by the setting of diff.renames
148 * the user happens to have in the configuration file.
149 */
ef90d6d4 150int git_diff_ui_config(const char *var, const char *value, void *cb)
801235c5 151{
a159ca0c 152 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
e269eb79 153 diff_use_color_default = git_config_colorbool(var, value);
801235c5
JH
154 return 0;
155 }
6468a4e5
JM
156 if (!strcmp(var, "diff.context")) {
157 diff_context_default = git_config_int(var, value);
158 if (diff_context_default < 0)
159 return -1;
160 return 0;
161 }
b68ea12e 162 if (!strcmp(var, "diff.renames")) {
cced5fbc 163 diff_detect_rename_default = git_config_rename(var, value);
b68ea12e
EW
164 return 0;
165 }
aecbf914
JH
166 if (!strcmp(var, "diff.autorefreshindex")) {
167 diff_auto_refresh_index = git_config_bool(var, value);
168 return 0;
169 }
a5a818ee
JH
170 if (!strcmp(var, "diff.mnemonicprefix")) {
171 diff_mnemonic_prefix = git_config_bool(var, value);
172 return 0;
173 }
f89504dd
EC
174 if (!strcmp(var, "diff.noprefix")) {
175 diff_no_prefix = git_config_bool(var, value);
176 return 0;
177 }
df44483a
ZJS
178 if (!strcmp(var, "diff.statgraphwidth")) {
179 diff_stat_graph_width = git_config_int(var, value);
180 return 0;
181 }
daec808c
BH
182 if (!strcmp(var, "diff.external"))
183 return git_config_string(&external_diff_cmd_cfg, var, value);
98a4d87b
BSSJ
184 if (!strcmp(var, "diff.wordregex"))
185 return git_config_string(&diff_word_regex_cfg, var, value);
f1af60bd 186
be4f2b40
JS
187 if (!strcmp(var, "diff.ignoresubmodules"))
188 handle_ignore_submodules_arg(&default_diff_options, value);
189
c47ef57c
RR
190 if (!strcmp(var, "diff.submodule")) {
191 if (parse_submodule_params(&default_diff_options, value))
192 warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
193 value);
194 return 0;
195 }
196
3e1dd17a
JK
197 if (git_color_config(var, value, cb) < 0)
198 return -1;
199
ef90d6d4 200 return git_diff_basic_config(var, value, cb);
9a1805a8
JK
201}
202
ef90d6d4 203int git_diff_basic_config(const char *var, const char *value, void *cb)
9a1805a8 204{
2b6ca6df
LT
205 if (!strcmp(var, "diff.renamelimit")) {
206 diff_rename_limit_default = git_config_int(var, value);
207 return 0;
208 }
209
6680a087
JK
210 if (userdiff_config(var, value) < 0)
211 return -1;
c7534ef4 212
1968d77d 213 if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
801235c5 214 int slot = parse_diff_color_slot(var, 11);
8b8e8624
JK
215 if (slot < 0)
216 return 0;
64f30e94
JH
217 if (!value)
218 return config_error_nonbool(var);
7c92fe0e 219 color_parse(value, var, diff_colors[slot]);
801235c5
JH
220 return 0;
221 }
f1af60bd 222
a624eaa7 223 /* like GNU diff's --suppress-blank-empty option */
950db879
JS
224 if (!strcmp(var, "diff.suppressblankempty") ||
225 /* for backwards compatibility */
226 !strcmp(var, "diff.suppress-blank-empty")) {
a624eaa7
JM
227 diff_suppress_blank_empty = git_config_bool(var, value);
228 return 0;
229 }
230
2d174951 231 if (!strcmp(var, "diff.dirstat")) {
51670fc8 232 struct strbuf errmsg = STRBUF_INIT;
712d2c7d 233 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
51670fc8 234 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
7478ac57 235 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
51670fc8
JH
236 errmsg.buf);
237 strbuf_release(&errmsg);
712d2c7d 238 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
2d174951
JH
239 return 0;
240 }
241
aee9c7d6
JL
242 if (!prefixcmp(var, "submodule."))
243 return parse_submodule_config_option(var, value);
244
3e1dd17a 245 return git_default_config(var, value, cb);
801235c5
JH
246}
247
6973dcae
JH
248static char *quote_two(const char *one, const char *two)
249{
250 int need_one = quote_c_style(one, NULL, NULL, 1);
251 int need_two = quote_c_style(two, NULL, NULL, 1);
f285a2d7 252 struct strbuf res = STRBUF_INIT;
6973dcae
JH
253
254 if (need_one + need_two) {
663af342
PH
255 strbuf_addch(&res, '"');
256 quote_c_style(one, &res, NULL, 1);
257 quote_c_style(two, &res, NULL, 1);
258 strbuf_addch(&res, '"');
259 } else {
260 strbuf_addstr(&res, one);
261 strbuf_addstr(&res, two);
6973dcae 262 }
b315c5c0 263 return strbuf_detach(&res, NULL);
6973dcae
JH
264}
265
266static const char *external_diff(void)
267{
268 static const char *external_diff_cmd = NULL;
269 static int done_preparing = 0;
270
271 if (done_preparing)
272 return external_diff_cmd;
273 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
cbe02100
JS
274 if (!external_diff_cmd)
275 external_diff_cmd = external_diff_cmd_cfg;
6973dcae
JH
276 done_preparing = 1;
277 return external_diff_cmd;
278}
279
6973dcae
JH
280static struct diff_tempfile {
281 const char *name; /* filename external diff should read from */
282 char hex[41];
283 char mode[10];
1472966c 284 char tmp_path[PATH_MAX];
6973dcae
JH
285} diff_temp[2];
286
6957eb9a
JH
287typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
288
289struct emit_callback {
6957eb9a
JH
290 int color_diff;
291 unsigned ws_rule;
292 int blank_at_eof_in_preimage;
293 int blank_at_eof_in_postimage;
294 int lno_in_preimage;
295 int lno_in_postimage;
296 sane_truncate_fn truncate;
297 const char **label_path;
298 struct diff_words_data *diff_words;
a3c158d4 299 struct diff_options *opt;
6957eb9a 300 int *found_changesp;
3e97c7c6 301 struct strbuf *header;
6957eb9a
JH
302};
303
6973dcae
JH
304static int count_lines(const char *data, int size)
305{
306 int count, ch, completely_empty = 1, nl_just_seen = 0;
307 count = 0;
308 while (0 < size--) {
309 ch = *data++;
310 if (ch == '\n') {
311 count++;
312 nl_just_seen = 1;
313 completely_empty = 0;
314 }
315 else {
316 nl_just_seen = 0;
317 completely_empty = 0;
318 }
319 }
320 if (completely_empty)
321 return 0;
322 if (!nl_just_seen)
323 count++; /* no trailing newline */
324 return count;
325}
326
6957eb9a
JH
327static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
328{
329 if (!DIFF_FILE_VALID(one)) {
330 mf->ptr = (char *)""; /* does not matter */
331 mf->size = 0;
332 return 0;
333 }
334 else if (diff_populate_filespec(one, 0))
335 return -1;
bb35fefb 336
6957eb9a
JH
337 mf->ptr = one->data;
338 mf->size = one->size;
339 return 0;
340}
341
abb371a1
JK
342/* like fill_mmfile, but only for size, so we can avoid retrieving blob */
343static unsigned long diff_filespec_size(struct diff_filespec *one)
344{
345 if (!DIFF_FILE_VALID(one))
346 return 0;
347 diff_populate_filespec(one, 1);
348 return one->size;
349}
350
6957eb9a
JH
351static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
352{
353 char *ptr = mf->ptr;
354 long size = mf->size;
355 int cnt = 0;
356
357 if (!size)
358 return cnt;
359 ptr += size - 1; /* pointing at the very end */
360 if (*ptr != '\n')
361 ; /* incomplete line */
362 else
363 ptr--; /* skip the last LF */
364 while (mf->ptr < ptr) {
365 char *prev_eol;
366 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
367 if (*prev_eol == '\n')
368 break;
369 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
370 break;
371 cnt++;
372 ptr = prev_eol - 1;
373 }
374 return cnt;
375}
376
377static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
378 struct emit_callback *ecbdata)
379{
380 int l1, l2, at;
381 unsigned ws_rule = ecbdata->ws_rule;
382 l1 = count_trailing_blank(mf1, ws_rule);
383 l2 = count_trailing_blank(mf2, ws_rule);
384 if (l2 <= l1) {
385 ecbdata->blank_at_eof_in_preimage = 0;
386 ecbdata->blank_at_eof_in_postimage = 0;
387 return;
388 }
389 at = count_lines(mf1->ptr, mf1->size);
390 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
391
392 at = count_lines(mf2->ptr, mf2->size);
393 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
394}
395
a3c158d4 396static void emit_line_0(struct diff_options *o, const char *set, const char *reset,
250f7993 397 int first, const char *line, int len)
6957eb9a
JH
398{
399 int has_trailing_newline, has_trailing_carriage_return;
250f7993 400 int nofirst;
a3c158d4
BY
401 FILE *file = o->file;
402
403 if (o->output_prefix) {
404 struct strbuf *msg = NULL;
405 msg = o->output_prefix(o, o->output_prefix_data);
406 assert(msg);
407 fwrite(msg->buf, msg->len, 1, file);
408 }
6957eb9a 409
250f7993
JH
410 if (len == 0) {
411 has_trailing_newline = (first == '\n');
412 has_trailing_carriage_return = (!has_trailing_newline &&
413 (first == '\r'));
414 nofirst = has_trailing_newline || has_trailing_carriage_return;
415 } else {
416 has_trailing_newline = (len > 0 && line[len-1] == '\n');
417 if (has_trailing_newline)
418 len--;
419 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
420 if (has_trailing_carriage_return)
421 len--;
422 nofirst = 0;
423 }
6957eb9a 424
06a47552
JH
425 if (len || !nofirst) {
426 fputs(set, file);
427 if (!nofirst)
428 fputc(first, file);
429 fwrite(line, len, 1, file);
430 fputs(reset, file);
431 }
6957eb9a
JH
432 if (has_trailing_carriage_return)
433 fputc('\r', file);
434 if (has_trailing_newline)
435 fputc('\n', file);
436}
437
a3c158d4 438static void emit_line(struct diff_options *o, const char *set, const char *reset,
250f7993
JH
439 const char *line, int len)
440{
a3c158d4 441 emit_line_0(o, set, reset, line[0], line+1, len-1);
250f7993
JH
442}
443
6957eb9a
JH
444static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
445{
446 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
447 ecbdata->blank_at_eof_in_preimage &&
448 ecbdata->blank_at_eof_in_postimage &&
449 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
450 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
451 return 0;
018cff70 452 return ws_blank_line(line, len, ecbdata->ws_rule);
6957eb9a
JH
453}
454
018cff70
JH
455static void emit_add_line(const char *reset,
456 struct emit_callback *ecbdata,
457 const char *line, int len)
6957eb9a
JH
458{
459 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
460 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
461
462 if (!*ws)
a3c158d4 463 emit_line_0(ecbdata->opt, set, reset, '+', line, len);
6957eb9a
JH
464 else if (new_blank_line_at_eof(ecbdata, line, len))
465 /* Blank line at EOF - paint '+' as well */
a3c158d4 466 emit_line_0(ecbdata->opt, ws, reset, '+', line, len);
6957eb9a
JH
467 else {
468 /* Emit just the prefix, then the rest. */
a3c158d4 469 emit_line_0(ecbdata->opt, set, reset, '+', "", 0);
018cff70 470 ws_check_emit(line, len, ecbdata->ws_rule,
a3c158d4 471 ecbdata->opt->file, set, reset, ws);
6957eb9a
JH
472 }
473}
474
89cb73a1
BW
475static void emit_hunk_header(struct emit_callback *ecbdata,
476 const char *line, int len)
477{
478 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
479 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
480 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
481 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
482 static const char atat[2] = { '@', '@' };
483 const char *cp, *ep;
2efcc977
BY
484 struct strbuf msgbuf = STRBUF_INIT;
485 int org_len = len;
486 int i = 1;
89cb73a1
BW
487
488 /*
489 * As a hunk header must begin with "@@ -<old>, +<new> @@",
490 * it always is at least 10 bytes long.
491 */
492 if (len < 10 ||
493 memcmp(line, atat, 2) ||
494 !(ep = memmem(line + 2, len - 2, atat, 2))) {
a3c158d4 495 emit_line(ecbdata->opt, plain, reset, line, len);
89cb73a1
BW
496 return;
497 }
498 ep += 2; /* skip over @@ */
499
500 /* The hunk header in fraginfo color */
2efcc977
BY
501 strbuf_add(&msgbuf, frag, strlen(frag));
502 strbuf_add(&msgbuf, line, ep - line);
503 strbuf_add(&msgbuf, reset, strlen(reset));
504
505 /*
506 * trailing "\r\n"
507 */
508 for ( ; i < 3; i++)
509 if (line[len - i] == '\r' || line[len - i] == '\n')
510 len--;
89cb73a1
BW
511
512 /* blank before the func header */
513 for (cp = ep; ep - line < len; ep++)
514 if (*ep != ' ' && *ep != '\t')
515 break;
2efcc977
BY
516 if (ep != cp) {
517 strbuf_add(&msgbuf, plain, strlen(plain));
518 strbuf_add(&msgbuf, cp, ep - cp);
519 strbuf_add(&msgbuf, reset, strlen(reset));
520 }
521
522 if (ep < line + len) {
523 strbuf_add(&msgbuf, func, strlen(func));
524 strbuf_add(&msgbuf, ep, line + len - ep);
525 strbuf_add(&msgbuf, reset, strlen(reset));
526 }
89cb73a1 527
2efcc977
BY
528 strbuf_add(&msgbuf, line + len, org_len - len);
529 emit_line(ecbdata->opt, "", "", msgbuf.buf, msgbuf.len);
530 strbuf_release(&msgbuf);
89cb73a1
BW
531}
532
479b0ae8
JK
533static struct diff_tempfile *claim_diff_tempfile(void) {
534 int i;
535 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
536 if (!diff_temp[i].name)
537 return diff_temp + i;
538 die("BUG: diff is failing to clean up its tempfiles");
539}
540
541static int remove_tempfile_installed;
542
543static void remove_tempfile(void)
544{
545 int i;
a8344abe
NR
546 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
547 if (diff_temp[i].name == diff_temp[i].tmp_path)
691f1a28 548 unlink_or_warn(diff_temp[i].name);
a8344abe
NR
549 diff_temp[i].name = NULL;
550 }
479b0ae8
JK
551}
552
553static void remove_tempfile_on_signal(int signo)
554{
555 remove_tempfile();
4a16d072 556 sigchain_pop(signo);
479b0ae8
JK
557 raise(signo);
558}
559
c0c77734 560static void print_line_count(FILE *file, int count)
6973dcae
JH
561{
562 switch (count) {
563 case 0:
c0c77734 564 fprintf(file, "0,0");
6973dcae
JH
565 break;
566 case 1:
c0c77734 567 fprintf(file, "1");
6973dcae
JH
568 break;
569 default:
c0c77734 570 fprintf(file, "1,%d", count);
6973dcae
JH
571 break;
572 }
573}
574
7f7ee2ff
JH
575static void emit_rewrite_lines(struct emit_callback *ecb,
576 int prefix, const char *data, int size)
6973dcae 577{
7f7ee2ff
JH
578 const char *endp = NULL;
579 static const char *nneof = " No newline at end of file\n";
580 const char *old = diff_get_color(ecb->color_diff, DIFF_FILE_OLD);
581 const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
582
583 while (0 < size) {
584 int len;
585
586 endp = memchr(data, '\n', size);
587 len = endp ? (endp - data + 1) : size;
588 if (prefix != '+') {
589 ecb->lno_in_preimage++;
a3c158d4 590 emit_line_0(ecb->opt, old, reset, '-',
7f7ee2ff
JH
591 data, len);
592 } else {
593 ecb->lno_in_postimage++;
594 emit_add_line(reset, ecb, data, len);
13e36ec5 595 }
7f7ee2ff
JH
596 size -= len;
597 data += len;
598 }
599 if (!endp) {
600 const char *plain = diff_get_color(ecb->color_diff,
601 DIFF_PLAIN);
35e2d03c 602 putc('\n', ecb->opt->file);
a3c158d4 603 emit_line_0(ecb->opt, plain, reset, '\\',
7f7ee2ff 604 nneof, strlen(nneof));
6973dcae 605 }
6973dcae
JH
606}
607
608static void emit_rewrite_diff(const char *name_a,
609 const char *name_b,
610 struct diff_filespec *one,
13e36ec5 611 struct diff_filespec *two,
d9bae1a1
JK
612 struct userdiff_driver *textconv_one,
613 struct userdiff_driver *textconv_two,
eab9a40b 614 struct diff_options *o)
6973dcae
JH
615{
616 int lc_a, lc_b;
1a9eb3b9 617 const char *name_a_tab, *name_b_tab;
f1c96261
JK
618 const char *metainfo = diff_get_color(o->use_color, DIFF_METAINFO);
619 const char *fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
620 const char *reset = diff_get_color(o->use_color, DIFF_RESET);
d5625091 621 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
a5a818ee 622 const char *a_prefix, *b_prefix;
840383b2 623 char *data_one, *data_two;
3aa1f7ca 624 size_t size_one, size_two;
7f7ee2ff 625 struct emit_callback ecbdata;
7be57610
BY
626 char *line_prefix = "";
627 struct strbuf *msgbuf;
628
629 if (o && o->output_prefix) {
630 msgbuf = o->output_prefix(o, o->output_prefix_data);
631 line_prefix = msgbuf->buf;
632 }
a5a818ee
JH
633
634 if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
635 a_prefix = o->b_prefix;
636 b_prefix = o->a_prefix;
637 } else {
638 a_prefix = o->a_prefix;
639 b_prefix = o->b_prefix;
640 }
1a9eb3b9 641
8a13becc
JH
642 name_a += (*name_a == '/');
643 name_b += (*name_b == '/');
1a9eb3b9
JH
644 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
645 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
646
d5625091
JH
647 strbuf_reset(&a_name);
648 strbuf_reset(&b_name);
a5a818ee
JH
649 quote_two_c_style(&a_name, a_prefix, name_a, 0);
650 quote_two_c_style(&b_name, b_prefix, name_b, 0);
d5625091 651
840383b2
JK
652 size_one = fill_textconv(textconv_one, one, &data_one);
653 size_two = fill_textconv(textconv_two, two, &data_two);
3aa1f7ca 654
d91ba8fa 655 memset(&ecbdata, 0, sizeof(ecbdata));
daa0c3d9 656 ecbdata.color_diff = want_color(o->use_color);
d91ba8fa
JH
657 ecbdata.found_changesp = &o->found_changes;
658 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
a3c158d4 659 ecbdata.opt = o;
d91ba8fa
JH
660 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
661 mmfile_t mf1, mf2;
662 mf1.ptr = (char *)data_one;
663 mf2.ptr = (char *)data_two;
664 mf1.size = size_one;
665 mf2.size = size_two;
666 check_blank_at_eof(&mf1, &mf2, &ecbdata);
667 }
668 ecbdata.lno_in_preimage = 1;
669 ecbdata.lno_in_postimage = 1;
670
3aa1f7ca
JK
671 lc_a = count_lines(data_one, size_one);
672 lc_b = count_lines(data_two, size_two);
c0c77734 673 fprintf(o->file,
7be57610
BY
674 "%s%s--- %s%s%s\n%s%s+++ %s%s%s\n%s%s@@ -",
675 line_prefix, metainfo, a_name.buf, name_a_tab, reset,
676 line_prefix, metainfo, b_name.buf, name_b_tab, reset,
677 line_prefix, fraginfo);
467ddc14
JH
678 if (!o->irreversible_delete)
679 print_line_count(o->file, lc_a);
680 else
681 fprintf(o->file, "?,?");
c0c77734
DB
682 fprintf(o->file, " +");
683 print_line_count(o->file, lc_b);
684 fprintf(o->file, " @@%s\n", reset);
467ddc14 685 if (lc_a && !o->irreversible_delete)
d91ba8fa 686 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
6973dcae 687 if (lc_b)
d91ba8fa 688 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
b76c056b 689 if (textconv_one)
aed6ca52 690 free((char *)data_one);
b76c056b 691 if (textconv_two)
aed6ca52 692 free((char *)data_two);
6973dcae
JH
693}
694
f59a59e2
JS
695struct diff_words_buffer {
696 mmfile_t text;
697 long alloc;
2e5d2003
JS
698 struct diff_words_orig {
699 const char *begin, *end;
700 } *orig;
701 int orig_nr, orig_alloc;
f59a59e2
JS
702};
703
704static void diff_words_append(char *line, unsigned long len,
705 struct diff_words_buffer *buffer)
706{
23c1575f 707 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
f59a59e2
JS
708 line++;
709 len--;
710 memcpy(buffer->text.ptr + buffer->text.size, line, len);
711 buffer->text.size += len;
2b6a5417 712 buffer->text.ptr[buffer->text.size] = '\0';
f59a59e2
JS
713}
714
9cba13ca 715struct diff_words_style_elem {
882749a0
TR
716 const char *prefix;
717 const char *suffix;
718 const char *color; /* NULL; filled in by the setup code if
719 * color is enabled */
720};
721
9cba13ca 722struct diff_words_style {
882749a0
TR
723 enum diff_words_type type;
724 struct diff_words_style_elem new, old, ctx;
725 const char *newline;
726};
727
c2e86add 728static struct diff_words_style diff_words_styles[] = {
882749a0
TR
729 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
730 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
731 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
732};
733
f59a59e2 734struct diff_words_data {
f59a59e2 735 struct diff_words_buffer minus, plus;
2e5d2003 736 const char *current_plus;
4297c0ae
BY
737 int last_minus;
738 struct diff_options *opt;
2b6a5417 739 regex_t *word_regex;
882749a0
TR
740 enum diff_words_type type;
741 struct diff_words_style *style;
f59a59e2
JS
742};
743
882749a0
TR
744static int fn_out_diff_words_write_helper(FILE *fp,
745 struct diff_words_style_elem *st_el,
746 const char *newline,
4297c0ae
BY
747 size_t count, const char *buf,
748 const char *line_prefix)
882749a0 749{
4297c0ae
BY
750 int print = 0;
751
882749a0
TR
752 while (count) {
753 char *p = memchr(buf, '\n', count);
4297c0ae
BY
754 if (print)
755 fputs(line_prefix, fp);
882749a0
TR
756 if (p != buf) {
757 if (st_el->color && fputs(st_el->color, fp) < 0)
758 return -1;
759 if (fputs(st_el->prefix, fp) < 0 ||
760 fwrite(buf, p ? p - buf : count, 1, fp) != 1 ||
761 fputs(st_el->suffix, fp) < 0)
762 return -1;
763 if (st_el->color && *st_el->color
764 && fputs(GIT_COLOR_RESET, fp) < 0)
765 return -1;
766 }
767 if (!p)
768 return 0;
769 if (fputs(newline, fp) < 0)
770 return -1;
771 count -= p + 1 - buf;
772 buf = p + 1;
4297c0ae 773 print = 1;
882749a0
TR
774 }
775 return 0;
776}
777
4297c0ae
BY
778/*
779 * '--color-words' algorithm can be described as:
780 *
781 * 1. collect a the minus/plus lines of a diff hunk, divided into
782 * minus-lines and plus-lines;
783 *
784 * 2. break both minus-lines and plus-lines into words and
785 * place them into two mmfile_t with one word for each line;
786 *
787 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
788 *
789 * And for the common parts of the both file, we output the plus side text.
790 * diff_words->current_plus is used to trace the current position of the plus file
791 * which printed. diff_words->last_minus is used to trace the last minus word
792 * printed.
793 *
794 * For '--graph' to work with '--color-words', we need to output the graph prefix
795 * on each line of color words output. Generally, there are two conditions on
796 * which we should output the prefix.
797 *
798 * 1. diff_words->last_minus == 0 &&
799 * diff_words->current_plus == diff_words->plus.text.ptr
800 *
801 * that is: the plus text must start as a new line, and if there is no minus
802 * word printed, a graph prefix must be printed.
803 *
804 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
805 * *(diff_words->current_plus - 1) == '\n'
806 *
807 * that is: a graph prefix must be printed following a '\n'
808 */
809static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
810{
811 if ((diff_words->last_minus == 0 &&
812 diff_words->current_plus == diff_words->plus.text.ptr) ||
813 (diff_words->current_plus > diff_words->plus.text.ptr &&
814 *(diff_words->current_plus - 1) == '\n')) {
815 return 1;
816 } else {
817 return 0;
818 }
819}
820
f59a59e2 821static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
f59a59e2 822{
f59a59e2 823 struct diff_words_data *diff_words = priv;
882749a0 824 struct diff_words_style *style = diff_words->style;
2e5d2003
JS
825 int minus_first, minus_len, plus_first, plus_len;
826 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
4297c0ae
BY
827 struct diff_options *opt = diff_words->opt;
828 struct strbuf *msgbuf;
829 char *line_prefix = "";
f59a59e2 830
2e5d2003
JS
831 if (line[0] != '@' || parse_hunk_header(line, len,
832 &minus_first, &minus_len, &plus_first, &plus_len))
f59a59e2
JS
833 return;
834
4297c0ae
BY
835 assert(opt);
836 if (opt->output_prefix) {
837 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
838 line_prefix = msgbuf->buf;
839 }
840
2e5d2003
JS
841 /* POSIX requires that first be decremented by one if len == 0... */
842 if (minus_len) {
843 minus_begin = diff_words->minus.orig[minus_first].begin;
844 minus_end =
845 diff_words->minus.orig[minus_first + minus_len - 1].end;
846 } else
847 minus_begin = minus_end =
848 diff_words->minus.orig[minus_first].end;
849
850 if (plus_len) {
851 plus_begin = diff_words->plus.orig[plus_first].begin;
852 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
853 } else
854 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
855
4297c0ae
BY
856 if (color_words_output_graph_prefix(diff_words)) {
857 fputs(line_prefix, diff_words->opt->file);
858 }
859 if (diff_words->current_plus != plus_begin) {
860 fn_out_diff_words_write_helper(diff_words->opt->file,
882749a0
TR
861 &style->ctx, style->newline,
862 plus_begin - diff_words->current_plus,
4297c0ae
BY
863 diff_words->current_plus, line_prefix);
864 if (*(plus_begin - 1) == '\n')
865 fputs(line_prefix, diff_words->opt->file);
866 }
867 if (minus_begin != minus_end) {
868 fn_out_diff_words_write_helper(diff_words->opt->file,
882749a0 869 &style->old, style->newline,
4297c0ae
BY
870 minus_end - minus_begin, minus_begin,
871 line_prefix);
872 }
873 if (plus_begin != plus_end) {
874 fn_out_diff_words_write_helper(diff_words->opt->file,
882749a0 875 &style->new, style->newline,
4297c0ae
BY
876 plus_end - plus_begin, plus_begin,
877 line_prefix);
878 }
2e5d2003
JS
879
880 diff_words->current_plus = plus_end;
4297c0ae 881 diff_words->last_minus = minus_first;
f59a59e2
JS
882}
883
2b6a5417
JS
884/* This function starts looking at *begin, and returns 0 iff a word was found. */
885static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
886 int *begin, int *end)
887{
888 if (word_regex && *begin < buffer->size) {
889 regmatch_t match[1];
890 if (!regexec(word_regex, buffer->ptr + *begin, 1, match, 0)) {
891 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
892 '\n', match[0].rm_eo - match[0].rm_so);
893 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
894 *begin += match[0].rm_so;
895 return *begin >= *end;
896 }
897 return -1;
f59a59e2
JS
898 }
899
2b6a5417
JS
900 /* find the next word */
901 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
902 (*begin)++;
903 if (*begin >= buffer->size)
904 return -1;
f59a59e2 905
2b6a5417
JS
906 /* find the end of the word */
907 *end = *begin + 1;
908 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
909 (*end)++;
910
911 return 0;
f59a59e2
JS
912}
913
23c1575f 914/*
2e5d2003
JS
915 * This function splits the words in buffer->text, stores the list with
916 * newline separator into out, and saves the offsets of the original words
917 * in buffer->orig.
23c1575f 918 */
2b6a5417
JS
919static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
920 regex_t *word_regex)
f59a59e2 921{
2e5d2003 922 int i, j;
2b6a5417 923 long alloc = 0;
f59a59e2 924
2e5d2003 925 out->size = 0;
2b6a5417 926 out->ptr = NULL;
f59a59e2 927
2e5d2003
JS
928 /* fake an empty "0th" word */
929 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
930 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
931 buffer->orig_nr = 1;
932
933 for (i = 0; i < buffer->text.size; i++) {
2b6a5417
JS
934 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
935 return;
2e5d2003
JS
936
937 /* store original boundaries */
938 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
939 buffer->orig_alloc);
940 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
941 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
942 buffer->orig_nr++;
943
944 /* store one word */
2b6a5417 945 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
2e5d2003
JS
946 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
947 out->ptr[out->size + j - i] = '\n';
948 out->size += j - i + 1;
949
950 i = j - 1;
f59a59e2
JS
951 }
952}
953
954/* this executes the word diff on the accumulated buffers */
955static void diff_words_show(struct diff_words_data *diff_words)
956{
957 xpparam_t xpp;
958 xdemitconf_t xecfg;
f59a59e2 959 mmfile_t minus, plus;
882749a0 960 struct diff_words_style *style = diff_words->style;
f59a59e2 961
4297c0ae
BY
962 struct diff_options *opt = diff_words->opt;
963 struct strbuf *msgbuf;
964 char *line_prefix = "";
965
966 assert(opt);
967 if (opt->output_prefix) {
968 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
969 line_prefix = msgbuf->buf;
970 }
971
2e5d2003
JS
972 /* special case: only removal */
973 if (!diff_words->plus.text.size) {
4297c0ae
BY
974 fputs(line_prefix, diff_words->opt->file);
975 fn_out_diff_words_write_helper(diff_words->opt->file,
882749a0 976 &style->old, style->newline,
4297c0ae
BY
977 diff_words->minus.text.size,
978 diff_words->minus.text.ptr, line_prefix);
2e5d2003
JS
979 diff_words->minus.text.size = 0;
980 return;
981 }
982
983 diff_words->current_plus = diff_words->plus.text.ptr;
4297c0ae 984 diff_words->last_minus = 0;
f59a59e2 985
9ccd0a88 986 memset(&xpp, 0, sizeof(xpp));
30b25010 987 memset(&xecfg, 0, sizeof(xecfg));
2b6a5417
JS
988 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
989 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
582aa00b 990 xpp.flags = 0;
2b6a5417 991 /* as only the hunk header will be parsed, we need a 0-context */
2e5d2003 992 xecfg.ctxlen = 0;
8a3f524b 993 xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
dfea7900 994 &xpp, &xecfg);
f59a59e2
JS
995 free(minus.ptr);
996 free(plus.ptr);
2e5d2003 997 if (diff_words->current_plus != diff_words->plus.text.ptr +
4297c0ae
BY
998 diff_words->plus.text.size) {
999 if (color_words_output_graph_prefix(diff_words))
1000 fputs(line_prefix, diff_words->opt->file);
1001 fn_out_diff_words_write_helper(diff_words->opt->file,
882749a0 1002 &style->ctx, style->newline,
2e5d2003 1003 diff_words->plus.text.ptr + diff_words->plus.text.size
4297c0ae
BY
1004 - diff_words->current_plus, diff_words->current_plus,
1005 line_prefix);
1006 }
f59a59e2 1007 diff_words->minus.text.size = diff_words->plus.text.size = 0;
f59a59e2
JS
1008}
1009
76fd2828
JH
1010/* In "color-words" mode, show word-diff of words accumulated in the buffer */
1011static void diff_words_flush(struct emit_callback *ecbdata)
1012{
1013 if (ecbdata->diff_words->minus.text.size ||
1014 ecbdata->diff_words->plus.text.size)
1015 diff_words_show(ecbdata->diff_words);
1016}
1017
77d1a520
TR
1018static void diff_filespec_load_driver(struct diff_filespec *one)
1019{
1020 /* Use already-loaded driver */
1021 if (one->driver)
1022 return;
1023
1024 if (S_ISREG(one->mode))
1025 one->driver = userdiff_find_by_path(one->path);
1026
1027 /* Fallback to default settings */
1028 if (!one->driver)
1029 one->driver = userdiff_find_by_name("default");
1030}
1031
1032static const char *userdiff_word_regex(struct diff_filespec *one)
1033{
1034 diff_filespec_load_driver(one);
1035 return one->driver->word_regex;
1036}
1037
1038static void init_diff_words_data(struct emit_callback *ecbdata,
6440d341 1039 struct diff_options *orig_opts,
77d1a520
TR
1040 struct diff_filespec *one,
1041 struct diff_filespec *two)
1042{
1043 int i;
6440d341
TR
1044 struct diff_options *o = xmalloc(sizeof(struct diff_options));
1045 memcpy(o, orig_opts, sizeof(struct diff_options));
77d1a520
TR
1046
1047 ecbdata->diff_words =
1048 xcalloc(1, sizeof(struct diff_words_data));
1049 ecbdata->diff_words->type = o->word_diff;
1050 ecbdata->diff_words->opt = o;
1051 if (!o->word_regex)
1052 o->word_regex = userdiff_word_regex(one);
1053 if (!o->word_regex)
1054 o->word_regex = userdiff_word_regex(two);
1055 if (!o->word_regex)
1056 o->word_regex = diff_word_regex_cfg;
1057 if (o->word_regex) {
1058 ecbdata->diff_words->word_regex = (regex_t *)
1059 xmalloc(sizeof(regex_t));
1060 if (regcomp(ecbdata->diff_words->word_regex,
1061 o->word_regex,
1062 REG_EXTENDED | REG_NEWLINE))
1063 die ("Invalid regular expression: %s",
1064 o->word_regex);
1065 }
1066 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
1067 if (o->word_diff == diff_words_styles[i].type) {
1068 ecbdata->diff_words->style =
1069 &diff_words_styles[i];
1070 break;
1071 }
1072 }
1073 if (want_color(o->use_color)) {
1074 struct diff_words_style *st = ecbdata->diff_words->style;
1075 st->old.color = diff_get_color_opt(o, DIFF_FILE_OLD);
1076 st->new.color = diff_get_color_opt(o, DIFF_FILE_NEW);
1077 st->ctx.color = diff_get_color_opt(o, DIFF_PLAIN);
1078 }
1079}
1080
f59a59e2
JS
1081static void free_diff_words_data(struct emit_callback *ecbdata)
1082{
1083 if (ecbdata->diff_words) {
76fd2828 1084 diff_words_flush(ecbdata);
6440d341 1085 free (ecbdata->diff_words->opt);
8e0f7003 1086 free (ecbdata->diff_words->minus.text.ptr);
2e5d2003 1087 free (ecbdata->diff_words->minus.orig);
8e0f7003 1088 free (ecbdata->diff_words->plus.text.ptr);
2e5d2003 1089 free (ecbdata->diff_words->plus.orig);
ef5644ea
BC
1090 if (ecbdata->diff_words->word_regex) {
1091 regfree(ecbdata->diff_words->word_regex);
1092 free(ecbdata->diff_words->word_regex);
1093 }
f59a59e2
JS
1094 free(ecbdata->diff_words);
1095 ecbdata->diff_words = NULL;
1096 }
1097}
1098
ce436973 1099const char *diff_get_color(int diff_use_color, enum color_diff ix)
cd112cef 1100{
daa0c3d9 1101 if (want_color(diff_use_color))
50f575fc
LT
1102 return diff_colors[ix];
1103 return "";
cd112cef
JS
1104}
1105
23707811
JH
1106static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
1107{
1108 const char *cp;
1109 unsigned long allot;
1110 size_t l = len;
1111
1112 if (ecb->truncate)
1113 return ecb->truncate(line, len);
1114 cp = line;
1115 allot = l;
1116 while (0 < l) {
1117 (void) utf8_width(&cp, &l);
1118 if (!cp)
1119 break; /* truncated in the middle? */
1120 }
1121 return allot - l;
1122}
1123
d68fe26f 1124static void find_lno(const char *line, struct emit_callback *ecbdata)
690ed843 1125{
d68fe26f
JH
1126 const char *p;
1127 ecbdata->lno_in_preimage = 0;
1128 ecbdata->lno_in_postimage = 0;
1129 p = strchr(line, '-');
690ed843 1130 if (!p)
d68fe26f
JH
1131 return; /* cannot happen */
1132 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
1133 p = strchr(p, '+');
1134 if (!p)
1135 return; /* cannot happen */
1136 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
690ed843
JH
1137}
1138
cd112cef 1139static void fn_out_consume(void *priv, char *line, unsigned long len)
6973dcae 1140{
6973dcae 1141 struct emit_callback *ecbdata = priv;
472ca780
JK
1142 const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
1143 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
ce436973 1144 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
7be57610
BY
1145 struct diff_options *o = ecbdata->opt;
1146 char *line_prefix = "";
1147 struct strbuf *msgbuf;
1148
1149 if (o && o->output_prefix) {
1150 msgbuf = o->output_prefix(o, o->output_prefix_data);
1151 line_prefix = msgbuf->buf;
1152 }
6973dcae 1153
3e97c7c6 1154 if (ecbdata->header) {
a3c158d4 1155 fprintf(ecbdata->opt->file, "%s", ecbdata->header->buf);
3e97c7c6
GB
1156 strbuf_reset(ecbdata->header);
1157 ecbdata->header = NULL;
1158 }
34a5e1a2
JS
1159 *(ecbdata->found_changesp) = 1;
1160
6973dcae 1161 if (ecbdata->label_path[0]) {
1a9eb3b9
JH
1162 const char *name_a_tab, *name_b_tab;
1163
1164 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
1165 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
1166
7be57610
BY
1167 fprintf(ecbdata->opt->file, "%s%s--- %s%s%s\n",
1168 line_prefix, meta, ecbdata->label_path[0], reset, name_a_tab);
1169 fprintf(ecbdata->opt->file, "%s%s+++ %s%s%s\n",
1170 line_prefix, meta, ecbdata->label_path[1], reset, name_b_tab);
6973dcae
JH
1171 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
1172 }
cd112cef 1173
a624eaa7
JM
1174 if (diff_suppress_blank_empty
1175 && len == 2 && line[0] == ' ' && line[1] == '\n') {
1176 line[0] = '\n';
1177 len = 1;
1178 }
1179
b8d9c1a6 1180 if (line[0] == '@') {
76fd2828
JH
1181 if (ecbdata->diff_words)
1182 diff_words_flush(ecbdata);
23707811 1183 len = sane_truncate_line(ecbdata, line, len);
d68fe26f 1184 find_lno(line, ecbdata);
89cb73a1 1185 emit_hunk_header(ecbdata, line, len);
23707811 1186 if (line[len-1] != '\n')
a3c158d4 1187 putc('\n', ecbdata->opt->file);
448c3ef1 1188 return;
cd112cef 1189 }
448c3ef1 1190
b8d9c1a6 1191 if (len < 1) {
a3c158d4 1192 emit_line(ecbdata->opt, reset, reset, line, len);
882749a0
TR
1193 if (ecbdata->diff_words
1194 && ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN)
a3c158d4 1195 fputs("~\n", ecbdata->opt->file);
448c3ef1 1196 return;
cd112cef 1197 }
448c3ef1 1198
448c3ef1
JH
1199 if (ecbdata->diff_words) {
1200 if (line[0] == '-') {
1201 diff_words_append(line, len,
1202 &ecbdata->diff_words->minus);
1203 return;
1204 } else if (line[0] == '+') {
1205 diff_words_append(line, len,
1206 &ecbdata->diff_words->plus);
1207 return;
c7c2bc0a
TR
1208 } else if (!prefixcmp(line, "\\ ")) {
1209 /*
1210 * Eat the "no newline at eof" marker as if we
1211 * saw a "+" or "-" line with nothing on it,
1212 * and return without diff_words_flush() to
1213 * defer processing. If this is the end of
1214 * preimage, more "+" lines may come after it.
1215 */
1216 return;
448c3ef1 1217 }
76fd2828 1218 diff_words_flush(ecbdata);
882749a0 1219 if (ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN) {
a3c158d4
BY
1220 emit_line(ecbdata->opt, plain, reset, line, len);
1221 fputs("~\n", ecbdata->opt->file);
882749a0 1222 } else {
42536dd9
JM
1223 /*
1224 * Skip the prefix character, if any. With
1225 * diff_suppress_blank_empty, there may be
1226 * none.
1227 */
1228 if (line[0] != '\n') {
1229 line++;
1230 len--;
1231 }
1232 emit_line(ecbdata->opt, plain, reset, line, len);
882749a0 1233 }
448c3ef1
JH
1234 return;
1235 }
448c3ef1 1236
690ed843
JH
1237 if (line[0] != '+') {
1238 const char *color =
1239 diff_get_color(ecbdata->color_diff,
1240 line[0] == '-' ? DIFF_FILE_OLD : DIFF_PLAIN);
1241 ecbdata->lno_in_preimage++;
d68fe26f
JH
1242 if (line[0] == ' ')
1243 ecbdata->lno_in_postimage++;
a3c158d4 1244 emit_line(ecbdata->opt, color, reset, line, len);
d68fe26f
JH
1245 } else {
1246 ecbdata->lno_in_postimage++;
018cff70 1247 emit_add_line(reset, ecbdata, line + 1, len - 1);
448c3ef1 1248 }
6973dcae
JH
1249}
1250
1251static char *pprint_rename(const char *a, const char *b)
1252{
1253 const char *old = a;
1254 const char *new = b;
f285a2d7 1255 struct strbuf name = STRBUF_INIT;
6973dcae
JH
1256 int pfx_length, sfx_length;
1257 int len_a = strlen(a);
1258 int len_b = strlen(b);
663af342 1259 int a_midlen, b_midlen;
e5bfbf9b
AJ
1260 int qlen_a = quote_c_style(a, NULL, NULL, 0);
1261 int qlen_b = quote_c_style(b, NULL, NULL, 0);
1262
1263 if (qlen_a || qlen_b) {
663af342
PH
1264 quote_c_style(a, &name, NULL, 0);
1265 strbuf_addstr(&name, " => ");
1266 quote_c_style(b, &name, NULL, 0);
b315c5c0 1267 return strbuf_detach(&name, NULL);
e5bfbf9b 1268 }
6973dcae
JH
1269
1270 /* Find common prefix */
1271 pfx_length = 0;
1272 while (*old && *new && *old == *new) {
1273 if (*old == '/')
1274 pfx_length = old - a + 1;
1275 old++;
1276 new++;
1277 }
1278
1279 /* Find common suffix */
1280 old = a + len_a;
1281 new = b + len_b;
1282 sfx_length = 0;
1283 while (a <= old && b <= new && *old == *new) {
1284 if (*old == '/')
1285 sfx_length = len_a - (old - a);
1286 old--;
1287 new--;
1288 }
1289
1290 /*
1291 * pfx{mid-a => mid-b}sfx
1292 * {pfx-a => pfx-b}sfx
1293 * pfx{sfx-a => sfx-b}
1294 * name-a => name-b
1295 */
663af342
PH
1296 a_midlen = len_a - pfx_length - sfx_length;
1297 b_midlen = len_b - pfx_length - sfx_length;
1298 if (a_midlen < 0)
1299 a_midlen = 0;
1300 if (b_midlen < 0)
1301 b_midlen = 0;
1302
1303 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
6973dcae 1304 if (pfx_length + sfx_length) {
663af342
PH
1305 strbuf_add(&name, a, pfx_length);
1306 strbuf_addch(&name, '{');
6973dcae 1307 }
663af342
PH
1308 strbuf_add(&name, a + pfx_length, a_midlen);
1309 strbuf_addstr(&name, " => ");
1310 strbuf_add(&name, b + pfx_length, b_midlen);
1311 if (pfx_length + sfx_length) {
1312 strbuf_addch(&name, '}');
1313 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
6973dcae 1314 }
b315c5c0 1315 return strbuf_detach(&name, NULL);
6973dcae
JH
1316}
1317
1318struct diffstat_t {
6973dcae
JH
1319 int nr;
1320 int alloc;
1321 struct diffstat_file {
f604652e 1322 char *from_name;
6973dcae 1323 char *name;
f604652e 1324 char *print_name;
6973dcae
JH
1325 unsigned is_unmerged:1;
1326 unsigned is_binary:1;
1327 unsigned is_renamed:1;
0974c117 1328 uintmax_t added, deleted;
6973dcae
JH
1329 } **files;
1330};
1331
1332static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
1333 const char *name_a,
1334 const char *name_b)
1335{
1336 struct diffstat_file *x;
1337 x = xcalloc(sizeof (*x), 1);
1338 if (diffstat->nr == diffstat->alloc) {
1339 diffstat->alloc = alloc_nr(diffstat->alloc);
1340 diffstat->files = xrealloc(diffstat->files,
1341 diffstat->alloc * sizeof(x));
1342 }
1343 diffstat->files[diffstat->nr++] = x;
1344 if (name_b) {
f604652e
JH
1345 x->from_name = xstrdup(name_a);
1346 x->name = xstrdup(name_b);
6973dcae
JH
1347 x->is_renamed = 1;
1348 }
f604652e
JH
1349 else {
1350 x->from_name = NULL;
9befac47 1351 x->name = xstrdup(name_a);
f604652e 1352 }
6973dcae
JH
1353 return x;
1354}
1355
1356static void diffstat_consume(void *priv, char *line, unsigned long len)
1357{
1358 struct diffstat_t *diffstat = priv;
1359 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
1360
1361 if (line[0] == '+')
1362 x->added++;
1363 else if (line[0] == '-')
1364 x->deleted++;
1365}
1366
698ce6f8 1367const char mime_boundary_leader[] = "------------";
6973dcae 1368
a2540023
JH
1369static int scale_linear(int it, int width, int max_change)
1370{
2eeeef24
JH
1371 if (!it)
1372 return 0;
a2540023 1373 /*
2eeeef24
JH
1374 * make sure that at least one '-' or '+' is printed if
1375 * there is any change to this path. The easiest way is to
1376 * scale linearly as if the alloted width is one column shorter
1377 * than it is, and then add 1 to the result.
a2540023 1378 */
2eeeef24 1379 return 1 + (it * (width - 1) / max_change);
a2540023
JH
1380}
1381
c0c77734 1382static void show_name(FILE *file,
a408e0e6 1383 const char *prefix, const char *name, int len)
a2540023 1384{
a408e0e6 1385 fprintf(file, " %s%-*s |", prefix, len, name);
a2540023
JH
1386}
1387
c0c77734 1388static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
a2540023
JH
1389{
1390 if (cnt <= 0)
1391 return;
c0c77734 1392 fprintf(file, "%s", set);
a2540023 1393 while (cnt--)
c0c77734
DB
1394 putc(ch, file);
1395 fprintf(file, "%s", reset);
a2540023
JH
1396}
1397
f604652e
JH
1398static void fill_print_name(struct diffstat_file *file)
1399{
1400 char *pname;
1401
1402 if (file->print_name)
1403 return;
1404
1405 if (!file->is_renamed) {
f285a2d7 1406 struct strbuf buf = STRBUF_INIT;
f604652e
JH
1407 if (quote_c_style(file->name, &buf, NULL, 0)) {
1408 pname = strbuf_detach(&buf, NULL);
1409 } else {
1410 pname = file->name;
1411 strbuf_release(&buf);
1412 }
1413 } else {
1414 pname = pprint_rename(file->from_name, file->name);
1415 }
1416 file->print_name = pname;
1417}
1418
7f814632
NTND
1419int print_stat_summary(FILE *fp, int files, int insertions, int deletions)
1420{
1421 struct strbuf sb = STRBUF_INIT;
1422 int ret;
1423
1424 if (!files) {
1425 assert(insertions == 0 && deletions == 0);
218adaaa 1426 return fprintf(fp, "%s\n", " 0 files changed");
7f814632
NTND
1427 }
1428
1429 strbuf_addf(&sb,
218adaaa 1430 (files == 1) ? " %d file changed" : " %d files changed",
7f814632
NTND
1431 files);
1432
1433 /*
1434 * For binary diff, the caller may want to print "x files
1435 * changed" with insertions == 0 && deletions == 0.
1436 *
1437 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
1438 * is probably less confusing (i.e skip over "2 files changed
1439 * but nothing about added/removed lines? Is this a bug in Git?").
1440 */
1441 if (insertions || deletions == 0) {
1442 /*
1443 * TRANSLATORS: "+" in (+) is a line addition marker;
1444 * do not translate it.
1445 */
1446 strbuf_addf(&sb,
218adaaa 1447 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
7f814632
NTND
1448 insertions);
1449 }
1450
1451 if (deletions || insertions == 0) {
1452 /*
1453 * TRANSLATORS: "-" in (-) is a line removal marker;
1454 * do not translate it.
1455 */
1456 strbuf_addf(&sb,
218adaaa 1457 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
7f814632
NTND
1458 deletions);
1459 }
1460 strbuf_addch(&sb, '\n');
1461 ret = fputs(sb.buf, fp);
1462 strbuf_release(&sb);
1463 return ret;
1464}
1465
4b25d091 1466static void show_stats(struct diffstat_t *data, struct diff_options *options)
6973dcae 1467{
eb3a9dd3 1468 int i, len, add, del, adds = 0, dels = 0;
0974c117 1469 uintmax_t max_change = 0, max_len = 0;
dc801e71
ZJS
1470 int total_files = data->nr, count;
1471 int width, name_width, graph_width, number_width = 0, bin_width = 0;
c0aa335c 1472 const char *reset, *add_c, *del_c;
7be57610 1473 const char *line_prefix = "";
e5f85df8 1474 int extra_shown = 0;
7be57610 1475 struct strbuf *msg = NULL;
6973dcae
JH
1476
1477 if (data->nr == 0)
1478 return;
1479
7be57610
BY
1480 if (options->output_prefix) {
1481 msg = options->output_prefix(options, options->output_prefix_data);
1482 line_prefix = msg->buf;
1483 }
1484
808e1db2 1485 count = options->stat_count ? options->stat_count : data->nr;
a2540023 1486
8f67f8ae 1487 reset = diff_get_color_opt(options, DIFF_RESET);
8f67f8ae
PH
1488 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
1489 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
785f7432 1490
1b058bc3
ZJS
1491 /*
1492 * Find the longest filename and max number of changes
1493 */
808e1db2 1494 for (i = 0; (i < count) && (i < data->nr); i++) {
6973dcae 1495 struct diffstat_file *file = data->files[i];
0974c117 1496 uintmax_t change = file->added + file->deleted;
358e460e
MG
1497 if (!data->files[i]->is_renamed &&
1498 (change == 0)) {
808e1db2 1499 count++; /* not shown == room for one more */
358e460e
MG
1500 continue;
1501 }
f604652e
JH
1502 fill_print_name(file);
1503 len = strlen(file->print_name);
6973dcae
JH
1504 if (max_len < len)
1505 max_len = len;
1506
dc801e71
ZJS
1507 if (file->is_unmerged) {
1508 /* "Unmerged" is 8 characters */
1509 bin_width = bin_width < 8 ? 8 : bin_width;
6973dcae 1510 continue;
dc801e71
ZJS
1511 }
1512 if (file->is_binary) {
1513 /* "Bin XXX -> YYY bytes" */
1514 int w = 14 + decimal_width(file->added)
1515 + decimal_width(file->deleted);
1516 bin_width = bin_width < w ? w : bin_width;
1517 /* Display change counts aligned with "Bin" */
1518 number_width = 3;
1519 continue;
1520 }
1521
a2540023
JH
1522 if (max_change < change)
1523 max_change = change;
6973dcae 1524 }
808e1db2 1525 count = i; /* min(count, data->nr) */
6973dcae 1526
1b058bc3
ZJS
1527 /*
1528 * We have width = stat_width or term_columns() columns total.
1529 * We want a maximum of min(max_len, stat_name_width) for the name part.
969fe57b 1530 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
1b058bc3
ZJS
1531 * We also need 1 for " " and 4 + decimal_width(max_change)
1532 * for " | NNNN " and one the empty column at the end, altogether
1533 * 6 + decimal_width(max_change).
1534 *
1535 * If there's not enough space, we will use the smaller of
1536 * stat_name_width (if set) and 5/8*width for the filename,
969fe57b
ZJS
1537 * and the rest for constant elements + graph part, but no more
1538 * than stat_graph_width for the graph part.
1b058bc3
ZJS
1539 * (5/8 gives 50 for filename and 30 for the constant parts + graph
1540 * for the standard terminal size).
a2540023 1541 *
1b058bc3
ZJS
1542 * In other words: stat_width limits the maximum width, and
1543 * stat_name_width fixes the maximum width of the filename,
1544 * and is also used to divide available columns if there
1545 * aren't enough.
dc801e71
ZJS
1546 *
1547 * Binary files are displayed with "Bin XXX -> YYY bytes"
1548 * instead of the change count and graph. This part is treated
1549 * similarly to the graph part, except that it is not
1550 * "scaled". If total width is too small to accomodate the
1551 * guaranteed minimum width of the filename part and the
1552 * separators and this message, this message will "overflow"
1553 * making the line longer than the maximum width.
a2540023 1554 */
1b058bc3
ZJS
1555
1556 if (options->stat_width == -1)
3f145132 1557 width = term_columns() - options->output_prefix_length;
a2540023 1558 else
1b058bc3 1559 width = options->stat_width ? options->stat_width : 80;
dc801e71
ZJS
1560 number_width = decimal_width(max_change) > number_width ?
1561 decimal_width(max_change) : number_width;
a2540023 1562
df44483a
ZJS
1563 if (options->stat_graph_width == -1)
1564 options->stat_graph_width = diff_stat_graph_width;
a2540023 1565
1b058bc3
ZJS
1566 /*
1567 * Guarantee 3/8*16==6 for the graph part
1568 * and 5/8*16==10 for the filename part
1569 */
1570 if (width < 16 + 6 + number_width)
1571 width = 16 + 6 + number_width;
1572
1573 /*
1574 * First assign sizes that are wanted, ignoring available width.
dc801e71
ZJS
1575 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
1576 * starting from "XXX" should fit in graph_width.
1b058bc3 1577 */
dc801e71
ZJS
1578 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
1579 if (options->stat_graph_width &&
1580 options->stat_graph_width < graph_width)
1581 graph_width = options->stat_graph_width;
1582
1b058bc3
ZJS
1583 name_width = (options->stat_name_width > 0 &&
1584 options->stat_name_width < max_len) ?
1585 options->stat_name_width : max_len;
1586
1587 /*
1588 * Adjust adjustable widths not to exceed maximum width
1589 */
1590 if (name_width + number_width + 6 + graph_width > width) {
678c5741 1591 if (graph_width > width * 3/8 - number_width - 6) {
1b058bc3 1592 graph_width = width * 3/8 - number_width - 6;
678c5741
LP
1593 if (graph_width < 6)
1594 graph_width = 6;
1595 }
1596
969fe57b
ZJS
1597 if (options->stat_graph_width &&
1598 graph_width > options->stat_graph_width)
1599 graph_width = options->stat_graph_width;
1b058bc3
ZJS
1600 if (name_width > width - number_width - 6 - graph_width)
1601 name_width = width - number_width - 6 - graph_width;
1602 else
1603 graph_width = width - number_width - 6 - name_width;
1604 }
1605
1606 /*
1607 * From here name_width is the width of the name area,
1608 * and graph_width is the width of the graph area.
1609 * max_change is used to scale graph properly.
1610 */
808e1db2 1611 for (i = 0; i < count; i++) {
d2543b8e 1612 const char *prefix = "";
f604652e 1613 char *name = data->files[i]->print_name;
0974c117
JK
1614 uintmax_t added = data->files[i]->added;
1615 uintmax_t deleted = data->files[i]->deleted;
a2540023 1616 int name_len;
6973dcae 1617
358e460e
MG
1618 if (!data->files[i]->is_renamed &&
1619 (added + deleted == 0)) {
1620 total_files--;
1621 continue;
1622 }
6973dcae
JH
1623 /*
1624 * "scale" the filename
1625 */
a2540023
JH
1626 len = name_width;
1627 name_len = strlen(name);
1628 if (name_width < name_len) {
6973dcae
JH
1629 char *slash;
1630 prefix = "...";
a2540023
JH
1631 len -= 3;
1632 name += name_len - len;
6973dcae
JH
1633 slash = strchr(name, '/');
1634 if (slash)
1635 name = slash;
1636 }
6973dcae
JH
1637
1638 if (data->files[i]->is_binary) {
7be57610 1639 fprintf(options->file, "%s", line_prefix);
a408e0e6 1640 show_name(options->file, prefix, name, len);
fc1320bf 1641 fprintf(options->file, " %*s", number_width, "Bin");
e18872b2
ZJS
1642 if (!added && !deleted) {
1643 putc('\n', options->file);
1644 continue;
1645 }
1646 fprintf(options->file, " %s%"PRIuMAX"%s",
0974c117 1647 del_c, deleted, reset);
c0c77734 1648 fprintf(options->file, " -> ");
0974c117
JK
1649 fprintf(options->file, "%s%"PRIuMAX"%s",
1650 add_c, added, reset);
c0c77734
DB
1651 fprintf(options->file, " bytes");
1652 fprintf(options->file, "\n");
f604652e 1653 continue;
6973dcae
JH
1654 }
1655 else if (data->files[i]->is_unmerged) {
7be57610 1656 fprintf(options->file, "%s", line_prefix);
a408e0e6 1657 show_name(options->file, prefix, name, len);
dc801e71 1658 fprintf(options->file, " Unmerged\n");
f604652e 1659 continue;
6973dcae 1660 }
6973dcae 1661
a2540023
JH
1662 /*
1663 * scale the add/delete
1664 */
6973dcae
JH
1665 add = added;
1666 del = deleted;
6973dcae
JH
1667 adds += add;
1668 dels += del;
1669
1b058bc3 1670 if (graph_width <= max_change) {
2eeeef24
JH
1671 int total = add + del;
1672
1b058bc3 1673 total = scale_linear(add + del, graph_width, max_change);
2eeeef24
JH
1674 if (total < 2 && add && del)
1675 /* width >= 2 due to the sanity check */
1676 total = 2;
1677 if (add < del) {
1b058bc3 1678 add = scale_linear(add, graph_width, max_change);
2eeeef24
JH
1679 del = total - add;
1680 } else {
1b058bc3 1681 del = scale_linear(del, graph_width, max_change);
2eeeef24
JH
1682 add = total - del;
1683 }
6973dcae 1684 }
7be57610 1685 fprintf(options->file, "%s", line_prefix);
a408e0e6 1686 show_name(options->file, prefix, name, len);
dc801e71
ZJS
1687 fprintf(options->file, " %*"PRIuMAX"%s",
1688 number_width, added + deleted,
1689 added + deleted ? " " : "");
c0c77734
DB
1690 show_graph(options->file, '+', add, add_c, reset);
1691 show_graph(options->file, '-', del, del_c, reset);
1692 fprintf(options->file, "\n");
1693 }
808e1db2
MG
1694 for (i = count; i < data->nr; i++) {
1695 uintmax_t added = data->files[i]->added;
1696 uintmax_t deleted = data->files[i]->deleted;
1697 if (!data->files[i]->is_renamed &&
1698 (added + deleted == 0)) {
1699 total_files--;
1700 continue;
1701 }
1702 adds += added;
1703 dels += deleted;
e5f85df8
JH
1704 if (!extra_shown)
1705 fprintf(options->file, "%s ...\n", line_prefix);
1706 extra_shown = 1;
808e1db2 1707 }
7be57610 1708 fprintf(options->file, "%s", line_prefix);
7f814632 1709 print_stat_summary(options->file, total_files, adds, dels);
6973dcae
JH
1710}
1711
2775d92c 1712static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
ebd124c6
NP
1713{
1714 int i, adds = 0, dels = 0, total_files = data->nr;
1715
1716 if (data->nr == 0)
1717 return;
1718
1719 for (i = 0; i < data->nr; i++) {
e18872b2
ZJS
1720 int added = data->files[i]->added;
1721 int deleted= data->files[i]->deleted;
1722
1723 if (data->files[i]->is_unmerged)
1724 continue;
1725 if (!data->files[i]->is_renamed && (added + deleted == 0)) {
1726 total_files--;
de9658b5 1727 } else if (!data->files[i]->is_binary) { /* don't count bytes */
e18872b2
ZJS
1728 adds += added;
1729 dels += deleted;
ebd124c6 1730 }
ebd124c6 1731 }
7be57610
BY
1732 if (options->output_prefix) {
1733 struct strbuf *msg = NULL;
1734 msg = options->output_prefix(options,
1735 options->output_prefix_data);
1736 fprintf(options->file, "%s", msg->buf);
1737 }
7f814632 1738 print_stat_summary(options->file, total_files, adds, dels);
ebd124c6
NP
1739}
1740
4b25d091 1741static void show_numstat(struct diffstat_t *data, struct diff_options *options)
74e2abe5
JH
1742{
1743 int i;
1744
f604652e
JH
1745 if (data->nr == 0)
1746 return;
1747
74e2abe5
JH
1748 for (i = 0; i < data->nr; i++) {
1749 struct diffstat_file *file = data->files[i];
1750
7be57610
BY
1751 if (options->output_prefix) {
1752 struct strbuf *msg = NULL;
1753 msg = options->output_prefix(options,
1754 options->output_prefix_data);
1755 fprintf(options->file, "%s", msg->buf);
1756 }
1757
bfddbc5e 1758 if (file->is_binary)
c0c77734 1759 fprintf(options->file, "-\t-\t");
bfddbc5e 1760 else
c0c77734 1761 fprintf(options->file,
0974c117
JK
1762 "%"PRIuMAX"\t%"PRIuMAX"\t",
1763 file->added, file->deleted);
f604652e
JH
1764 if (options->line_termination) {
1765 fill_print_name(file);
1766 if (!file->is_renamed)
c0c77734 1767 write_name_quoted(file->name, options->file,
f604652e
JH
1768 options->line_termination);
1769 else {
c0c77734
DB
1770 fputs(file->print_name, options->file);
1771 putc(options->line_termination, options->file);
f604652e 1772 }
663af342 1773 } else {
f604652e 1774 if (file->is_renamed) {
c0c77734
DB
1775 putc('\0', options->file);
1776 write_name_quoted(file->from_name, options->file, '\0');
f604652e 1777 }
c0c77734 1778 write_name_quoted(file->name, options->file, '\0');
663af342 1779 }
74e2abe5
JH
1780 }
1781}
1782
c04a7155
JH
1783struct dirstat_file {
1784 const char *name;
1785 unsigned long changed;
7df7c019
LT
1786};
1787
c04a7155
JH
1788struct dirstat_dir {
1789 struct dirstat_file *files;
712d2c7d 1790 int alloc, nr, permille, cumulative;
c04a7155
JH
1791};
1792
7be57610
BY
1793static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
1794 unsigned long changed, const char *base, int baselen)
7df7c019
LT
1795{
1796 unsigned long this_dir = 0;
1797 unsigned int sources = 0;
7be57610
BY
1798 const char *line_prefix = "";
1799 struct strbuf *msg = NULL;
1800
1801 if (opt->output_prefix) {
1802 msg = opt->output_prefix(opt, opt->output_prefix_data);
1803 line_prefix = msg->buf;
1804 }
7df7c019
LT
1805
1806 while (dir->nr) {
c04a7155 1807 struct dirstat_file *f = dir->files;
7df7c019
LT
1808 int namelen = strlen(f->name);
1809 unsigned long this;
1810 char *slash;
1811
1812 if (namelen < baselen)
1813 break;
1814 if (memcmp(f->name, base, baselen))
1815 break;
1816 slash = strchr(f->name + baselen, '/');
1817 if (slash) {
1818 int newbaselen = slash + 1 - f->name;
7be57610 1819 this = gather_dirstat(opt, dir, changed, f->name, newbaselen);
7df7c019
LT
1820 sources++;
1821 } else {
c04a7155 1822 this = f->changed;
7df7c019
LT
1823 dir->files++;
1824 dir->nr--;
1825 sources += 2;
1826 }
1827 this_dir += this;
1828 }
1829
1830 /*
1831 * We don't report dirstat's for
1832 * - the top level
1833 * - or cases where everything came from a single directory
1834 * under this directory (sources == 1).
1835 */
1836 if (baselen && sources != 1) {
58a8756a
JH
1837 if (this_dir) {
1838 int permille = this_dir * 1000 / changed;
712d2c7d 1839 if (permille >= dir->permille) {
7be57610 1840 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
712d2c7d 1841 permille / 10, permille % 10, baselen, base);
7df7c019
LT
1842 if (!dir->cumulative)
1843 return 0;
1844 }
1845 }
1846 }
1847 return this_dir;
1848}
1849
441bca0b
LT
1850static int dirstat_compare(const void *_a, const void *_b)
1851{
1852 const struct dirstat_file *a = _a;
1853 const struct dirstat_file *b = _b;
1854 return strcmp(a->name, b->name);
1855}
1856
c04a7155 1857static void show_dirstat(struct diff_options *options)
7df7c019
LT
1858{
1859 int i;
1860 unsigned long changed;
c04a7155
JH
1861 struct dirstat_dir dir;
1862 struct diff_queue_struct *q = &diff_queued_diff;
1863
1864 dir.files = NULL;
1865 dir.alloc = 0;
1866 dir.nr = 0;
712d2c7d 1867 dir.permille = options->dirstat_permille;
f88d225f 1868 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
7df7c019 1869
7df7c019 1870 changed = 0;
c04a7155
JH
1871 for (i = 0; i < q->nr; i++) {
1872 struct diff_filepair *p = q->queue[i];
1873 const char *name;
1874 unsigned long copied, added, damage;
0133dab7 1875 int content_changed;
c04a7155 1876
2ca86714 1877 name = p->two->path ? p->two->path : p->one->path;
c04a7155 1878
0133dab7
JH
1879 if (p->one->sha1_valid && p->two->sha1_valid)
1880 content_changed = hashcmp(p->one->sha1, p->two->sha1);
1881 else
1882 content_changed = 1;
1883
2ff3a803
JH
1884 if (!content_changed) {
1885 /*
1886 * The SHA1 has not changed, so pre-/post-content is
1887 * identical. We can therefore skip looking at the
1888 * file contents altogether.
1889 */
1890 damage = 0;
1891 goto found_damage;
1892 }
1893
0133dab7
JH
1894 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE)) {
1895 /*
1896 * In --dirstat-by-file mode, we don't really need to
1897 * look at the actual file contents at all.
1898 * The fact that the SHA1 changed is enough for us to
1899 * add this file to the list of results
1900 * (with each file contributing equal damage).
1901 */
2ff3a803 1902 damage = 1;
0133dab7
JH
1903 goto found_damage;
1904 }
c04a7155
JH
1905
1906 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1907 diff_populate_filespec(p->one, 0);
1908 diff_populate_filespec(p->two, 0);
1909 diffcore_count_changes(p->one, p->two, NULL, NULL, 0,
1910 &copied, &added);
1911 diff_free_filespec_data(p->one);
1912 diff_free_filespec_data(p->two);
1913 } else if (DIFF_FILE_VALID(p->one)) {
1914 diff_populate_filespec(p->one, 1);
1915 copied = added = 0;
1916 diff_free_filespec_data(p->one);
1917 } else if (DIFF_FILE_VALID(p->two)) {
1918 diff_populate_filespec(p->two, 1);
1919 copied = 0;
1920 added = p->two->size;
1921 diff_free_filespec_data(p->two);
1922 } else
2b0b551d 1923 continue;
c04a7155
JH
1924
1925 /*
1926 * Original minus copied is the removed material,
1927 * added is the new material. They are both damages
0133dab7 1928 * made to the preimage.
2ff3a803
JH
1929 * If the resulting damage is zero, we know that
1930 * diffcore_count_changes() considers the two entries to
1931 * be identical, but since content_changed is true, we
1932 * know that there must have been _some_ kind of change,
1933 * so we force all entries to have damage > 0.
c04a7155
JH
1934 */
1935 damage = (p->one->size - copied) + added;
2ff3a803 1936 if (!damage)
fd33777b 1937 damage = 1;
c04a7155 1938
0133dab7 1939found_damage:
c04a7155
JH
1940 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1941 dir.files[dir.nr].name = name;
1942 dir.files[dir.nr].changed = damage;
1943 changed += damage;
1944 dir.nr++;
7df7c019
LT
1945 }
1946
1947 /* This can happen even with many files, if everything was renames */
1948 if (!changed)
1949 return;
1950
1951 /* Show all directories with more than x% of the changes */
441bca0b 1952 qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
7be57610 1953 gather_dirstat(options, &dir, changed, "", 0);
7df7c019
LT
1954}
1955
1c57a627
JH
1956static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
1957{
1958 int i;
1959 unsigned long changed;
1960 struct dirstat_dir dir;
1961
1962 if (data->nr == 0)
1963 return;
1964
1965 dir.files = NULL;
1966 dir.alloc = 0;
1967 dir.nr = 0;
1968 dir.permille = options->dirstat_permille;
1969 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
1970
1971 changed = 0;
1972 for (i = 0; i < data->nr; i++) {
1973 struct diffstat_file *file = data->files[i];
1974 unsigned long damage = file->added + file->deleted;
1975 if (file->is_binary)
1976 /*
1977 * binary files counts bytes, not lines. Must find some
1978 * way to normalize binary bytes vs. textual lines.
1979 * The following heuristic assumes that there are 64
1980 * bytes per "line".
1981 * This is stupid and ugly, but very cheap...
1982 */
1983 damage = (damage + 63) / 64;
1984 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1985 dir.files[dir.nr].name = file->name;
1986 dir.files[dir.nr].changed = damage;
1987 changed += damage;
1988 dir.nr++;
1989 }
1990
1991 /* This can happen even with many files, if everything was renames */
1992 if (!changed)
1993 return;
1994
1995 /* Show all directories with more than x% of the changes */
1996 qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
1997 gather_dirstat(options, &dir, changed, "", 0);
1998}
1999
f604652e
JH
2000static void free_diffstat_info(struct diffstat_t *diffstat)
2001{
2002 int i;
2003 for (i = 0; i < diffstat->nr; i++) {
2004 struct diffstat_file *f = diffstat->files[i];
2005 if (f->name != f->print_name)
2006 free(f->print_name);
2007 free(f->name);
2008 free(f->from_name);
2009 free(f);
2010 }
2011 free(diffstat->files);
2012}
2013
88246898 2014struct checkdiff_t {
88246898 2015 const char *filename;
1ba111d1 2016 int lineno;
a757c646 2017 int conflict_marker_size;
1ba111d1 2018 struct diff_options *o;
cf1b7869 2019 unsigned ws_rule;
62c64895 2020 unsigned status;
88246898
JS
2021};
2022
a757c646 2023static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
04954043
JH
2024{
2025 char firstchar;
2026 int cnt;
2027
a757c646 2028 if (len < marker_size + 1)
04954043
JH
2029 return 0;
2030 firstchar = line[0];
2031 switch (firstchar) {
a757c646 2032 case '=': case '>': case '<': case '|':
04954043
JH
2033 break;
2034 default:
2035 return 0;
2036 }
a757c646 2037 for (cnt = 1; cnt < marker_size; cnt++)
04954043
JH
2038 if (line[cnt] != firstchar)
2039 return 0;
a757c646
JH
2040 /* line[1] thru line[marker_size-1] are same as firstchar */
2041 if (len < marker_size + 1 || !isspace(line[marker_size]))
04954043 2042 return 0;
04954043
JH
2043 return 1;
2044}
2045
88246898
JS
2046static void checkdiff_consume(void *priv, char *line, unsigned long len)
2047{
2048 struct checkdiff_t *data = priv;
a757c646 2049 int marker_size = data->conflict_marker_size;
f1c96261
JK
2050 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
2051 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
2052 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
c1795bb0 2053 char *err;
7be57610
BY
2054 char *line_prefix = "";
2055 struct strbuf *msgbuf;
2056
2057 assert(data->o);
2058 if (data->o->output_prefix) {
2059 msgbuf = data->o->output_prefix(data->o,
2060 data->o->output_prefix_data);
2061 line_prefix = msgbuf->buf;
2062 }
88246898
JS
2063
2064 if (line[0] == '+') {
18374e58 2065 unsigned bad;
0ef617f4 2066 data->lineno++;
a757c646 2067 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
04954043
JH
2068 data->status |= 1;
2069 fprintf(data->o->file,
7be57610
BY
2070 "%s%s:%d: leftover conflict marker\n",
2071 line_prefix, data->filename, data->lineno);
04954043 2072 }
8f8841e9 2073 bad = ws_check(line + 1, len - 1, data->ws_rule);
18374e58 2074 if (!bad)
c1795bb0 2075 return;
18374e58
JH
2076 data->status |= bad;
2077 err = whitespace_error_string(bad);
7be57610
BY
2078 fprintf(data->o->file, "%s%s:%d: %s.\n",
2079 line_prefix, data->filename, data->lineno, err);
c1795bb0 2080 free(err);
a3c158d4 2081 emit_line(data->o, set, reset, line, 1);
8f8841e9 2082 ws_check_emit(line + 1, len - 1, data->ws_rule,
1ba111d1 2083 data->o->file, set, reset, ws);
877f23cc 2084 } else if (line[0] == ' ') {
88246898 2085 data->lineno++;
877f23cc 2086 } else if (line[0] == '@') {
88246898
JS
2087 char *plus = strchr(line, '+');
2088 if (plus)
0ef617f4 2089 data->lineno = strtol(plus, NULL, 10) - 1;
88246898
JS
2090 else
2091 die("invalid diff");
2092 }
2093}
2094
0660626c
JH
2095static unsigned char *deflate_it(char *data,
2096 unsigned long size,
2097 unsigned long *result_size)
051308f6 2098{
0660626c
JH
2099 int bound;
2100 unsigned char *deflated;
ef49a7a0 2101 git_zstream stream;
0660626c
JH
2102
2103 memset(&stream, 0, sizeof(stream));
55bb5c91 2104 git_deflate_init(&stream, zlib_compression_level);
225a6f10 2105 bound = git_deflate_bound(&stream, size);
0660626c
JH
2106 deflated = xmalloc(bound);
2107 stream.next_out = deflated;
2108 stream.avail_out = bound;
2109
2110 stream.next_in = (unsigned char *)data;
2111 stream.avail_in = size;
55bb5c91 2112 while (git_deflate(&stream, Z_FINISH) == Z_OK)
0660626c 2113 ; /* nothing */
55bb5c91 2114 git_deflate_end(&stream);
0660626c
JH
2115 *result_size = stream.total_out;
2116 return deflated;
051308f6
JH
2117}
2118
7be57610 2119static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two, char *prefix)
051308f6 2120{
0660626c
JH
2121 void *cp;
2122 void *delta;
2123 void *deflated;
2124 void *data;
2125 unsigned long orig_size;
2126 unsigned long delta_size;
2127 unsigned long deflate_size;
2128 unsigned long data_size;
051308f6 2129
0660626c
JH
2130 /* We could do deflated delta, or we could do just deflated two,
2131 * whichever is smaller.
051308f6 2132 */
0660626c
JH
2133 delta = NULL;
2134 deflated = deflate_it(two->ptr, two->size, &deflate_size);
2135 if (one->size && two->size) {
2136 delta = diff_delta(one->ptr, one->size,
2137 two->ptr, two->size,
2138 &delta_size, deflate_size);
2139 if (delta) {
2140 void *to_free = delta;
2141 orig_size = delta_size;
2142 delta = deflate_it(delta, delta_size, &delta_size);
2143 free(to_free);
051308f6
JH
2144 }
2145 }
051308f6 2146
0660626c 2147 if (delta && delta_size < deflate_size) {
7be57610 2148 fprintf(file, "%sdelta %lu\n", prefix, orig_size);
0660626c
JH
2149 free(deflated);
2150 data = delta;
2151 data_size = delta_size;
2152 }
2153 else {
7be57610 2154 fprintf(file, "%sliteral %lu\n", prefix, two->size);
0660626c
JH
2155 free(delta);
2156 data = deflated;
2157 data_size = deflate_size;
2158 }
051308f6 2159
0660626c
JH
2160 /* emit data encoded in base85 */
2161 cp = data;
2162 while (data_size) {
2163 int bytes = (52 < data_size) ? 52 : data_size;
051308f6 2164 char line[70];
0660626c 2165 data_size -= bytes;
051308f6
JH
2166 if (bytes <= 26)
2167 line[0] = bytes + 'A' - 1;
2168 else
2169 line[0] = bytes - 26 + 'a' - 1;
2170 encode_85(line + 1, cp, bytes);
1d7f171c 2171 cp = (char *) cp + bytes;
7be57610 2172 fprintf(file, "%s", prefix);
c0c77734
DB
2173 fputs(line, file);
2174 fputc('\n', file);
051308f6 2175 }
7be57610 2176 fprintf(file, "%s\n", prefix);
0660626c 2177 free(data);
051308f6
JH
2178}
2179
7be57610 2180static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two, char *prefix)
d4c452f0 2181{
7be57610
BY
2182 fprintf(file, "%sGIT binary patch\n", prefix);
2183 emit_binary_diff_body(file, one, two, prefix);
2184 emit_binary_diff_body(file, two, one, prefix);
d4c452f0
JH
2185}
2186
29a3eefd
JH
2187int diff_filespec_is_binary(struct diff_filespec *one)
2188{
122aa6f9
JK
2189 if (one->is_binary == -1) {
2190 diff_filespec_load_driver(one);
2191 if (one->driver->binary != -1)
2192 one->is_binary = one->driver->binary;
2193 else {
2194 if (!one->data && DIFF_FILE_VALID(one))
2195 diff_populate_filespec(one, 0);
2196 if (one->data)
2197 one->is_binary = buffer_is_binary(one->data,
2198 one->size);
2199 if (one->is_binary == -1)
2200 one->is_binary = 0;
2201 }
2202 }
29a3eefd 2203 return one->is_binary;
6973dcae
JH
2204}
2205
be58e70d 2206static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
f258475a 2207{
122aa6f9
JK
2208 diff_filespec_load_driver(one);
2209 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
f258475a
JH
2210}
2211
a5a818ee
JH
2212void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
2213{
2214 if (!options->a_prefix)
2215 options->a_prefix = a;
2216 if (!options->b_prefix)
2217 options->b_prefix = b;
2218}
2219
a788d7d5 2220struct userdiff_driver *get_textconv(struct diff_filespec *one)
04427ac8
JK
2221{
2222 if (!DIFF_FILE_VALID(one))
2223 return NULL;
d391c0ff 2224
04427ac8 2225 diff_filespec_load_driver(one);
3813e690 2226 return userdiff_get_textconv(one->driver);
04427ac8
JK
2227}
2228
6973dcae
JH
2229static void builtin_diff(const char *name_a,
2230 const char *name_b,
2231 struct diff_filespec *one,
2232 struct diff_filespec *two,
2233 const char *xfrm_msg,
296c6bb2 2234 int must_show_header,
051308f6 2235 struct diff_options *o,
6973dcae
JH
2236 int complete_rewrite)
2237{
2238 mmfile_t mf1, mf2;
2239 const char *lbl[2];
2240 char *a_one, *b_two;
8f67f8ae
PH
2241 const char *set = diff_get_color_opt(o, DIFF_METAINFO);
2242 const char *reset = diff_get_color_opt(o, DIFF_RESET);
a5a818ee 2243 const char *a_prefix, *b_prefix;
d9bae1a1
JK
2244 struct userdiff_driver *textconv_one = NULL;
2245 struct userdiff_driver *textconv_two = NULL;
3e97c7c6 2246 struct strbuf header = STRBUF_INIT;
7be57610
BY
2247 struct strbuf *msgbuf;
2248 char *line_prefix = "";
2249
2250 if (o->output_prefix) {
2251 msgbuf = o->output_prefix(o, o->output_prefix_data);
2252 line_prefix = msgbuf->buf;
2253 }
a5a818ee 2254
752c0c24
JS
2255 if (DIFF_OPT_TST(o, SUBMODULE_LOG) &&
2256 (!one->mode || S_ISGITLINK(one->mode)) &&
2257 (!two->mode || S_ISGITLINK(two->mode))) {
2258 const char *del = diff_get_color_opt(o, DIFF_FILE_OLD);
2259 const char *add = diff_get_color_opt(o, DIFF_FILE_NEW);
2260 show_submodule_summary(o->file, one ? one->path : two->path,
721ceec1 2261 one->sha1, two->sha1, two->dirty_submodule,
752c0c24
JS
2262 del, add, reset);
2263 return;
2264 }
2265
3aa1f7ca
JK
2266 if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
2267 textconv_one = get_textconv(one);
2268 textconv_two = get_textconv(two);
2269 }
2270
a5a818ee
JH
2271 diff_set_mnemonic_prefix(o, "a/", "b/");
2272 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
2273 a_prefix = o->b_prefix;
2274 b_prefix = o->a_prefix;
2275 } else {
2276 a_prefix = o->a_prefix;
2277 b_prefix = o->b_prefix;
2278 }
6973dcae 2279
71b989e7
LT
2280 /* Never use a non-valid filename anywhere if at all possible */
2281 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
2282 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
2283
a5a818ee
JH
2284 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
2285 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
6973dcae
JH
2286 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
2287 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
7be57610 2288 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, set, a_one, b_two, reset);
6973dcae
JH
2289 if (lbl[0][0] == '/') {
2290 /* /dev/null */
7be57610 2291 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, set, two->mode, reset);
37466447
BW
2292 if (xfrm_msg)
2293 strbuf_addstr(&header, xfrm_msg);
296c6bb2 2294 must_show_header = 1;
6973dcae
JH
2295 }
2296 else if (lbl[1][0] == '/') {
7be57610 2297 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, set, one->mode, reset);
37466447
BW
2298 if (xfrm_msg)
2299 strbuf_addstr(&header, xfrm_msg);
296c6bb2 2300 must_show_header = 1;
6973dcae
JH
2301 }
2302 else {
2303 if (one->mode != two->mode) {
7be57610
BY
2304 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, set, one->mode, reset);
2305 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, set, two->mode, reset);
296c6bb2 2306 must_show_header = 1;
cd112cef 2307 }
37466447
BW
2308 if (xfrm_msg)
2309 strbuf_addstr(&header, xfrm_msg);
3e97c7c6 2310
6973dcae
JH
2311 /*
2312 * we do not run diff between different kind
2313 * of objects.
2314 */
2315 if ((one->mode ^ two->mode) & S_IFMT)
2316 goto free_ab_and_return;
0c01857d 2317 if (complete_rewrite &&
3aa1f7ca
JK
2318 (textconv_one || !diff_filespec_is_binary(one)) &&
2319 (textconv_two || !diff_filespec_is_binary(two))) {
3e97c7c6
GB
2320 fprintf(o->file, "%s", header.buf);
2321 strbuf_reset(&header);
3aa1f7ca
JK
2322 emit_rewrite_diff(name_a, name_b, one, two,
2323 textconv_one, textconv_two, o);
34a5e1a2 2324 o->found_changes = 1;
6973dcae
JH
2325 goto free_ab_and_return;
2326 }
2327 }
2328
467ddc14
JH
2329 if (o->irreversible_delete && lbl[1][0] == '/') {
2330 fprintf(o->file, "%s", header.buf);
2331 strbuf_reset(&header);
2332 goto free_ab_and_return;
2333 } else if (!DIFF_OPT_TST(o, TEXT) &&
b3373982
JK
2334 ( (!textconv_one && diff_filespec_is_binary(one)) ||
2335 (!textconv_two && diff_filespec_is_binary(two)) )) {
2336 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2337 die("unable to read files to diff");
0660626c
JH
2338 /* Quite common confusing case */
2339 if (mf1.size == mf2.size &&
296c6bb2
CC
2340 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
2341 if (must_show_header)
2342 fprintf(o->file, "%s", header.buf);
0660626c 2343 goto free_ab_and_return;
296c6bb2 2344 }
3e97c7c6
GB
2345 fprintf(o->file, "%s", header.buf);
2346 strbuf_reset(&header);
8f67f8ae 2347 if (DIFF_OPT_TST(o, BINARY))
7be57610 2348 emit_binary_diff(o->file, &mf1, &mf2, line_prefix);
051308f6 2349 else
7be57610
BY
2350 fprintf(o->file, "%sBinary files %s and %s differ\n",
2351 line_prefix, lbl[0], lbl[1]);
34a5e1a2 2352 o->found_changes = 1;
467ddc14 2353 } else {
6973dcae
JH
2354 /* Crazy xdl interfaces.. */
2355 const char *diffopts = getenv("GIT_DIFF_OPTS");
2356 xpparam_t xpp;
2357 xdemitconf_t xecfg;
6973dcae 2358 struct emit_callback ecbdata;
be58e70d 2359 const struct userdiff_funcname *pe;
f258475a 2360
b3f01ff2 2361 if (must_show_header) {
3e97c7c6
GB
2362 fprintf(o->file, "%s", header.buf);
2363 strbuf_reset(&header);
2364 }
2365
840383b2
JK
2366 mf1.size = fill_textconv(textconv_one, one, &mf1.ptr);
2367 mf2.size = fill_textconv(textconv_two, two, &mf2.ptr);
04427ac8 2368
45e7ca0f
BC
2369 pe = diff_funcname_pattern(one);
2370 if (!pe)
2371 pe = diff_funcname_pattern(two);
6973dcae 2372
9ccd0a88 2373 memset(&xpp, 0, sizeof(xpp));
30b25010 2374 memset(&xecfg, 0, sizeof(xecfg));
cd112cef 2375 memset(&ecbdata, 0, sizeof(ecbdata));
6973dcae 2376 ecbdata.label_path = lbl;
daa0c3d9 2377 ecbdata.color_diff = want_color(o->use_color);
34a5e1a2 2378 ecbdata.found_changesp = &o->found_changes;
cf1b7869 2379 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
690ed843 2380 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
d68fe26f 2381 check_blank_at_eof(&mf1, &mf2, &ecbdata);
a3c158d4 2382 ecbdata.opt = o;
3e97c7c6 2383 ecbdata.header = header.len ? &header : NULL;
582aa00b 2384 xpp.flags = o->xdl_opts;
ee1e5412 2385 xecfg.ctxlen = o->context;
6d0e674a 2386 xecfg.interhunkctxlen = o->interhunkcontext;
6973dcae 2387 xecfg.flags = XDL_EMIT_FUNCNAMES;
14937c2c
RS
2388 if (DIFF_OPT_TST(o, FUNCCONTEXT))
2389 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
45e7ca0f 2390 if (pe)
a013585b 2391 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
6973dcae
JH
2392 if (!diffopts)
2393 ;
cc44c765 2394 else if (!prefixcmp(diffopts, "--unified="))
6973dcae 2395 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
cc44c765 2396 else if (!prefixcmp(diffopts, "-u"))
6973dcae 2397 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
77d1a520
TR
2398 if (o->word_diff)
2399 init_diff_words_data(&ecbdata, o, one, two);
8a3f524b 2400 xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
dfea7900 2401 &xpp, &xecfg);
882749a0 2402 if (o->word_diff)
f59a59e2 2403 free_diff_words_data(&ecbdata);
04427ac8
JK
2404 if (textconv_one)
2405 free(mf1.ptr);
2406 if (textconv_two)
2407 free(mf2.ptr);
8cfe5f1c 2408 xdiff_clear_find_func(&xecfg);
6973dcae
JH
2409 }
2410
2411 free_ab_and_return:
3e97c7c6 2412 strbuf_release(&header);
fc3abdf5
JH
2413 diff_free_filespec_data(one);
2414 diff_free_filespec_data(two);
6973dcae
JH
2415 free(a_one);
2416 free(b_two);
2417 return;
2418}
2419
2420static void builtin_diffstat(const char *name_a, const char *name_b,
2421 struct diff_filespec *one,
2422 struct diff_filespec *two,
710158e3 2423 struct diffstat_t *diffstat,
0d21efa5 2424 struct diff_options *o,
710158e3 2425 int complete_rewrite)
6973dcae
JH
2426{
2427 mmfile_t mf1, mf2;
2428 struct diffstat_file *data;
352ca4e1 2429 int same_contents;
6973dcae
JH
2430
2431 data = diffstat_add(diffstat, name_a, name_b);
2432
2433 if (!one || !two) {
2434 data->is_unmerged = 1;
2435 return;
2436 }
ded0abc7 2437
352ca4e1
ZJS
2438 same_contents = !hashcmp(one->sha1, two->sha1);
2439
ded0abc7 2440 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
ded0abc7 2441 data->is_binary = 1;
352ca4e1 2442 if (same_contents) {
e18872b2
ZJS
2443 data->added = 0;
2444 data->deleted = 0;
2445 } else {
2446 data->added = diff_filespec_size(two);
2447 data->deleted = diff_filespec_size(one);
2448 }
ded0abc7
JK
2449 }
2450
2451 else if (complete_rewrite) {
710158e3
JH
2452 diff_populate_filespec(one, 0);
2453 diff_populate_filespec(two, 0);
2454 data->deleted = count_lines(one->data, one->size);
2455 data->added = count_lines(two->data, two->size);
710158e3 2456 }
6973dcae 2457
352ca4e1 2458 else if (!same_contents) {
6973dcae
JH
2459 /* Crazy xdl interfaces.. */
2460 xpparam_t xpp;
2461 xdemitconf_t xecfg;
6973dcae 2462
ded0abc7
JK
2463 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2464 die("unable to read files to diff");
2465
9ccd0a88 2466 memset(&xpp, 0, sizeof(xpp));
30b25010 2467 memset(&xecfg, 0, sizeof(xecfg));
582aa00b 2468 xpp.flags = o->xdl_opts;
f01cae91
JH
2469 xecfg.ctxlen = o->context;
2470 xecfg.interhunkctxlen = o->interhunkcontext;
8a3f524b 2471 xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
dfea7900 2472 &xpp, &xecfg);
6973dcae 2473 }
fc3abdf5 2474
fc3abdf5
JH
2475 diff_free_filespec_data(one);
2476 diff_free_filespec_data(two);
6973dcae
JH
2477}
2478
88246898 2479static void builtin_checkdiff(const char *name_a, const char *name_b,
cd676a51 2480 const char *attr_path,
5ff10dd6
JH
2481 struct diff_filespec *one,
2482 struct diff_filespec *two,
2483 struct diff_options *o)
88246898
JS
2484{
2485 mmfile_t mf1, mf2;
2486 struct checkdiff_t data;
2487
2488 if (!two)
2489 return;
2490
2491 memset(&data, 0, sizeof(data));
88246898
JS
2492 data.filename = name_b ? name_b : name_a;
2493 data.lineno = 0;
1ba111d1 2494 data.o = o;
cd676a51 2495 data.ws_rule = whitespace_rule(attr_path);
a757c646 2496 data.conflict_marker_size = ll_merge_marker_size(attr_path);
88246898
JS
2497
2498 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2499 die("unable to read files to diff");
2500
5ff10dd6
JH
2501 /*
2502 * All the other codepaths check both sides, but not checking
2503 * the "old" side here is deliberate. We are checking the newly
2504 * introduced changes, and as long as the "new" side is text, we
2505 * can and should check what it introduces.
2506 */
29a3eefd 2507 if (diff_filespec_is_binary(two))
fc3abdf5 2508 goto free_and_return;
88246898
JS
2509 else {
2510 /* Crazy xdl interfaces.. */
2511 xpparam_t xpp;
2512 xdemitconf_t xecfg;
88246898 2513
9ccd0a88 2514 memset(&xpp, 0, sizeof(xpp));
30b25010 2515 memset(&xecfg, 0, sizeof(xecfg));
c35539eb 2516 xecfg.ctxlen = 1; /* at least one context line */
582aa00b 2517 xpp.flags = 0;
8a3f524b 2518 xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
dfea7900 2519 &xpp, &xecfg);
877f23cc 2520
467babf8 2521 if (data.ws_rule & WS_BLANK_AT_EOF) {
d68fe26f
JH
2522 struct emit_callback ecbdata;
2523 int blank_at_eof;
2524
2525 ecbdata.ws_rule = data.ws_rule;
2526 check_blank_at_eof(&mf1, &mf2, &ecbdata);
8837d335 2527 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
d68fe26f 2528
467babf8
JH
2529 if (blank_at_eof) {
2530 static char *err;
2531 if (!err)
2532 err = whitespace_error_string(WS_BLANK_AT_EOF);
2533 fprintf(o->file, "%s:%d: %s.\n",
2534 data.filename, blank_at_eof, err);
2535 data.status = 1; /* report errors */
2536 }
877f23cc 2537 }
88246898 2538 }
fc3abdf5
JH
2539 free_and_return:
2540 diff_free_filespec_data(one);
2541 diff_free_filespec_data(two);
62c64895
WC
2542 if (data.status)
2543 DIFF_OPT_SET(o, CHECK_FAILED);
88246898
JS
2544}
2545
6973dcae
JH
2546struct diff_filespec *alloc_filespec(const char *path)
2547{
2548 int namelen = strlen(path);
2549 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
2550
2551 memset(spec, 0, sizeof(*spec));
2552 spec->path = (char *)(spec + 1);
2553 memcpy(spec->path, path, namelen+1);
9fb88419 2554 spec->count = 1;
122aa6f9 2555 spec->is_binary = -1;
6973dcae
JH
2556 return spec;
2557}
2558
9fb88419
LT
2559void free_filespec(struct diff_filespec *spec)
2560{
2561 if (!--spec->count) {
2562 diff_free_filespec_data(spec);
2563 free(spec);
2564 }
2565}
2566
6973dcae 2567void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
e5450100 2568 int sha1_valid, unsigned short mode)
6973dcae
JH
2569{
2570 if (mode) {
2571 spec->mode = canon_mode(mode);
e702496e 2572 hashcpy(spec->sha1, sha1);
e5450100 2573 spec->sha1_valid = sha1_valid;
6973dcae
JH
2574 }
2575}
2576
2577/*
5adf317b 2578 * Given a name and sha1 pair, if the index tells us the file in
6973dcae
JH
2579 * the work tree has that object contents, return true, so that
2580 * prepare_temp_file() does not have to inflate and extract.
2581 */
1510fea7 2582static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
6973dcae
JH
2583{
2584 struct cache_entry *ce;
2585 struct stat st;
2586 int pos, len;
2587
150115ad
JH
2588 /*
2589 * We do not read the cache ourselves here, because the
6973dcae
JH
2590 * benchmark with my previous version that always reads cache
2591 * shows that it makes things worse for diff-tree comparing
2592 * two linux-2.6 kernel trees in an already checked out work
2593 * tree. This is because most diff-tree comparisons deal with
2594 * only a small number of files, while reading the cache is
2595 * expensive for a large project, and its cost outweighs the
2596 * savings we get by not inflating the object to a temporary
2597 * file. Practically, this code only helps when we are used
2598 * by diff-cache --cached, which does read the cache before
2599 * calling us.
2600 */
2601 if (!active_cache)
2602 return 0;
2603
1510fea7
SP
2604 /* We want to avoid the working directory if our caller
2605 * doesn't need the data in a normal file, this system
2606 * is rather slow with its stat/open/mmap/close syscalls,
2607 * and the object is contained in a pack file. The pack
2608 * is probably already open and will be faster to obtain
2609 * the data through than the working directory. Loose
2610 * objects however would tend to be slower as they need
2611 * to be individually opened and inflated.
2612 */
cd673c1f 2613 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1))
1510fea7
SP
2614 return 0;
2615
6973dcae
JH
2616 len = strlen(name);
2617 pos = cache_name_pos(name, len);
2618 if (pos < 0)
2619 return 0;
2620 ce = active_cache[pos];
eadb5831
JH
2621
2622 /*
2623 * This is not the sha1 we are looking for, or
2624 * unreusable because it is not a regular file.
2625 */
2626 if (hashcmp(sha1, ce->sha1) || !S_ISREG(ce->ce_mode))
6973dcae 2627 return 0;
eadb5831 2628
150115ad
JH
2629 /*
2630 * If ce is marked as "assume unchanged", there is no
2631 * guarantee that work tree matches what we are looking for.
2632 */
b4d1690d 2633 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
150115ad
JH
2634 return 0;
2635
eadb5831
JH
2636 /*
2637 * If ce matches the file in the work tree, we can reuse it.
6973dcae 2638 */
eadb5831
JH
2639 if (ce_uptodate(ce) ||
2640 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
2641 return 1;
2642
2643 return 0;
6973dcae
JH
2644}
2645
04786756
LT
2646static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
2647{
2648 int len;
8e08b419
JH
2649 char *data = xmalloc(100), *dirty = "";
2650
2651 /* Are we looking at the work tree? */
85adbf2f 2652 if (s->dirty_submodule)
8e08b419
JH
2653 dirty = "-dirty";
2654
04786756 2655 len = snprintf(data, 100,
8e08b419 2656 "Subproject commit %s%s\n", sha1_to_hex(s->sha1), dirty);
04786756
LT
2657 s->data = data;
2658 s->size = len;
2659 s->should_free = 1;
2660 if (size_only) {
2661 s->data = NULL;
2662 free(data);
2663 }
2664 return 0;
2665}
2666
6973dcae
JH
2667/*
2668 * While doing rename detection and pickaxe operation, we may need to
2669 * grab the data for the blob (or file) for our own in-core comparison.
2670 * diff_filespec has data and size fields for this purpose.
2671 */
2672int diff_populate_filespec(struct diff_filespec *s, int size_only)
2673{
2674 int err = 0;
2675 if (!DIFF_FILE_VALID(s))
2676 die("internal error: asking to populate invalid file.");
2677 if (S_ISDIR(s->mode))
2678 return -1;
2679
6973dcae 2680 if (s->data)
fc3abdf5 2681 return 0;
04786756 2682
6e0b8ed6
JH
2683 if (size_only && 0 < s->size)
2684 return 0;
2685
302b9282 2686 if (S_ISGITLINK(s->mode))
04786756
LT
2687 return diff_populate_gitlink(s, size_only);
2688
6973dcae 2689 if (!s->sha1_valid ||
1510fea7 2690 reuse_worktree_file(s->path, s->sha1, 0)) {
f285a2d7 2691 struct strbuf buf = STRBUF_INIT;
6973dcae
JH
2692 struct stat st;
2693 int fd;
6c510bee 2694
6973dcae
JH
2695 if (lstat(s->path, &st) < 0) {
2696 if (errno == ENOENT) {
2697 err_empty:
2698 err = -1;
2699 empty:
d2543b8e 2700 s->data = (char *)"";
6973dcae
JH
2701 s->size = 0;
2702 return err;
2703 }
2704 }
dc49cd76 2705 s->size = xsize_t(st.st_size);
6973dcae
JH
2706 if (!s->size)
2707 goto empty;
6973dcae 2708 if (S_ISLNK(st.st_mode)) {
cf219d8c
LT
2709 struct strbuf sb = STRBUF_INIT;
2710
2711 if (strbuf_readlink(&sb, s->path, s->size))
6973dcae 2712 goto err_empty;
0956a6db
RS
2713 s->size = sb.len;
2714 s->data = strbuf_detach(&sb, NULL);
cf219d8c 2715 s->should_free = 1;
6973dcae
JH
2716 return 0;
2717 }
cf219d8c
LT
2718 if (size_only)
2719 return 0;
6973dcae
JH
2720 fd = open(s->path, O_RDONLY);
2721 if (fd < 0)
2722 goto err_empty;
c4712e45 2723 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
6973dcae 2724 close(fd);
6973dcae 2725 s->should_munmap = 1;
6c510bee
LT
2726
2727 /*
2728 * Convert from working tree format to canonical git format
2729 */
21e5ad50 2730 if (convert_to_git(s->path, s->data, s->size, &buf, safe_crlf)) {
c32f749f 2731 size_t size = 0;
6c510bee
LT
2732 munmap(s->data, s->size);
2733 s->should_munmap = 0;
c32f749f
RS
2734 s->data = strbuf_detach(&buf, &size);
2735 s->size = size;
6c510bee
LT
2736 s->should_free = 1;
2737 }
6973dcae
JH
2738 }
2739 else {
21666f1a 2740 enum object_type type;
c50c4316 2741 if (size_only) {
21666f1a 2742 type = sha1_object_info(s->sha1, &s->size);
c50c4316
NP
2743 if (type < 0)
2744 die("unable to read %s", sha1_to_hex(s->sha1));
2745 } else {
21666f1a 2746 s->data = read_sha1_file(s->sha1, &type, &s->size);
c50c4316
NP
2747 if (!s->data)
2748 die("unable to read %s", sha1_to_hex(s->sha1));
6973dcae
JH
2749 s->should_free = 1;
2750 }
2751 }
2752 return 0;
2753}
2754
8ae92e63 2755void diff_free_filespec_blob(struct diff_filespec *s)
6973dcae
JH
2756{
2757 if (s->should_free)
2758 free(s->data);
2759 else if (s->should_munmap)
2760 munmap(s->data, s->size);
fc3abdf5
JH
2761
2762 if (s->should_free || s->should_munmap) {
2763 s->should_free = s->should_munmap = 0;
2764 s->data = NULL;
2765 }
eede7b7d
JK
2766}
2767
2768void diff_free_filespec_data(struct diff_filespec *s)
2769{
8ae92e63 2770 diff_free_filespec_blob(s);
6973dcae
JH
2771 free(s->cnt_data);
2772 s->cnt_data = NULL;
2773}
2774
4e218f54 2775static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
6973dcae
JH
2776 void *blob,
2777 unsigned long size,
2778 const unsigned char *sha1,
2779 int mode)
2780{
2781 int fd;
4e218f54 2782 struct strbuf buf = STRBUF_INIT;
003b33a8
DA
2783 struct strbuf template = STRBUF_INIT;
2784 char *path_dup = xstrdup(path);
2785 const char *base = basename(path_dup);
6973dcae 2786
003b33a8
DA
2787 /* Generate "XXXXXX_basename.ext" */
2788 strbuf_addstr(&template, "XXXXXX_");
2789 strbuf_addstr(&template, base);
2790
2791 fd = git_mkstemps(temp->tmp_path, PATH_MAX, template.buf,
2792 strlen(base) + 1);
6973dcae 2793 if (fd < 0)
d824cbba 2794 die_errno("unable to create temp-file");
4e218f54
JS
2795 if (convert_to_working_tree(path,
2796 (const char *)blob, (size_t)size, &buf)) {
2797 blob = buf.buf;
2798 size = buf.len;
2799 }
93822c22 2800 if (write_in_full(fd, blob, size) != size)
0721c314 2801 die_errno("unable to write temp-file");
6973dcae
JH
2802 close(fd);
2803 temp->name = temp->tmp_path;
2804 strcpy(temp->hex, sha1_to_hex(sha1));
2805 temp->hex[40] = 0;
2806 sprintf(temp->mode, "%06o", mode);
4e218f54 2807 strbuf_release(&buf);
003b33a8
DA
2808 strbuf_release(&template);
2809 free(path_dup);
6973dcae
JH
2810}
2811
479b0ae8
JK
2812static struct diff_tempfile *prepare_temp_file(const char *name,
2813 struct diff_filespec *one)
6973dcae 2814{
479b0ae8
JK
2815 struct diff_tempfile *temp = claim_diff_tempfile();
2816
6973dcae
JH
2817 if (!DIFF_FILE_VALID(one)) {
2818 not_a_valid_file:
2819 /* A '-' entry produces this for file-2, and
2820 * a '+' entry produces this for file-1.
2821 */
2822 temp->name = "/dev/null";
2823 strcpy(temp->hex, ".");
2824 strcpy(temp->mode, ".");
479b0ae8
JK
2825 return temp;
2826 }
2827
2828 if (!remove_tempfile_installed) {
2829 atexit(remove_tempfile);
57b235a4 2830 sigchain_push_common(remove_tempfile_on_signal);
479b0ae8 2831 remove_tempfile_installed = 1;
6973dcae
JH
2832 }
2833
2834 if (!one->sha1_valid ||
1510fea7 2835 reuse_worktree_file(name, one->sha1, 1)) {
6973dcae
JH
2836 struct stat st;
2837 if (lstat(name, &st) < 0) {
2838 if (errno == ENOENT)
2839 goto not_a_valid_file;
d824cbba 2840 die_errno("stat(%s)", name);
6973dcae
JH
2841 }
2842 if (S_ISLNK(st.st_mode)) {
3cd7388d
JK
2843 struct strbuf sb = STRBUF_INIT;
2844 if (strbuf_readlink(&sb, name, st.st_size) < 0)
0721c314 2845 die_errno("readlink(%s)", name);
3cd7388d 2846 prep_temp_blob(name, temp, sb.buf, sb.len,
6973dcae
JH
2847 (one->sha1_valid ?
2848 one->sha1 : null_sha1),
2849 (one->sha1_valid ?
2850 one->mode : S_IFLNK));
3cd7388d 2851 strbuf_release(&sb);
6973dcae
JH
2852 }
2853 else {
2854 /* we can borrow from the file in the work tree */
2855 temp->name = name;
2856 if (!one->sha1_valid)
2857 strcpy(temp->hex, sha1_to_hex(null_sha1));
2858 else
2859 strcpy(temp->hex, sha1_to_hex(one->sha1));
2860 /* Even though we may sometimes borrow the
2861 * contents from the work tree, we always want
2862 * one->mode. mode is trustworthy even when
2863 * !(one->sha1_valid), as long as
2864 * DIFF_FILE_VALID(one).
2865 */
2866 sprintf(temp->mode, "%06o", one->mode);
2867 }
479b0ae8 2868 return temp;
6973dcae
JH
2869 }
2870 else {
2871 if (diff_populate_filespec(one, 0))
2872 die("cannot read data blob for %s", one->path);
4e218f54 2873 prep_temp_blob(name, temp, one->data, one->size,
6973dcae
JH
2874 one->sha1, one->mode);
2875 }
479b0ae8 2876 return temp;
6973dcae
JH
2877}
2878
6973dcae
JH
2879/* An external diff command takes:
2880 *
2881 * diff-cmd name infile1 infile1-sha1 infile1-mode \
2882 * infile2 infile2-sha1 infile2-mode [ rename-to ]
2883 *
2884 */
2885static void run_external_diff(const char *pgm,
2886 const char *name,
2887 const char *other,
2888 struct diff_filespec *one,
2889 struct diff_filespec *two,
2890 const char *xfrm_msg,
2891 int complete_rewrite)
2892{
2893 const char *spawn_arg[10];
6973dcae 2894 int retval;
6973dcae
JH
2895 const char **arg = &spawn_arg[0];
2896
6973dcae 2897 if (one && two) {
479b0ae8
JK
2898 struct diff_tempfile *temp_one, *temp_two;
2899 const char *othername = (other ? other : name);
2900 temp_one = prepare_temp_file(name, one);
2901 temp_two = prepare_temp_file(othername, two);
6973dcae
JH
2902 *arg++ = pgm;
2903 *arg++ = name;
479b0ae8
JK
2904 *arg++ = temp_one->name;
2905 *arg++ = temp_one->hex;
2906 *arg++ = temp_one->mode;
2907 *arg++ = temp_two->name;
2908 *arg++ = temp_two->hex;
2909 *arg++ = temp_two->mode;
6973dcae
JH
2910 if (other) {
2911 *arg++ = other;
2912 *arg++ = xfrm_msg;
2913 }
2914 } else {
2915 *arg++ = pgm;
2916 *arg++ = name;
2917 }
2918 *arg = NULL;
d5535ec7 2919 fflush(NULL);
7ed7fac4 2920 retval = run_command_v_opt(spawn_arg, RUN_USING_SHELL);
6973dcae
JH
2921 remove_tempfile();
2922 if (retval) {
2923 fprintf(stderr, "external diff died, stopping at %s.\n", name);
2924 exit(1);
2925 }
2926}
2927
b67b9612
JH
2928static int similarity_index(struct diff_filepair *p)
2929{
2930 return p->score * 100 / MAX_SCORE;
2931}
2932
2933static void fill_metainfo(struct strbuf *msg,
2934 const char *name,
2935 const char *other,
2936 struct diff_filespec *one,
2937 struct diff_filespec *two,
2938 struct diff_options *o,
37466447 2939 struct diff_filepair *p,
5977744d 2940 int *must_show_header,
37466447 2941 int use_color)
b67b9612 2942{
37466447
BW
2943 const char *set = diff_get_color(use_color, DIFF_METAINFO);
2944 const char *reset = diff_get_color(use_color, DIFF_RESET);
7be57610
BY
2945 struct strbuf *msgbuf;
2946 char *line_prefix = "";
2947
296c6bb2 2948 *must_show_header = 1;
7be57610
BY
2949 if (o->output_prefix) {
2950 msgbuf = o->output_prefix(o, o->output_prefix_data);
2951 line_prefix = msgbuf->buf;
2952 }
b67b9612
JH
2953 strbuf_init(msg, PATH_MAX * 2 + 300);
2954 switch (p->status) {
2955 case DIFF_STATUS_COPIED:
98ad90fb
JH
2956 strbuf_addf(msg, "%s%ssimilarity index %d%%",
2957 line_prefix, set, similarity_index(p));
2958 strbuf_addf(msg, "%s\n%s%scopy from ",
2959 reset, line_prefix, set);
b67b9612 2960 quote_c_style(name, msg, NULL, 0);
98ad90fb 2961 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
b67b9612 2962 quote_c_style(other, msg, NULL, 0);
37466447 2963 strbuf_addf(msg, "%s\n", reset);
b67b9612
JH
2964 break;
2965 case DIFF_STATUS_RENAMED:
98ad90fb
JH
2966 strbuf_addf(msg, "%s%ssimilarity index %d%%",
2967 line_prefix, set, similarity_index(p));
2968 strbuf_addf(msg, "%s\n%s%srename from ",
2969 reset, line_prefix, set);
b67b9612 2970 quote_c_style(name, msg, NULL, 0);
98ad90fb
JH
2971 strbuf_addf(msg, "%s\n%s%srename to ",
2972 reset, line_prefix, set);
b67b9612 2973 quote_c_style(other, msg, NULL, 0);
37466447 2974 strbuf_addf(msg, "%s\n", reset);
b67b9612
JH
2975 break;
2976 case DIFF_STATUS_MODIFIED:
2977 if (p->score) {
98ad90fb
JH
2978 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
2979 line_prefix,
37466447 2980 set, similarity_index(p), reset);
b67b9612
JH
2981 break;
2982 }
2983 /* fallthru */
2984 default:
296c6bb2 2985 *must_show_header = 0;
b67b9612
JH
2986 }
2987 if (one && two && hashcmp(one->sha1, two->sha1)) {
2988 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
2989
2990 if (DIFF_OPT_TST(o, BINARY)) {
2991 mmfile_t mf;
2992 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
2993 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
2994 abbrev = 40;
2995 }
e13f38a3 2996 strbuf_addf(msg, "%s%sindex %s..", line_prefix, set,
3e5a188f
JH
2997 find_unique_abbrev(one->sha1, abbrev));
2998 strbuf_addstr(msg, find_unique_abbrev(two->sha1, abbrev));
b67b9612
JH
2999 if (one->mode == two->mode)
3000 strbuf_addf(msg, " %06o", one->mode);
37466447 3001 strbuf_addf(msg, "%s\n", reset);
b67b9612 3002 }
b67b9612
JH
3003}
3004
6973dcae
JH
3005static void run_diff_cmd(const char *pgm,
3006 const char *name,
3007 const char *other,
cd676a51 3008 const char *attr_path,
6973dcae
JH
3009 struct diff_filespec *one,
3010 struct diff_filespec *two,
b67b9612 3011 struct strbuf *msg,
051308f6 3012 struct diff_options *o,
b67b9612 3013 struct diff_filepair *p)
6973dcae 3014{
b67b9612
JH
3015 const char *xfrm_msg = NULL;
3016 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
296c6bb2 3017 int must_show_header = 0;
b67b9612 3018
bd8c1a9b
JH
3019
3020 if (DIFF_OPT_TST(o, ALLOW_EXTERNAL)) {
be58e70d
JK
3021 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
3022 if (drv && drv->external)
3023 pgm = drv->external;
f1af60bd
JH
3024 }
3025
37466447
BW
3026 if (msg) {
3027 /*
3028 * don't use colors when the header is intended for an
3029 * external diff driver
3030 */
3031 fill_metainfo(msg, name, other, one, two, o, p,
5977744d 3032 &must_show_header,
daa0c3d9 3033 want_color(o->use_color) && !pgm);
37466447
BW
3034 xfrm_msg = msg->len ? msg->buf : NULL;
3035 }
3036
6973dcae
JH
3037 if (pgm) {
3038 run_external_diff(pgm, name, other, one, two, xfrm_msg,
3039 complete_rewrite);
3040 return;
3041 }
3042 if (one && two)
3043 builtin_diff(name, other ? other : name,
296c6bb2
CC
3044 one, two, xfrm_msg, must_show_header,
3045 o, complete_rewrite);
6973dcae 3046 else
c0c77734 3047 fprintf(o->file, "* Unmerged path %s\n", name);
6973dcae
JH
3048}
3049
3050static void diff_fill_sha1_info(struct diff_filespec *one)
3051{
3052 if (DIFF_FILE_VALID(one)) {
3053 if (!one->sha1_valid) {
3054 struct stat st;
4682d852 3055 if (one->is_stdin) {
5332b2af
JS
3056 hashcpy(one->sha1, null_sha1);
3057 return;
3058 }
6973dcae 3059 if (lstat(one->path, &st) < 0)
0721c314 3060 die_errno("stat '%s'", one->path);
6973dcae 3061 if (index_path(one->sha1, one->path, &st, 0))
d7530708 3062 die("cannot hash %s", one->path);
6973dcae
JH
3063 }
3064 }
3065 else
e702496e 3066 hashclr(one->sha1);
6973dcae
JH
3067}
3068
cd676a51
JH
3069static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
3070{
3071 /* Strip the prefix but do not molest /dev/null and absolute paths */
d8faea9d 3072 if (*namep && **namep != '/') {
cd676a51 3073 *namep += prefix_length;
d8faea9d
JN
3074 if (**namep == '/')
3075 ++*namep;
3076 }
3077 if (*otherp && **otherp != '/') {
cd676a51 3078 *otherp += prefix_length;
d8faea9d
JN
3079 if (**otherp == '/')
3080 ++*otherp;
3081 }
cd676a51
JH
3082}
3083
6973dcae
JH
3084static void run_diff(struct diff_filepair *p, struct diff_options *o)
3085{
3086 const char *pgm = external_diff();
663af342 3087 struct strbuf msg;
663af342
PH
3088 struct diff_filespec *one = p->one;
3089 struct diff_filespec *two = p->two;
6973dcae
JH
3090 const char *name;
3091 const char *other;
cd676a51 3092 const char *attr_path;
663af342 3093
cd676a51
JH
3094 name = p->one->path;
3095 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
3096 attr_path = name;
3097 if (o->prefix_length)
3098 strip_prefix(o->prefix_length, &name, &other);
6973dcae 3099
bd8c1a9b
JH
3100 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
3101 pgm = NULL;
3102
6973dcae 3103 if (DIFF_PAIR_UNMERGED(p)) {
cd676a51 3104 run_diff_cmd(pgm, name, NULL, attr_path,
b67b9612 3105 NULL, NULL, NULL, o, p);
6973dcae
JH
3106 return;
3107 }
3108
6973dcae
JH
3109 diff_fill_sha1_info(one);
3110 diff_fill_sha1_info(two);
3111
6973dcae
JH
3112 if (!pgm &&
3113 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
3114 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
b67b9612
JH
3115 /*
3116 * a filepair that changes between file and symlink
6973dcae
JH
3117 * needs to be split into deletion and creation.
3118 */
3119 struct diff_filespec *null = alloc_filespec(two->path);
cd676a51 3120 run_diff_cmd(NULL, name, other, attr_path,
b67b9612 3121 one, null, &msg, o, p);
6973dcae 3122 free(null);
b67b9612
JH
3123 strbuf_release(&msg);
3124
6973dcae 3125 null = alloc_filespec(one->path);
cd676a51 3126 run_diff_cmd(NULL, name, other, attr_path,
b67b9612 3127 null, two, &msg, o, p);
6973dcae
JH
3128 free(null);
3129 }
3130 else
cd676a51 3131 run_diff_cmd(pgm, name, other, attr_path,
b67b9612 3132 one, two, &msg, o, p);
6973dcae 3133
663af342 3134 strbuf_release(&msg);
6973dcae
JH
3135}
3136
3137static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
3138 struct diffstat_t *diffstat)
3139{
3140 const char *name;
3141 const char *other;
710158e3 3142 int complete_rewrite = 0;
6973dcae
JH
3143
3144 if (DIFF_PAIR_UNMERGED(p)) {
3145 /* unmerged */
0d21efa5 3146 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
6973dcae
JH
3147 return;
3148 }
3149
3150 name = p->one->path;
3151 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
3152
cd676a51
JH
3153 if (o->prefix_length)
3154 strip_prefix(o->prefix_length, &name, &other);
3155
6973dcae
JH
3156 diff_fill_sha1_info(p->one);
3157 diff_fill_sha1_info(p->two);
3158
710158e3
JH
3159 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3160 complete_rewrite = 1;
0d21efa5 3161 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
6973dcae
JH
3162}
3163
88246898
JS
3164static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
3165{
3166 const char *name;
3167 const char *other;
cd676a51 3168 const char *attr_path;
88246898
JS
3169
3170 if (DIFF_PAIR_UNMERGED(p)) {
3171 /* unmerged */
3172 return;
3173 }
3174
3175 name = p->one->path;
3176 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
cd676a51
JH
3177 attr_path = other ? other : name;
3178
3179 if (o->prefix_length)
3180 strip_prefix(o->prefix_length, &name, &other);
88246898
JS
3181
3182 diff_fill_sha1_info(p->one);
3183 diff_fill_sha1_info(p->two);
3184
cd676a51 3185 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
88246898
JS
3186}
3187
6973dcae
JH
3188void diff_setup(struct diff_options *options)
3189{
be4f2b40 3190 memcpy(options, &default_diff_options, sizeof(*options));
c0c77734
DB
3191
3192 options->file = stdout;
3193
6973dcae
JH
3194 options->line_termination = '\n';
3195 options->break_opt = -1;
3196 options->rename_limit = -1;
712d2c7d 3197 options->dirstat_permille = diff_dirstat_permille_default;
6468a4e5 3198 options->context = diff_context_default;
90d43b07 3199 DIFF_OPT_SET(options, RENAME_EMPTY);
6973dcae
JH
3200
3201 options->change = diff_change;
3202 options->add_remove = diff_addremove;
f1c96261 3203 options->use_color = diff_use_color_default;
b68ea12e 3204 options->detect_rename = diff_detect_rename_default;
eab9a40b 3205
f89504dd
EC
3206 if (diff_no_prefix) {
3207 options->a_prefix = options->b_prefix = "";
3208 } else if (!diff_mnemonic_prefix) {
a5a818ee
JH
3209 options->a_prefix = "a/";
3210 options->b_prefix = "b/";
3211 }
6973dcae
JH
3212}
3213
28452655 3214void diff_setup_done(struct diff_options *options)
6973dcae 3215{
d7de00f7
TH
3216 int count = 0;
3217
3218 if (options->output_format & DIFF_FORMAT_NAME)
3219 count++;
3220 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
3221 count++;
3222 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
3223 count++;
3224 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
3225 count++;
3226 if (count > 1)
3227 die("--name-only, --name-status, --check and -s are mutually exclusive");
3228
f245194f
JH
3229 /*
3230 * Most of the time we can say "there are changes"
3231 * only by checking if there are changed paths, but
3232 * --ignore-whitespace* options force us to look
97bf2a08 3233 * inside contents.
f245194f
JH
3234 */
3235
3236 if (DIFF_XDL_TST(options, IGNORE_WHITESPACE) ||
3237 DIFF_XDL_TST(options, IGNORE_WHITESPACE_CHANGE) ||
3238 DIFF_XDL_TST(options, IGNORE_WHITESPACE_AT_EOL))
3239 DIFF_OPT_SET(options, DIFF_FROM_CONTENTS);
3240 else
3241 DIFF_OPT_CLR(options, DIFF_FROM_CONTENTS);
3242
8f67f8ae 3243 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
03b9d560
JH
3244 options->detect_rename = DIFF_DETECT_COPY;
3245
cd676a51
JH
3246 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
3247 options->prefix = NULL;
3248 if (options->prefix)
3249 options->prefix_length = strlen(options->prefix);
3250 else
3251 options->prefix_length = 0;
3252
c6744349
TH
3253 if (options->output_format & (DIFF_FORMAT_NAME |
3254 DIFF_FORMAT_NAME_STATUS |
3255 DIFF_FORMAT_CHECKDIFF |
3256 DIFF_FORMAT_NO_OUTPUT))
3257 options->output_format &= ~(DIFF_FORMAT_RAW |
74e2abe5 3258 DIFF_FORMAT_NUMSTAT |
c6744349 3259 DIFF_FORMAT_DIFFSTAT |
ebd124c6 3260 DIFF_FORMAT_SHORTSTAT |
7df7c019 3261 DIFF_FORMAT_DIRSTAT |
c6744349
TH
3262 DIFF_FORMAT_SUMMARY |
3263 DIFF_FORMAT_PATCH);
3264
6973dcae
JH
3265 /*
3266 * These cases always need recursive; we do not drop caller-supplied
3267 * recursive bits for other formats here.
3268 */
c6744349 3269 if (options->output_format & (DIFF_FORMAT_PATCH |
74e2abe5 3270 DIFF_FORMAT_NUMSTAT |
c6744349 3271 DIFF_FORMAT_DIFFSTAT |
ebd124c6 3272 DIFF_FORMAT_SHORTSTAT |
7df7c019 3273 DIFF_FORMAT_DIRSTAT |
d7014dc0 3274 DIFF_FORMAT_SUMMARY |
c6744349 3275 DIFF_FORMAT_CHECKDIFF))
8f67f8ae 3276 DIFF_OPT_SET(options, RECURSIVE);
5e363541 3277 /*
3969cf7d 3278 * Also pickaxe would not work very well if you do not say recursive
5e363541 3279 */
3969cf7d 3280 if (options->pickaxe)
8f67f8ae 3281 DIFF_OPT_SET(options, RECURSIVE);
ae6d5c1b
JL
3282 /*
3283 * When patches are generated, submodules diffed against the work tree
3284 * must be checked for dirtiness too so it can be shown in the output
3285 */
3286 if (options->output_format & DIFF_FORMAT_PATCH)
3287 DIFF_OPT_SET(options, DIRTY_SUBMODULES);
5e363541 3288
6973dcae
JH
3289 if (options->detect_rename && options->rename_limit < 0)
3290 options->rename_limit = diff_rename_limit_default;
3291 if (options->setup & DIFF_SETUP_USE_CACHE) {
3292 if (!active_cache)
3293 /* read-cache does not die even when it fails
3294 * so it is safe for us to do this here. Also
3295 * it does not smudge active_cache or active_nr
3296 * when it fails, so we do not have to worry about
3297 * cleaning it up ourselves either.
3298 */
3299 read_cache();
3300 }
6973dcae
JH
3301 if (options->abbrev <= 0 || 40 < options->abbrev)
3302 options->abbrev = 40; /* full */
3303
68aacb2f
JH
3304 /*
3305 * It does not make sense to show the first hit we happened
3306 * to have found. It does not make sense not to return with
3307 * exit code in such a case either.
3308 */
90b19941 3309 if (DIFF_OPT_TST(options, QUICK)) {
68aacb2f 3310 options->output_format = DIFF_FORMAT_NO_OUTPUT;
8f67f8ae 3311 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
68aacb2f 3312 }
6973dcae
JH
3313}
3314
d2543b8e 3315static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
ee1e5412
LT
3316{
3317 char c, *eq;
3318 int len;
3319
3320 if (*arg != '-')
3321 return 0;
3322 c = *++arg;
3323 if (!c)
3324 return 0;
3325 if (c == arg_short) {
3326 c = *++arg;
3327 if (!c)
3328 return 1;
3329 if (val && isdigit(c)) {
3330 char *end;
3331 int n = strtoul(arg, &end, 10);
3332 if (*end)
3333 return 0;
3334 *val = n;
3335 return 1;
3336 }
3337 return 0;
3338 }
3339 if (c != '-')
3340 return 0;
3341 arg++;
3342 eq = strchr(arg, '=');
3343 if (eq)
3344 len = eq - arg;
3345 else
3346 len = strlen(arg);
3347 if (!len || strncmp(arg, arg_long, len))
3348 return 0;
3349 if (eq) {
3350 int n;
3351 char *end;
3352 if (!isdigit(*++eq))
3353 return 0;
3354 n = strtoul(eq, &end, 10);
3355 if (*end)
3356 return 0;
3357 *val = n;
3358 }
3359 return 1;
3360}
3361
16befb8b
JH
3362static int diff_scoreopt_parse(const char *opt);
3363
dea007fb
MM
3364static inline int short_opt(char opt, const char **argv,
3365 const char **optarg)
3366{
3367 const char *arg = argv[0];
3368 if (arg[0] != '-' || arg[1] != opt)
3369 return 0;
3370 if (arg[2] != '\0') {
3371 *optarg = arg + 2;
3372 return 1;
3373 }
3374 if (!argv[1])
3375 die("Option '%c' requires a value", opt);
3376 *optarg = argv[1];
3377 return 2;
3378}
3379
3380int parse_long_opt(const char *opt, const char **argv,
3381 const char **optarg)
3382{
3383 const char *arg = argv[0];
3384 if (arg[0] != '-' || arg[1] != '-')
3385 return 0;
3386 arg += strlen("--");
3387 if (prefixcmp(arg, opt))
3388 return 0;
3389 arg += strlen(opt);
3390 if (*arg == '=') { /* sticked form: --option=value */
3391 *optarg = arg + 1;
3392 return 1;
3393 }
3394 if (*arg != '\0')
3395 return 0;
3396 /* separate form: --option value */
3397 if (!argv[1])
3398 die("Option '--%s' requires a value", opt);
3399 *optarg = argv[1];
3400 return 2;
3401}
3402
4d7f7a4a
JN
3403static int stat_opt(struct diff_options *options, const char **av)
3404{
3405 const char *arg = av[0];
3406 char *end;
3407 int width = options->stat_width;
3408 int name_width = options->stat_name_width;
969fe57b 3409 int graph_width = options->stat_graph_width;
808e1db2 3410 int count = options->stat_count;
1e57208e 3411 int argcount = 1;
4d7f7a4a
JN
3412
3413 arg += strlen("--stat");
3414 end = (char *)arg;
3415
3416 switch (*arg) {
3417 case '-':
1e57208e
MM
3418 if (!prefixcmp(arg, "-width")) {
3419 arg += strlen("-width");
3420 if (*arg == '=')
3421 width = strtoul(arg + 1, &end, 10);
3422 else if (!*arg && !av[1])
3423 die("Option '--stat-width' requires a value");
3424 else if (!*arg) {
3425 width = strtoul(av[1], &end, 10);
3426 argcount = 2;
3427 }
3428 } else if (!prefixcmp(arg, "-name-width")) {
3429 arg += strlen("-name-width");
3430 if (*arg == '=')
3431 name_width = strtoul(arg + 1, &end, 10);
3432 else if (!*arg && !av[1])
3433 die("Option '--stat-name-width' requires a value");
3434 else if (!*arg) {
3435 name_width = strtoul(av[1], &end, 10);
3436 argcount = 2;
3437 }
969fe57b
ZJS
3438 } else if (!prefixcmp(arg, "-graph-width")) {
3439 arg += strlen("-graph-width");
3440 if (*arg == '=')
3441 graph_width = strtoul(arg + 1, &end, 10);
3442 else if (!*arg && !av[1])
3443 die("Option '--stat-graph-width' requires a value");
3444 else if (!*arg) {
3445 graph_width = strtoul(av[1], &end, 10);
3446 argcount = 2;
3447 }
808e1db2
MG
3448 } else if (!prefixcmp(arg, "-count")) {
3449 arg += strlen("-count");
3450 if (*arg == '=')
3451 count = strtoul(arg + 1, &end, 10);
3452 else if (!*arg && !av[1])
3453 die("Option '--stat-count' requires a value");
3454 else if (!*arg) {
3455 count = strtoul(av[1], &end, 10);
3456 argcount = 2;
3457 }
1e57208e 3458 }
4d7f7a4a
JN
3459 break;
3460 case '=':
3461 width = strtoul(arg+1, &end, 10);
3462 if (*end == ',')
3463 name_width = strtoul(end+1, &end, 10);
808e1db2
MG
3464 if (*end == ',')
3465 count = strtoul(end+1, &end, 10);
4d7f7a4a
JN
3466 }
3467
3468 /* Important! This checks all the error cases! */
3469 if (*end)
3470 return 0;
3471 options->output_format |= DIFF_FORMAT_DIFFSTAT;
3472 options->stat_name_width = name_width;
969fe57b 3473 options->stat_graph_width = graph_width;
4d7f7a4a 3474 options->stat_width = width;
808e1db2 3475 options->stat_count = count;
1e57208e 3476 return argcount;
4d7f7a4a
JN
3477}
3478
333f3fb0
JH
3479static int parse_dirstat_opt(struct diff_options *options, const char *params)
3480{
51670fc8
JH
3481 struct strbuf errmsg = STRBUF_INIT;
3482 if (parse_dirstat_params(options, params, &errmsg))
7478ac57 3483 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
51670fc8
JH
3484 errmsg.buf);
3485 strbuf_release(&errmsg);
333f3fb0
JH
3486 /*
3487 * The caller knows a dirstat-related option is given from the command
3488 * line; allow it to say "return this_function();"
3489 */
3490 options->output_format |= DIFF_FORMAT_DIRSTAT;
3491 return 1;
3492}
3493
c47ef57c
RR
3494static int parse_submodule_opt(struct diff_options *options, const char *value)
3495{
3496 if (parse_submodule_params(options, value))
3497 die(_("Failed to parse --submodule option parameter: '%s'"),
3498 value);
3499 return 1;
3500}
3501
6973dcae
JH
3502int diff_opt_parse(struct diff_options *options, const char **av, int ac)
3503{
3504 const char *arg = av[0];
dea007fb
MM
3505 const char *optarg;
3506 int argcount;
d054680c
PH
3507
3508 /* Output format options */
1c9eecff 3509 if (!strcmp(arg, "-p") || !strcmp(arg, "-u") || !strcmp(arg, "--patch"))
c6744349 3510 options->output_format |= DIFF_FORMAT_PATCH;
ee1e5412 3511 else if (opt_arg(arg, 'U', "unified", &options->context))
c6744349 3512 options->output_format |= DIFF_FORMAT_PATCH;
a610786f
TH
3513 else if (!strcmp(arg, "--raw"))
3514 options->output_format |= DIFF_FORMAT_RAW;
8f67f8ae 3515 else if (!strcmp(arg, "--patch-with-raw"))
c6744349 3516 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
8f67f8ae 3517 else if (!strcmp(arg, "--numstat"))
74e2abe5 3518 options->output_format |= DIFF_FORMAT_NUMSTAT;
8f67f8ae 3519 else if (!strcmp(arg, "--shortstat"))
ebd124c6 3520 options->output_format |= DIFF_FORMAT_SHORTSTAT;
333f3fb0
JH
3521 else if (!strcmp(arg, "-X") || !strcmp(arg, "--dirstat"))
3522 return parse_dirstat_opt(options, "");
3523 else if (!prefixcmp(arg, "-X"))
3524 return parse_dirstat_opt(options, arg + 2);
3525 else if (!prefixcmp(arg, "--dirstat="))
3526 return parse_dirstat_opt(options, arg + 10);
3527 else if (!strcmp(arg, "--cumulative"))
3528 return parse_dirstat_opt(options, "cumulative");
3529 else if (!strcmp(arg, "--dirstat-by-file"))
3530 return parse_dirstat_opt(options, "files");
3531 else if (!prefixcmp(arg, "--dirstat-by-file=")) {
3532 parse_dirstat_opt(options, "files");
3533 return parse_dirstat_opt(options, arg + 18);
f88d225f 3534 }
d054680c
PH
3535 else if (!strcmp(arg, "--check"))
3536 options->output_format |= DIFF_FORMAT_CHECKDIFF;
3537 else if (!strcmp(arg, "--summary"))
3538 options->output_format |= DIFF_FORMAT_SUMMARY;
3539 else if (!strcmp(arg, "--patch-with-stat"))
3540 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
3541 else if (!strcmp(arg, "--name-only"))
3542 options->output_format |= DIFF_FORMAT_NAME;
3543 else if (!strcmp(arg, "--name-status"))
3544 options->output_format |= DIFF_FORMAT_NAME_STATUS;
3545 else if (!strcmp(arg, "-s"))
3546 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
4d7f7a4a 3547 else if (!prefixcmp(arg, "--stat"))
808e1db2 3548 /* --stat, --stat-width, --stat-name-width, or --stat-count */
4d7f7a4a 3549 return stat_opt(options, av);
d054680c
PH
3550
3551 /* renames options */
37ab5156
KB
3552 else if (!prefixcmp(arg, "-B") || !prefixcmp(arg, "--break-rewrites=") ||
3553 !strcmp(arg, "--break-rewrites")) {
8f67f8ae 3554 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
07cd7265 3555 return error("invalid argument to -B: %s", arg+2);
6973dcae 3556 }
f611ddc7
YD
3557 else if (!prefixcmp(arg, "-M") || !prefixcmp(arg, "--find-renames=") ||
3558 !strcmp(arg, "--find-renames")) {
8f67f8ae 3559 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
07cd7265 3560 return error("invalid argument to -M: %s", arg+2);
6973dcae
JH
3561 options->detect_rename = DIFF_DETECT_RENAME;
3562 }
467ddc14
JH
3563 else if (!strcmp(arg, "-D") || !strcmp(arg, "--irreversible-delete")) {
3564 options->irreversible_delete = 1;
3565 }
f611ddc7
YD
3566 else if (!prefixcmp(arg, "-C") || !prefixcmp(arg, "--find-copies=") ||
3567 !strcmp(arg, "--find-copies")) {
ca6c0970 3568 if (options->detect_rename == DIFF_DETECT_COPY)
8f67f8ae
PH
3569 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
3570 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
07cd7265 3571 return error("invalid argument to -C: %s", arg+2);
6973dcae
JH
3572 options->detect_rename = DIFF_DETECT_COPY;
3573 }
d054680c
PH
3574 else if (!strcmp(arg, "--no-renames"))
3575 options->detect_rename = 0;
90d43b07
JK
3576 else if (!strcmp(arg, "--rename-empty"))
3577 DIFF_OPT_SET(options, RENAME_EMPTY);
3578 else if (!strcmp(arg, "--no-rename-empty"))
3579 DIFF_OPT_CLR(options, RENAME_EMPTY);
cd676a51
JH
3580 else if (!strcmp(arg, "--relative"))
3581 DIFF_OPT_SET(options, RELATIVE_NAME);
c0cb4a06
JH
3582 else if (!prefixcmp(arg, "--relative=")) {
3583 DIFF_OPT_SET(options, RELATIVE_NAME);
3584 options->prefix = arg + 11;
3585 }
d054680c
PH
3586
3587 /* xdiff options */
81b568c8
JH
3588 else if (!strcmp(arg, "--minimal"))
3589 DIFF_XDL_SET(options, NEED_MINIMAL);
3590 else if (!strcmp(arg, "--no-minimal"))
3591 DIFF_XDL_CLR(options, NEED_MINIMAL);
d054680c 3592 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
628d5c2b 3593 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
d054680c 3594 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
628d5c2b 3595 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
d054680c 3596 else if (!strcmp(arg, "--ignore-space-at-eol"))
628d5c2b 3597 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
34292bdd 3598 else if (!strcmp(arg, "--patience"))
307ab20b 3599 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
8c912eea 3600 else if (!strcmp(arg, "--histogram"))
307ab20b 3601 options->xdl_opts = DIFF_WITH_ALG(options, HISTOGRAM_DIFF);
d054680c
PH
3602
3603 /* flags options */
3604 else if (!strcmp(arg, "--binary")) {
3605 options->output_format |= DIFF_FORMAT_PATCH;
3606 DIFF_OPT_SET(options, BINARY);
3607 }
3608 else if (!strcmp(arg, "--full-index"))
3609 DIFF_OPT_SET(options, FULL_INDEX);
3610 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
3611 DIFF_OPT_SET(options, TEXT);
3612 else if (!strcmp(arg, "-R"))
3613 DIFF_OPT_SET(options, REVERSE_DIFF);
6973dcae 3614 else if (!strcmp(arg, "--find-copies-harder"))
8f67f8ae 3615 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
750f7b66 3616 else if (!strcmp(arg, "--follow"))
8f67f8ae 3617 DIFF_OPT_SET(options, FOLLOW_RENAMES);
cd112cef 3618 else if (!strcmp(arg, "--color"))
f1c96261 3619 options->use_color = 1;
73e9da01 3620 else if (!prefixcmp(arg, "--color=")) {
e269eb79 3621 int value = git_config_colorbool(NULL, arg+8);
daa0c3d9 3622 if (value < 0)
73e9da01 3623 return error("option `color' expects \"always\", \"auto\", or \"never\"");
daa0c3d9 3624 options->use_color = value;
73e9da01 3625 }
fef88bb0 3626 else if (!strcmp(arg, "--no-color"))
f1c96261 3627 options->use_color = 0;
628d5c2b 3628 else if (!strcmp(arg, "--color-words")) {
f1c96261 3629 options->use_color = 1;
882749a0 3630 options->word_diff = DIFF_WORDS_COLOR;
628d5c2b 3631 }
2b6a5417 3632 else if (!prefixcmp(arg, "--color-words=")) {
f1c96261 3633 options->use_color = 1;
882749a0 3634 options->word_diff = DIFF_WORDS_COLOR;
2b6a5417
JS
3635 options->word_regex = arg + 14;
3636 }
882749a0
TR
3637 else if (!strcmp(arg, "--word-diff")) {
3638 if (options->word_diff == DIFF_WORDS_NONE)
3639 options->word_diff = DIFF_WORDS_PLAIN;
3640 }
3641 else if (!prefixcmp(arg, "--word-diff=")) {
3642 const char *type = arg + 12;
3643 if (!strcmp(type, "plain"))
3644 options->word_diff = DIFF_WORDS_PLAIN;
3645 else if (!strcmp(type, "color")) {
f1c96261 3646 options->use_color = 1;
882749a0
TR
3647 options->word_diff = DIFF_WORDS_COLOR;
3648 }
3649 else if (!strcmp(type, "porcelain"))
3650 options->word_diff = DIFF_WORDS_PORCELAIN;
3651 else if (!strcmp(type, "none"))
3652 options->word_diff = DIFF_WORDS_NONE;
3653 else
3654 die("bad --word-diff argument: %s", type);
3655 }
dea007fb 3656 else if ((argcount = parse_long_opt("word-diff-regex", av, &optarg))) {
882749a0
TR
3657 if (options->word_diff == DIFF_WORDS_NONE)
3658 options->word_diff = DIFF_WORDS_PLAIN;
dea007fb
MM
3659 options->word_regex = optarg;
3660 return argcount;
882749a0 3661 }
41bbf9d5 3662 else if (!strcmp(arg, "--exit-code"))
8f67f8ae 3663 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
68aacb2f 3664 else if (!strcmp(arg, "--quiet"))
90b19941 3665 DIFF_OPT_SET(options, QUICK);
72909bef 3666 else if (!strcmp(arg, "--ext-diff"))
8f67f8ae 3667 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
72909bef 3668 else if (!strcmp(arg, "--no-ext-diff"))
8f67f8ae 3669 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
e10ea812
JK
3670 else if (!strcmp(arg, "--textconv"))
3671 DIFF_OPT_SET(options, ALLOW_TEXTCONV);
3672 else if (!strcmp(arg, "--no-textconv"))
3673 DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
aee9c7d6
JL
3674 else if (!strcmp(arg, "--ignore-submodules")) {
3675 DIFF_OPT_SET(options, OVERRIDE_SUBMODULE_CONFIG);
46a958b3 3676 handle_ignore_submodules_arg(options, "all");
aee9c7d6
JL
3677 } else if (!prefixcmp(arg, "--ignore-submodules=")) {
3678 DIFF_OPT_SET(options, OVERRIDE_SUBMODULE_CONFIG);
46a958b3 3679 handle_ignore_submodules_arg(options, arg + 20);
aee9c7d6 3680 } else if (!strcmp(arg, "--submodule"))
752c0c24 3681 DIFF_OPT_SET(options, SUBMODULE_LOG);
c47ef57c
RR
3682 else if (!prefixcmp(arg, "--submodule="))
3683 return parse_submodule_opt(options, arg + 12);
d054680c
PH
3684
3685 /* misc options */
3686 else if (!strcmp(arg, "-z"))
3687 options->line_termination = 0;
dea007fb
MM
3688 else if ((argcount = short_opt('l', av, &optarg))) {
3689 options->rename_limit = strtoul(optarg, NULL, 10);
3690 return argcount;
3691 }
3692 else if ((argcount = short_opt('S', av, &optarg))) {
3693 options->pickaxe = optarg;
f506b8e8
JH
3694 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
3695 return argcount;
3696 } else if ((argcount = short_opt('G', av, &optarg))) {
3697 options->pickaxe = optarg;
3698 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
dea007fb
MM
3699 return argcount;
3700 }
d054680c 3701 else if (!strcmp(arg, "--pickaxe-all"))
f506b8e8 3702 options->pickaxe_opts |= DIFF_PICKAXE_ALL;
d054680c 3703 else if (!strcmp(arg, "--pickaxe-regex"))
f506b8e8 3704 options->pickaxe_opts |= DIFF_PICKAXE_REGEX;
dea007fb
MM
3705 else if ((argcount = short_opt('O', av, &optarg))) {
3706 options->orderfile = optarg;
3707 return argcount;
3708 }
3709 else if ((argcount = parse_long_opt("diff-filter", av, &optarg))) {
3710 options->filter = optarg;
3711 return argcount;
3712 }
d054680c
PH
3713 else if (!strcmp(arg, "--abbrev"))
3714 options->abbrev = DEFAULT_ABBREV;
3715 else if (!prefixcmp(arg, "--abbrev=")) {
3716 options->abbrev = strtoul(arg + 9, NULL, 10);
3717 if (options->abbrev < MINIMUM_ABBREV)
3718 options->abbrev = MINIMUM_ABBREV;
3719 else if (40 < options->abbrev)
3720 options->abbrev = 40;
3721 }
dea007fb
MM
3722 else if ((argcount = parse_long_opt("src-prefix", av, &optarg))) {
3723 options->a_prefix = optarg;
3724 return argcount;
3725 }
3726 else if ((argcount = parse_long_opt("dst-prefix", av, &optarg))) {
3727 options->b_prefix = optarg;
3728 return argcount;
3729 }
eab9a40b
JS
3730 else if (!strcmp(arg, "--no-prefix"))
3731 options->a_prefix = options->b_prefix = "";
6d0e674a
RS
3732 else if (opt_arg(arg, '\0', "inter-hunk-context",
3733 &options->interhunkcontext))
3734 ;
14937c2c
RS
3735 else if (!strcmp(arg, "-W"))
3736 DIFF_OPT_SET(options, FUNCCONTEXT);
3737 else if (!strcmp(arg, "--function-context"))
3738 DIFF_OPT_SET(options, FUNCCONTEXT);
3739 else if (!strcmp(arg, "--no-function-context"))
3740 DIFF_OPT_CLR(options, FUNCCONTEXT);
dea007fb
MM
3741 else if ((argcount = parse_long_opt("output", av, &optarg))) {
3742 options->file = fopen(optarg, "w");
8324b977 3743 if (!options->file)
9ec26eb7 3744 die_errno("Could not open '%s'", optarg);
c0c77734 3745 options->close_file = 1;
dea007fb 3746 return argcount;
c0c77734 3747 } else
6973dcae
JH
3748 return 0;
3749 return 1;
3750}
3751
10ae7526 3752int parse_rename_score(const char **cp_p)
6973dcae
JH
3753{
3754 unsigned long num, scale;
3755 int ch, dot;
3756 const char *cp = *cp_p;
3757
3758 num = 0;
3759 scale = 1;
3760 dot = 0;
eeefa7c9 3761 for (;;) {
6973dcae
JH
3762 ch = *cp;
3763 if ( !dot && ch == '.' ) {
3764 scale = 1;
3765 dot = 1;
3766 } else if ( ch == '%' ) {
3767 scale = dot ? scale*100 : 100;
3768 cp++; /* % is always at the end */
3769 break;
3770 } else if ( ch >= '0' && ch <= '9' ) {
3771 if ( scale < 100000 ) {
3772 scale *= 10;
3773 num = (num*10) + (ch-'0');
3774 }
3775 } else {
3776 break;
3777 }
3778 cp++;
3779 }
3780 *cp_p = cp;
3781
3782 /* user says num divided by scale and we say internally that
3783 * is MAX_SCORE * num / scale.
3784 */
dc49cd76 3785 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
6973dcae
JH
3786}
3787
16befb8b 3788static int diff_scoreopt_parse(const char *opt)
6973dcae
JH
3789{
3790 int opt1, opt2, cmd;
3791
3792 if (*opt++ != '-')
3793 return -1;
3794 cmd = *opt++;
37ab5156
KB
3795 if (cmd == '-') {
3796 /* convert the long-form arguments into short-form versions */
3797 if (!prefixcmp(opt, "break-rewrites")) {
3798 opt += strlen("break-rewrites");
3799 if (*opt == 0 || *opt++ == '=')
3800 cmd = 'B';
f611ddc7
YD
3801 } else if (!prefixcmp(opt, "find-copies")) {
3802 opt += strlen("find-copies");
37ab5156
KB
3803 if (*opt == 0 || *opt++ == '=')
3804 cmd = 'C';
f611ddc7
YD
3805 } else if (!prefixcmp(opt, "find-renames")) {
3806 opt += strlen("find-renames");
37ab5156
KB
3807 if (*opt == 0 || *opt++ == '=')
3808 cmd = 'M';
3809 }
3810 }
6973dcae
JH
3811 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
3812 return -1; /* that is not a -M, -C nor -B option */
3813
10ae7526 3814 opt1 = parse_rename_score(&opt);
6973dcae
JH
3815 if (cmd != 'B')
3816 opt2 = 0;
3817 else {
3818 if (*opt == 0)
3819 opt2 = 0;
3820 else if (*opt != '/')
3821 return -1; /* we expect -B80/99 or -B80 */
3822 else {
3823 opt++;
10ae7526 3824 opt2 = parse_rename_score(&opt);
6973dcae
JH
3825 }
3826 }
3827 if (*opt != 0)
3828 return -1;
3829 return opt1 | (opt2 << 16);
3830}
3831
3832struct diff_queue_struct diff_queued_diff;
3833
3834void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
3835{
3836 if (queue->alloc <= queue->nr) {
3837 queue->alloc = alloc_nr(queue->alloc);
3838 queue->queue = xrealloc(queue->queue,
3839 sizeof(dp) * queue->alloc);
3840 }
3841 queue->queue[queue->nr++] = dp;
3842}
3843
3844struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
3845 struct diff_filespec *one,
3846 struct diff_filespec *two)
3847{
ef677686 3848 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
6973dcae
JH
3849 dp->one = one;
3850 dp->two = two;
6973dcae
JH
3851 if (queue)
3852 diff_q(queue, dp);
3853 return dp;
3854}
3855
3856void diff_free_filepair(struct diff_filepair *p)
3857{
9fb88419
LT
3858 free_filespec(p->one);
3859 free_filespec(p->two);
6973dcae
JH
3860 free(p);
3861}
3862
3863/* This is different from find_unique_abbrev() in that
3864 * it stuffs the result with dots for alignment.
3865 */
3866const char *diff_unique_abbrev(const unsigned char *sha1, int len)
3867{
3868 int abblen;
3869 const char *abbrev;
3870 if (len == 40)
3871 return sha1_to_hex(sha1);
3872
3873 abbrev = find_unique_abbrev(sha1, len);
6973dcae
JH
3874 abblen = strlen(abbrev);
3875 if (abblen < 37) {
3876 static char hex[41];
3877 if (len < abblen && abblen <= len + 2)
3878 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
3879 else
3880 sprintf(hex, "%s...", abbrev);
3881 return hex;
3882 }
3883 return sha1_to_hex(sha1);
3884}
3885
663af342 3886static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
6973dcae 3887{
663af342
PH
3888 int line_termination = opt->line_termination;
3889 int inter_name_termination = line_termination ? '\t' : '\0';
7be57610
BY
3890 if (opt->output_prefix) {
3891 struct strbuf *msg = NULL;
3892 msg = opt->output_prefix(opt, opt->output_prefix_data);
3893 fprintf(opt->file, "%s", msg->buf);
3894 }
6973dcae 3895
663af342 3896 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
c0c77734
DB
3897 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
3898 diff_unique_abbrev(p->one->sha1, opt->abbrev));
3899 fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
6973dcae 3900 }
663af342 3901 if (p->score) {
c0c77734
DB
3902 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
3903 inter_name_termination);
663af342 3904 } else {
c0c77734 3905 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
6973dcae 3906 }
6973dcae 3907
cd676a51
JH
3908 if (p->status == DIFF_STATUS_COPIED ||
3909 p->status == DIFF_STATUS_RENAMED) {
3910 const char *name_a, *name_b;
3911 name_a = p->one->path;
3912 name_b = p->two->path;
3913 strip_prefix(opt->prefix_length, &name_a, &name_b);
c0c77734
DB
3914 write_name_quoted(name_a, opt->file, inter_name_termination);
3915 write_name_quoted(name_b, opt->file, line_termination);
663af342 3916 } else {
cd676a51
JH
3917 const char *name_a, *name_b;
3918 name_a = p->one->mode ? p->one->path : p->two->path;
3919 name_b = NULL;
3920 strip_prefix(opt->prefix_length, &name_a, &name_b);
c0c77734 3921 write_name_quoted(name_a, opt->file, line_termination);
663af342 3922 }
6973dcae
JH
3923}
3924
3925int diff_unmodified_pair(struct diff_filepair *p)
3926{
3927 /* This function is written stricter than necessary to support
3928 * the currently implemented transformers, but the idea is to
3929 * let transformers to produce diff_filepairs any way they want,
3930 * and filter and clean them up here before producing the output.
3931 */
663af342 3932 struct diff_filespec *one = p->one, *two = p->two;
6973dcae
JH
3933
3934 if (DIFF_PAIR_UNMERGED(p))
3935 return 0; /* unmerged is interesting */
3936
6973dcae
JH
3937 /* deletion, addition, mode or type change
3938 * and rename are all interesting.
3939 */
3940 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
3941 DIFF_PAIR_MODE_CHANGED(p) ||
3942 strcmp(one->path, two->path))
3943 return 0;
3944
3945 /* both are valid and point at the same path. that is, we are
3946 * dealing with a change.
3947 */
3948 if (one->sha1_valid && two->sha1_valid &&
85adbf2f
JL
3949 !hashcmp(one->sha1, two->sha1) &&
3950 !one->dirty_submodule && !two->dirty_submodule)
6973dcae
JH
3951 return 1; /* no change */
3952 if (!one->sha1_valid && !two->sha1_valid)
3953 return 1; /* both look at the same file on the filesystem. */
3954 return 0;
3955}
3956
3957static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
3958{
3959 if (diff_unmodified_pair(p))
3960 return;
3961
3962 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3963 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3964 return; /* no tree diffs in patch format */
3965
3966 run_diff(p, o);
3967}
3968
3969static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
3970 struct diffstat_t *diffstat)
3971{
3972 if (diff_unmodified_pair(p))
3973 return;
3974
3975 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3976 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
c3fced64 3977 return; /* no useful stat for tree diffs */
6973dcae
JH
3978
3979 run_diffstat(p, o, diffstat);
3980}
3981
88246898
JS
3982static void diff_flush_checkdiff(struct diff_filepair *p,
3983 struct diff_options *o)
3984{
3985 if (diff_unmodified_pair(p))
3986 return;
3987
3988 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3989 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
c3fced64 3990 return; /* nothing to check in tree diffs */
88246898
JS
3991
3992 run_checkdiff(p, o);
3993}
3994
6973dcae
JH
3995int diff_queue_is_empty(void)
3996{
3997 struct diff_queue_struct *q = &diff_queued_diff;
3998 int i;
3999 for (i = 0; i < q->nr; i++)
4000 if (!diff_unmodified_pair(q->queue[i]))
4001 return 0;
4002 return 1;
4003}
4004
4005#if DIFF_DEBUG
4006void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
4007{
4008 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
4009 x, one ? one : "",
4010 s->path,
4011 DIFF_FILE_VALID(s) ? "valid" : "invalid",
4012 s->mode,
4013 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
4014 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
4015 x, one ? one : "",
4016 s->size, s->xfrm_flags);
4017}
4018
4019void diff_debug_filepair(const struct diff_filepair *p, int i)
4020{
4021 diff_debug_filespec(p->one, i, "one");
4022 diff_debug_filespec(p->two, i, "two");
64479711 4023 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
6973dcae 4024 p->score, p->status ? p->status : '?',
64479711 4025 p->one->rename_used, p->broken_pair);
6973dcae
JH
4026}
4027
4028void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
4029{
4030 int i;
4031 if (msg)
4032 fprintf(stderr, "%s\n", msg);
4033 fprintf(stderr, "q->nr = %d\n", q->nr);
4034 for (i = 0; i < q->nr; i++) {
4035 struct diff_filepair *p = q->queue[i];
4036 diff_debug_filepair(p, i);
4037 }
4038}
4039#endif
4040
4041static void diff_resolve_rename_copy(void)
4042{
64479711
LT
4043 int i;
4044 struct diff_filepair *p;
6973dcae
JH
4045 struct diff_queue_struct *q = &diff_queued_diff;
4046
4047 diff_debug_queue("resolve-rename-copy", q);
4048
4049 for (i = 0; i < q->nr; i++) {
4050 p = q->queue[i];
4051 p->status = 0; /* undecided */
4052 if (DIFF_PAIR_UNMERGED(p))
4053 p->status = DIFF_STATUS_UNMERGED;
4054 else if (!DIFF_FILE_VALID(p->one))
4055 p->status = DIFF_STATUS_ADDED;
4056 else if (!DIFF_FILE_VALID(p->two))
4057 p->status = DIFF_STATUS_DELETED;
4058 else if (DIFF_PAIR_TYPE_CHANGED(p))
4059 p->status = DIFF_STATUS_TYPE_CHANGED;
4060
4061 /* from this point on, we are dealing with a pair
4062 * whose both sides are valid and of the same type, i.e.
4063 * either in-place edit or rename/copy edit.
4064 */
4065 else if (DIFF_PAIR_RENAME(p)) {
64479711
LT
4066 /*
4067 * A rename might have re-connected a broken
4068 * pair up, causing the pathnames to be the
4069 * same again. If so, that's not a rename at
4070 * all, just a modification..
4071 *
4072 * Otherwise, see if this source was used for
4073 * multiple renames, in which case we decrement
4074 * the count, and call it a copy.
6973dcae 4075 */
64479711
LT
4076 if (!strcmp(p->one->path, p->two->path))
4077 p->status = DIFF_STATUS_MODIFIED;
4078 else if (--p->one->rename_used > 0)
6973dcae 4079 p->status = DIFF_STATUS_COPIED;
64479711 4080 else
6973dcae
JH
4081 p->status = DIFF_STATUS_RENAMED;
4082 }
a89fccd2 4083 else if (hashcmp(p->one->sha1, p->two->sha1) ||
d516c2d1 4084 p->one->mode != p->two->mode ||
85adbf2f
JL
4085 p->one->dirty_submodule ||
4086 p->two->dirty_submodule ||
d516c2d1 4087 is_null_sha1(p->one->sha1))
6973dcae
JH
4088 p->status = DIFF_STATUS_MODIFIED;
4089 else {
4090 /* This is a "no-change" entry and should not
4091 * happen anymore, but prepare for broken callers.
4092 */
4093 error("feeding unmodified %s to diffcore",
4094 p->one->path);
4095 p->status = DIFF_STATUS_UNKNOWN;
4096 }
4097 }
4098 diff_debug_queue("resolve-rename-copy done", q);
4099}
4100
c6744349 4101static int check_pair_status(struct diff_filepair *p)
6973dcae 4102{
6973dcae
JH
4103 switch (p->status) {
4104 case DIFF_STATUS_UNKNOWN:
c6744349 4105 return 0;
6973dcae
JH
4106 case 0:
4107 die("internal error in diff-resolve-rename-copy");
6973dcae 4108 default:
c6744349 4109 return 1;
6973dcae
JH
4110 }
4111}
4112
c6744349
TH
4113static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
4114{
4115 int fmt = opt->output_format;
4116
4117 if (fmt & DIFF_FORMAT_CHECKDIFF)
4118 diff_flush_checkdiff(p, opt);
4119 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
4120 diff_flush_raw(p, opt);
cd676a51
JH
4121 else if (fmt & DIFF_FORMAT_NAME) {
4122 const char *name_a, *name_b;
4123 name_a = p->two->path;
4124 name_b = NULL;
4125 strip_prefix(opt->prefix_length, &name_a, &name_b);
c0c77734 4126 write_name_quoted(name_a, opt->file, opt->line_termination);
cd676a51 4127 }
c6744349
TH
4128}
4129
c0c77734 4130static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
4bbd261b
SE
4131{
4132 if (fs->mode)
c0c77734 4133 fprintf(file, " %s mode %06o ", newdelete, fs->mode);
4bbd261b 4134 else
c0c77734
DB
4135 fprintf(file, " %s ", newdelete);
4136 write_name_quoted(fs->path, file, '\n');
4bbd261b
SE
4137}
4138
4139
7be57610
BY
4140static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name,
4141 const char *line_prefix)
4bbd261b
SE
4142{
4143 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
7be57610
BY
4144 fprintf(file, "%s mode change %06o => %06o%c", line_prefix, p->one->mode,
4145 p->two->mode, show_name ? ' ' : '\n');
0d26a64e 4146 if (show_name) {
c0c77734 4147 write_name_quoted(p->two->path, file, '\n');
0d26a64e 4148 }
4bbd261b
SE
4149 }
4150}
4151
7be57610
BY
4152static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p,
4153 const char *line_prefix)
4bbd261b 4154{
b9f44164 4155 char *names = pprint_rename(p->one->path, p->two->path);
4bbd261b 4156
c0c77734 4157 fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
b9f44164 4158 free(names);
7be57610 4159 show_mode_change(file, p, 0, line_prefix);
4bbd261b
SE
4160}
4161
7be57610 4162static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
4bbd261b 4163{
7be57610
BY
4164 FILE *file = opt->file;
4165 char *line_prefix = "";
4166
4167 if (opt->output_prefix) {
4168 struct strbuf *buf = opt->output_prefix(opt, opt->output_prefix_data);
4169 line_prefix = buf->buf;
4170 }
4171
4bbd261b
SE
4172 switch(p->status) {
4173 case DIFF_STATUS_DELETED:
7be57610 4174 fputs(line_prefix, file);
c0c77734 4175 show_file_mode_name(file, "delete", p->one);
4bbd261b
SE
4176 break;
4177 case DIFF_STATUS_ADDED:
7be57610 4178 fputs(line_prefix, file);
c0c77734 4179 show_file_mode_name(file, "create", p->two);
4bbd261b
SE
4180 break;
4181 case DIFF_STATUS_COPIED:
7be57610
BY
4182 fputs(line_prefix, file);
4183 show_rename_copy(file, "copy", p, line_prefix);
4bbd261b
SE
4184 break;
4185 case DIFF_STATUS_RENAMED:
7be57610
BY
4186 fputs(line_prefix, file);
4187 show_rename_copy(file, "rename", p, line_prefix);
4bbd261b
SE
4188 break;
4189 default:
4190 if (p->score) {
7be57610 4191 fprintf(file, "%s rewrite ", line_prefix);
c0c77734
DB
4192 write_name_quoted(p->two->path, file, ' ');
4193 fprintf(file, "(%d%%)\n", similarity_index(p));
663af342 4194 }
7be57610 4195 show_mode_change(file, p, !p->score, line_prefix);
4bbd261b
SE
4196 break;
4197 }
4198}
4199
fcb3d0ad 4200struct patch_id_t {
9126f009 4201 git_SHA_CTX *ctx;
fcb3d0ad
JS
4202 int patchlen;
4203};
4204
4205static int remove_space(char *line, int len)
4206{
4207 int i;
663af342
PH
4208 char *dst = line;
4209 unsigned char c;
fcb3d0ad 4210
663af342
PH
4211 for (i = 0; i < len; i++)
4212 if (!isspace((c = line[i])))
4213 *dst++ = c;
fcb3d0ad 4214
663af342 4215 return dst - line;
fcb3d0ad
JS
4216}
4217
4218static void patch_id_consume(void *priv, char *line, unsigned long len)
4219{
4220 struct patch_id_t *data = priv;
4221 int new_len;
4222
4223 /* Ignore line numbers when computing the SHA1 of the patch */
cc44c765 4224 if (!prefixcmp(line, "@@ -"))
fcb3d0ad
JS
4225 return;
4226
4227 new_len = remove_space(line, len);
4228
9126f009 4229 git_SHA1_Update(data->ctx, line, new_len);
fcb3d0ad
JS
4230 data->patchlen += new_len;
4231}
4232
4233/* returns 0 upon success, and writes result into sha1 */
4234static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
4235{
4236 struct diff_queue_struct *q = &diff_queued_diff;
4237 int i;
9126f009 4238 git_SHA_CTX ctx;
fcb3d0ad
JS
4239 struct patch_id_t data;
4240 char buffer[PATH_MAX * 4 + 20];
4241
9126f009 4242 git_SHA1_Init(&ctx);
fcb3d0ad
JS
4243 memset(&data, 0, sizeof(struct patch_id_t));
4244 data.ctx = &ctx;
fcb3d0ad
JS
4245
4246 for (i = 0; i < q->nr; i++) {
4247 xpparam_t xpp;
4248 xdemitconf_t xecfg;
fcb3d0ad
JS
4249 mmfile_t mf1, mf2;
4250 struct diff_filepair *p = q->queue[i];
4251 int len1, len2;
4252
9ccd0a88 4253 memset(&xpp, 0, sizeof(xpp));
30b25010 4254 memset(&xecfg, 0, sizeof(xecfg));
fcb3d0ad
JS
4255 if (p->status == 0)
4256 return error("internal diff status error");
4257 if (p->status == DIFF_STATUS_UNKNOWN)
4258 continue;
4259 if (diff_unmodified_pair(p))
4260 continue;
4261 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4262 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4263 continue;
4264 if (DIFF_PAIR_UNMERGED(p))
4265 continue;
4266
4267 diff_fill_sha1_info(p->one);
4268 diff_fill_sha1_info(p->two);
4269 if (fill_mmfile(&mf1, p->one) < 0 ||
4270 fill_mmfile(&mf2, p->two) < 0)
4271 return error("unable to read files to diff");
4272
fcb3d0ad
JS
4273 len1 = remove_space(p->one->path, strlen(p->one->path));
4274 len2 = remove_space(p->two->path, strlen(p->two->path));
4275 if (p->one->mode == 0)
4276 len1 = snprintf(buffer, sizeof(buffer),
4277 "diff--gita/%.*sb/%.*s"
4278 "newfilemode%06o"
4279 "---/dev/null"
4280 "+++b/%.*s",
4281 len1, p->one->path,
4282 len2, p->two->path,
4283 p->two->mode,
4284 len2, p->two->path);
4285 else if (p->two->mode == 0)
4286 len1 = snprintf(buffer, sizeof(buffer),
4287 "diff--gita/%.*sb/%.*s"
4288 "deletedfilemode%06o"
4289 "---a/%.*s"
4290 "+++/dev/null",
4291 len1, p->one->path,
4292 len2, p->two->path,
4293 p->one->mode,
4294 len1, p->one->path);
4295 else
4296 len1 = snprintf(buffer, sizeof(buffer),
4297 "diff--gita/%.*sb/%.*s"
4298 "---a/%.*s"
4299 "+++b/%.*s",
4300 len1, p->one->path,
4301 len2, p->two->path,
4302 len1, p->one->path,
4303 len2, p->two->path);
9126f009 4304 git_SHA1_Update(&ctx, buffer, len1);
fcb3d0ad 4305
34597c1f
CB
4306 if (diff_filespec_is_binary(p->one) ||
4307 diff_filespec_is_binary(p->two)) {
4308 git_SHA1_Update(&ctx, sha1_to_hex(p->one->sha1), 40);
4309 git_SHA1_Update(&ctx, sha1_to_hex(p->two->sha1), 40);
4310 continue;
4311 }
4312
582aa00b 4313 xpp.flags = 0;
fcb3d0ad 4314 xecfg.ctxlen = 3;
ad14b450 4315 xecfg.flags = 0;
8a3f524b 4316 xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
dfea7900 4317 &xpp, &xecfg);
fcb3d0ad
JS
4318 }
4319
9126f009 4320 git_SHA1_Final(sha1, &ctx);
fcb3d0ad
JS
4321 return 0;
4322}
4323
4324int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
4325{
4326 struct diff_queue_struct *q = &diff_queued_diff;
4327 int i;
4328 int result = diff_get_patch_id(options, sha1);
4329
4330 for (i = 0; i < q->nr; i++)
4331 diff_free_filepair(q->queue[i]);
4332
4333 free(q->queue);
9ca5df90 4334 DIFF_QUEUE_CLEAR(q);
fcb3d0ad
JS
4335
4336 return result;
4337}
4338
946c3784 4339static int is_summary_empty(const struct diff_queue_struct *q)
6973dcae 4340{
6973dcae 4341 int i;
6973dcae 4342
946c3784
TH
4343 for (i = 0; i < q->nr; i++) {
4344 const struct diff_filepair *p = q->queue[i];
4345
4346 switch (p->status) {
4347 case DIFF_STATUS_DELETED:
4348 case DIFF_STATUS_ADDED:
4349 case DIFF_STATUS_COPIED:
4350 case DIFF_STATUS_RENAMED:
4351 return 0;
4352 default:
4353 if (p->score)
4354 return 0;
4355 if (p->one->mode && p->two->mode &&
4356 p->one->mode != p->two->mode)
4357 return 0;
4358 break;
4359 }
6973dcae 4360 }
946c3784
TH
4361 return 1;
4362}
4363
f31027c9
JH
4364static const char rename_limit_warning[] =
4365"inexact rename detection was skipped due to too many files.";
4366
4367static const char degrade_cc_to_c_warning[] =
4368"only found copies from modified paths due to too many files.";
4369
4370static const char rename_limit_advice[] =
4371"you may want to set your %s variable to at least "
4372"%d and retry the command.";
4373
4374void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
4375{
4376 if (degraded_cc)
4377 warning(degrade_cc_to_c_warning);
4378 else if (needed)
4379 warning(rename_limit_warning);
4380 else
4381 return;
4382 if (0 < needed && needed < 32767)
4383 warning(rename_limit_advice, varname, needed);
4384}
4385
6973dcae
JH
4386void diff_flush(struct diff_options *options)
4387{
4388 struct diff_queue_struct *q = &diff_queued_diff;
c6744349 4389 int i, output_format = options->output_format;
946c3784 4390 int separator = 0;
1c57a627 4391 int dirstat_by_line = 0;
6973dcae 4392
c6744349
TH
4393 /*
4394 * Order: raw, stat, summary, patch
4395 * or: name/name-status/checkdiff (other bits clear)
4396 */
946c3784
TH
4397 if (!q->nr)
4398 goto free_queue;
6973dcae 4399
c6744349
TH
4400 if (output_format & (DIFF_FORMAT_RAW |
4401 DIFF_FORMAT_NAME |
4402 DIFF_FORMAT_NAME_STATUS |
4403 DIFF_FORMAT_CHECKDIFF)) {
6973dcae
JH
4404 for (i = 0; i < q->nr; i++) {
4405 struct diff_filepair *p = q->queue[i];
c6744349
TH
4406 if (check_pair_status(p))
4407 flush_one_pair(p, options);
6973dcae 4408 }
946c3784 4409 separator++;
6973dcae 4410 }
c6744349 4411
1c57a627
JH
4412 if (output_format & DIFF_FORMAT_DIRSTAT && DIFF_OPT_TST(options, DIRSTAT_BY_LINE))
4413 dirstat_by_line = 1;
4414
4415 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
4416 dirstat_by_line) {
5e2b0636 4417 struct diffstat_t diffstat;
c6744349 4418
5e2b0636 4419 memset(&diffstat, 0, sizeof(struct diffstat_t));
6973dcae
JH
4420 for (i = 0; i < q->nr; i++) {
4421 struct diff_filepair *p = q->queue[i];
c6744349 4422 if (check_pair_status(p))
5e2b0636 4423 diff_flush_stat(p, options, &diffstat);
6973dcae 4424 }
74e2abe5
JH
4425 if (output_format & DIFF_FORMAT_NUMSTAT)
4426 show_numstat(&diffstat, options);
4427 if (output_format & DIFF_FORMAT_DIFFSTAT)
4428 show_stats(&diffstat, options);
f604652e 4429 if (output_format & DIFF_FORMAT_SHORTSTAT)
c0c77734 4430 show_shortstats(&diffstat, options);
1c57a627
JH
4431 if (output_format & DIFF_FORMAT_DIRSTAT)
4432 show_dirstat_by_line(&diffstat, options);
f604652e 4433 free_diffstat_info(&diffstat);
3969cf7d 4434 separator++;
6973dcae 4435 }
1c57a627 4436 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
c04a7155 4437 show_dirstat(options);
6973dcae 4438
946c3784 4439 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
7be57610
BY
4440 for (i = 0; i < q->nr; i++) {
4441 diff_summary(options, q->queue[i]);
4442 }
3969cf7d 4443 separator++;
6973dcae
JH
4444 }
4445
6977c250
LA
4446 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
4447 DIFF_OPT_TST(options, EXIT_WITH_STATUS) &&
4448 DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
4449 /*
4450 * run diff_flush_patch for the exit status. setting
4451 * options->file to /dev/null should be safe, becaue we
4452 * aren't supposed to produce any output anyway.
4453 */
4454 if (options->close_file)
4455 fclose(options->file);
4456 options->file = fopen("/dev/null", "w");
4457 if (!options->file)
4458 die_errno("Could not open /dev/null");
4459 options->close_file = 1;
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 if (options->found_changes)
4465 break;
4466 }
4467 }
4468
c6744349 4469 if (output_format & DIFF_FORMAT_PATCH) {
946c3784 4470 if (separator) {
b18e97ce
LP
4471 if (options->output_prefix) {
4472 struct strbuf *msg = NULL;
4473 msg = options->output_prefix(options,
4474 options->output_prefix_data);
4475 fwrite(msg->buf, msg->len, 1, stdout);
4476 }
6b2fbaaf 4477 putc(options->line_termination, options->file);
946c3784
TH
4478 if (options->stat_sep) {
4479 /* attach patch instead of inline */
c0c77734 4480 fputs(options->stat_sep, options->file);
946c3784 4481 }
c6744349
TH
4482 }
4483
4484 for (i = 0; i < q->nr; i++) {
4485 struct diff_filepair *p = q->queue[i];
4486 if (check_pair_status(p))
4487 diff_flush_patch(p, options);
4488 }
4bbd261b
SE
4489 }
4490
04245581
JK
4491 if (output_format & DIFF_FORMAT_CALLBACK)
4492 options->format_callback(q, options, options->format_callback_data);
4493
c6744349
TH
4494 for (i = 0; i < q->nr; i++)
4495 diff_free_filepair(q->queue[i]);
946c3784 4496free_queue:
6973dcae 4497 free(q->queue);
9ca5df90 4498 DIFF_QUEUE_CLEAR(q);
c0c77734
DB
4499 if (options->close_file)
4500 fclose(options->file);
f245194f
JH
4501
4502 /*
97bf2a08 4503 * Report the content-level differences with HAS_CHANGES;
f245194f
JH
4504 * diff_addremove/diff_change does not set the bit when
4505 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
4506 */
4507 if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
4508 if (options->found_changes)
4509 DIFF_OPT_SET(options, HAS_CHANGES);
4510 else
4511 DIFF_OPT_CLR(options, HAS_CHANGES);
4512 }
6973dcae
JH
4513}
4514
4515static void diffcore_apply_filter(const char *filter)
4516{
4517 int i;
4518 struct diff_queue_struct *q = &diff_queued_diff;
4519 struct diff_queue_struct outq;
9ca5df90 4520 DIFF_QUEUE_CLEAR(&outq);
6973dcae
JH
4521
4522 if (!filter)
4523 return;
4524
4525 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
4526 int found;
4527 for (i = found = 0; !found && i < q->nr; i++) {
4528 struct diff_filepair *p = q->queue[i];
4529 if (((p->status == DIFF_STATUS_MODIFIED) &&
4530 ((p->score &&
4531 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
4532 (!p->score &&
4533 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
4534 ((p->status != DIFF_STATUS_MODIFIED) &&
4535 strchr(filter, p->status)))
4536 found++;
4537 }
4538 if (found)
4539 return;
4540
4541 /* otherwise we will clear the whole queue
4542 * by copying the empty outq at the end of this
4543 * function, but first clear the current entries
4544 * in the queue.
4545 */
4546 for (i = 0; i < q->nr; i++)
4547 diff_free_filepair(q->queue[i]);
4548 }
4549 else {
4550 /* Only the matching ones */
4551 for (i = 0; i < q->nr; i++) {
4552 struct diff_filepair *p = q->queue[i];
4553
4554 if (((p->status == DIFF_STATUS_MODIFIED) &&
4555 ((p->score &&
4556 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
4557 (!p->score &&
4558 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
4559 ((p->status != DIFF_STATUS_MODIFIED) &&
4560 strchr(filter, p->status)))
4561 diff_q(&outq, p);
4562 else
4563 diff_free_filepair(p);
4564 }
4565 }
4566 free(q->queue);
4567 *q = outq;
4568}
4569
5701115a
SV
4570/* Check whether two filespecs with the same mode and size are identical */
4571static int diff_filespec_is_identical(struct diff_filespec *one,
4572 struct diff_filespec *two)
4573{
2b459b48
JH
4574 if (S_ISGITLINK(one->mode))
4575 return 0;
5701115a
SV
4576 if (diff_populate_filespec(one, 0))
4577 return 0;
4578 if (diff_populate_filespec(two, 0))
4579 return 0;
4580 return !memcmp(one->data, two->data, one->size);
4581}
4582
fb13227e
JH
4583static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
4584{
4585 int i;
4586 struct diff_queue_struct *q = &diff_queued_diff;
4587 struct diff_queue_struct outq;
9ca5df90 4588 DIFF_QUEUE_CLEAR(&outq);
fb13227e
JH
4589
4590 for (i = 0; i < q->nr; i++) {
4591 struct diff_filepair *p = q->queue[i];
4592
4593 /*
9517e6b8 4594 * 1. Entries that come from stat info dirtiness
fb13227e
JH
4595 * always have both sides (iow, not create/delete),
4596 * one side of the object name is unknown, with
4597 * the same mode and size. Keep the ones that
4598 * do not match these criteria. They have real
4599 * differences.
4600 *
4601 * 2. At this point, the file is known to be modified,
4602 * with the same mode and size, and the object
4603 * name of one side is unknown. Need to inspect
4604 * the identical contents.
4605 */
4606 if (!DIFF_FILE_VALID(p->one) || /* (1) */
4607 !DIFF_FILE_VALID(p->two) ||
4608 (p->one->sha1_valid && p->two->sha1_valid) ||
4609 (p->one->mode != p->two->mode) ||
4610 diff_populate_filespec(p->one, 1) ||
4611 diff_populate_filespec(p->two, 1) ||
4612 (p->one->size != p->two->size) ||
5701115a 4613 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
fb13227e
JH
4614 diff_q(&outq, p);
4615 else {
4616 /*
4617 * The caller can subtract 1 from skip_stat_unmatch
4618 * to determine how many paths were dirty only
4619 * due to stat info mismatch.
4620 */
8f67f8ae 4621 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
6d2d9e86 4622 diffopt->skip_stat_unmatch++;
fb13227e
JH
4623 diff_free_filepair(p);
4624 }
4625 }
4626 free(q->queue);
4627 *q = outq;
4628}
4629
730f7284
JH
4630static int diffnamecmp(const void *a_, const void *b_)
4631{
4632 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
4633 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
4634 const char *name_a, *name_b;
4635
4636 name_a = a->one ? a->one->path : a->two->path;
4637 name_b = b->one ? b->one->path : b->two->path;
4638 return strcmp(name_a, name_b);
4639}
4640
4641void diffcore_fix_diff_index(struct diff_options *options)
4642{
4643 struct diff_queue_struct *q = &diff_queued_diff;
4644 qsort(q->queue, q->nr, sizeof(q->queue[0]), diffnamecmp);
4645}
4646
6973dcae
JH
4647void diffcore_std(struct diff_options *options)
4648{
9d865356 4649 if (options->skip_stat_unmatch)
fb13227e 4650 diffcore_skip_stat_unmatch(options);
44c48a90
JH
4651 if (!options->found_follow) {
4652 /* See try_to_follow_renames() in tree-diff.c */
4653 if (options->break_opt != -1)
4654 diffcore_break(options->break_opt);
4655 if (options->detect_rename)
4656 diffcore_rename(options);
4657 if (options->break_opt != -1)
4658 diffcore_merge_broken();
4659 }
6973dcae 4660 if (options->pickaxe)
382f013b 4661 diffcore_pickaxe(options);
6973dcae
JH
4662 if (options->orderfile)
4663 diffcore_order(options->orderfile);
44c48a90
JH
4664 if (!options->found_follow)
4665 /* See try_to_follow_renames() in tree-diff.c */
4666 diff_resolve_rename_copy();
6973dcae 4667 diffcore_apply_filter(options->filter);
68aacb2f 4668
f245194f 4669 if (diff_queued_diff.nr && !DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
8f67f8ae
PH
4670 DIFF_OPT_SET(options, HAS_CHANGES);
4671 else
4672 DIFF_OPT_CLR(options, HAS_CHANGES);
1da6175d 4673
44c48a90 4674 options->found_follow = 0;
6973dcae
JH
4675}
4676
da31b358
JH
4677int diff_result_code(struct diff_options *opt, int status)
4678{
4679 int result = 0;
f31027c9
JH
4680
4681 diff_warn_rename_limit("diff.renamelimit",
4682 opt->needed_rename_limit,
4683 opt->degraded_cc_to_c);
da31b358
JH
4684 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
4685 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
4686 return status;
4687 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
4688 DIFF_OPT_TST(opt, HAS_CHANGES))
4689 result |= 01;
4690 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
4691 DIFF_OPT_TST(opt, CHECK_FAILED))
4692 result |= 02;
4693 return result;
4694}
6973dcae 4695
28b9264d
JH
4696int diff_can_quit_early(struct diff_options *opt)
4697{
4698 return (DIFF_OPT_TST(opt, QUICK) &&
4699 !opt->filter &&
4700 DIFF_OPT_TST(opt, HAS_CHANGES));
4701}
4702
aee9c7d6
JL
4703/*
4704 * Shall changes to this submodule be ignored?
4705 *
4706 * Submodule changes can be configured to be ignored separately for each path,
4707 * but that configuration can be overridden from the command line.
4708 */
4709static int is_submodule_ignored(const char *path, struct diff_options *options)
4710{
4711 int ignored = 0;
4712 unsigned orig_flags = options->flags;
4713 if (!DIFF_OPT_TST(options, OVERRIDE_SUBMODULE_CONFIG))
4714 set_diffopt_flags_from_submodule_config(options, path);
4715 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES))
4716 ignored = 1;
4717 options->flags = orig_flags;
4718 return ignored;
4719}
4720
6973dcae
JH
4721void diff_addremove(struct diff_options *options,
4722 int addremove, unsigned mode,
4723 const unsigned char *sha1,
e5450100 4724 int sha1_valid,
e3d42c47 4725 const char *concatpath, unsigned dirty_submodule)
6973dcae 4726{
6973dcae
JH
4727 struct diff_filespec *one, *two;
4728
aee9c7d6 4729 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
50fd9bd8
JS
4730 return;
4731
6973dcae
JH
4732 /* This may look odd, but it is a preparation for
4733 * feeding "there are unchanged files which should
4734 * not produce diffs, but when you are doing copy
4735 * detection you would need them, so here they are"
4736 * entries to the diff-core. They will be prefixed
4737 * with something like '=' or '*' (I haven't decided
4738 * which but should not make any difference).
a6080a0a 4739 * Feeding the same new and old to diff_change()
6973dcae
JH
4740 * also has the same effect.
4741 * Before the final output happens, they are pruned after
4742 * merged into rename/copy pairs as appropriate.
4743 */
8f67f8ae 4744 if (DIFF_OPT_TST(options, REVERSE_DIFF))
6973dcae
JH
4745 addremove = (addremove == '+' ? '-' :
4746 addremove == '-' ? '+' : addremove);
4747
cd676a51
JH
4748 if (options->prefix &&
4749 strncmp(concatpath, options->prefix, options->prefix_length))
4750 return;
4751
6973dcae
JH
4752 one = alloc_filespec(concatpath);
4753 two = alloc_filespec(concatpath);
4754
4755 if (addremove != '+')
e5450100 4756 fill_filespec(one, sha1, sha1_valid, mode);
e3d42c47 4757 if (addremove != '-') {
e5450100 4758 fill_filespec(two, sha1, sha1_valid, mode);
e3d42c47
JL
4759 two->dirty_submodule = dirty_submodule;
4760 }
6973dcae
JH
4761
4762 diff_queue(&diff_queued_diff, one, two);
f245194f
JH
4763 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
4764 DIFF_OPT_SET(options, HAS_CHANGES);
6973dcae
JH
4765}
4766
4767void diff_change(struct diff_options *options,
4768 unsigned old_mode, unsigned new_mode,
4769 const unsigned char *old_sha1,
4770 const unsigned char *new_sha1,
e5450100 4771 int old_sha1_valid, int new_sha1_valid,
e3d42c47
JL
4772 const char *concatpath,
4773 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
6973dcae 4774{
6973dcae
JH
4775 struct diff_filespec *one, *two;
4776
aee9c7d6
JL
4777 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
4778 is_submodule_ignored(concatpath, options))
50fd9bd8
JS
4779 return;
4780
8f67f8ae 4781 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
6973dcae
JH
4782 unsigned tmp;
4783 const unsigned char *tmp_c;
4784 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
4785 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
e5450100
JK
4786 tmp = old_sha1_valid; old_sha1_valid = new_sha1_valid;
4787 new_sha1_valid = tmp;
e3d42c47
JL
4788 tmp = old_dirty_submodule; old_dirty_submodule = new_dirty_submodule;
4789 new_dirty_submodule = tmp;
6973dcae 4790 }
cd676a51
JH
4791
4792 if (options->prefix &&
4793 strncmp(concatpath, options->prefix, options->prefix_length))
4794 return;
4795
6973dcae
JH
4796 one = alloc_filespec(concatpath);
4797 two = alloc_filespec(concatpath);
e5450100
JK
4798 fill_filespec(one, old_sha1, old_sha1_valid, old_mode);
4799 fill_filespec(two, new_sha1, new_sha1_valid, new_mode);
e3d42c47
JL
4800 one->dirty_submodule = old_dirty_submodule;
4801 two->dirty_submodule = new_dirty_submodule;
6973dcae
JH
4802
4803 diff_queue(&diff_queued_diff, one, two);
f245194f
JH
4804 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
4805 DIFF_OPT_SET(options, HAS_CHANGES);
6973dcae
JH
4806}
4807
fa7b2908 4808struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
6973dcae 4809{
76399c01 4810 struct diff_filepair *pair;
6973dcae 4811 struct diff_filespec *one, *two;
cd676a51
JH
4812
4813 if (options->prefix &&
4814 strncmp(path, options->prefix, options->prefix_length))
76399c01 4815 return NULL;
cd676a51 4816
6973dcae
JH
4817 one = alloc_filespec(path);
4818 two = alloc_filespec(path);
76399c01
JH
4819 pair = diff_queue(&diff_queued_diff, one, two);
4820 pair->is_unmerged = 1;
4821 return pair;
6973dcae 4822}
9cb92c39
JK
4823
4824static char *run_textconv(const char *pgm, struct diff_filespec *spec,
4825 size_t *outsize)
4826{
479b0ae8 4827 struct diff_tempfile *temp;
9cb92c39
JK
4828 const char *argv[3];
4829 const char **arg = argv;
4830 struct child_process child;
4831 struct strbuf buf = STRBUF_INIT;
da1fbed3 4832 int err = 0;
9cb92c39 4833
479b0ae8 4834 temp = prepare_temp_file(spec->path, spec);
9cb92c39 4835 *arg++ = pgm;
479b0ae8 4836 *arg++ = temp->name;
9cb92c39
JK
4837 *arg = NULL;
4838
4839 memset(&child, 0, sizeof(child));
41a457e4 4840 child.use_shell = 1;
9cb92c39
JK
4841 child.argv = argv;
4842 child.out = -1;
da1fbed3 4843 if (start_command(&child)) {
479b0ae8 4844 remove_tempfile();
9cb92c39
JK
4845 return NULL;
4846 }
da1fbed3
JS
4847
4848 if (strbuf_read(&buf, child.out, 0) < 0)
4849 err = error("error reading from textconv command '%s'", pgm);
70d70999 4850 close(child.out);
da1fbed3
JS
4851
4852 if (finish_command(&child) || err) {
4853 strbuf_release(&buf);
4854 remove_tempfile();
4855 return NULL;
4856 }
479b0ae8 4857 remove_tempfile();
9cb92c39
JK
4858
4859 return strbuf_detach(&buf, outsize);
4860}
840383b2 4861
a788d7d5
AB
4862size_t fill_textconv(struct userdiff_driver *driver,
4863 struct diff_filespec *df,
4864 char **outbuf)
840383b2
JK
4865{
4866 size_t size;
4867
d9bae1a1 4868 if (!driver || !driver->textconv) {
840383b2
JK
4869 if (!DIFF_FILE_VALID(df)) {
4870 *outbuf = "";
4871 return 0;
4872 }
4873 if (diff_populate_filespec(df, 0))
4874 die("unable to read files to diff");
4875 *outbuf = df->data;
4876 return df->size;
4877 }
4878
9ec09b04 4879 if (driver->textconv_cache && df->sha1_valid) {
d9bae1a1
JK
4880 *outbuf = notes_cache_get(driver->textconv_cache, df->sha1,
4881 &size);
4882 if (*outbuf)
4883 return size;
4884 }
4885
4886 *outbuf = run_textconv(driver->textconv, df, &size);
840383b2
JK
4887 if (!*outbuf)
4888 die("unable to read files to diff");
d9bae1a1 4889
9ec09b04 4890 if (driver->textconv_cache && df->sha1_valid) {
d9bae1a1
JK
4891 /* ignore errors, as we might be in a readonly repository */
4892 notes_cache_put(driver->textconv_cache, df->sha1, *outbuf,
4893 size);
4894 /*
4895 * we could save up changes and flush them all at the end,
4896 * but we would need an extra call after all diffing is done.
4897 * Since generating a cache entry is the slow path anyway,
4898 * this extra overhead probably isn't a big deal.
4899 */
4900 notes_cache_write(driver->textconv_cache);
4901 }
4902
840383b2
JK
4903 return size;
4904}