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