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