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