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