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