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