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