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