]> git.ipfire.org Git - thirdparty/git.git/blame - diff.c
diff: drop useless return values in git-diff helpers
[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);
296c6bb2 3566 must_show_header = 1;
6973dcae
JH
3567 }
3568 else if (lbl[1][0] == '/') {
d9c552f1 3569 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
37466447
BW
3570 if (xfrm_msg)
3571 strbuf_addstr(&header, xfrm_msg);
296c6bb2 3572 must_show_header = 1;
6973dcae
JH
3573 }
3574 else {
3575 if (one->mode != two->mode) {
d9c552f1
JK
3576 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3577 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
296c6bb2 3578 must_show_header = 1;
cd112cef 3579 }
37466447
BW
3580 if (xfrm_msg)
3581 strbuf_addstr(&header, xfrm_msg);
3e97c7c6 3582
6973dcae
JH
3583 /*
3584 * we do not run diff between different kind
3585 * of objects.
3586 */
3587 if ((one->mode ^ two->mode) & S_IFMT)
3588 goto free_ab_and_return;
0c01857d 3589 if (complete_rewrite &&
b78ea5fc
NTND
3590 (textconv_one || !diff_filespec_is_binary(o->repo, one)) &&
3591 (textconv_two || !diff_filespec_is_binary(o->repo, two))) {
a29b0a13
SB
3592 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3593 header.buf, header.len, 0);
3e97c7c6 3594 strbuf_reset(&header);
3aa1f7ca 3595 emit_rewrite_diff(name_a, name_b, one, two,
b78ea5fc 3596 textconv_one, textconv_two, o);
34a5e1a2 3597 o->found_changes = 1;
6973dcae
JH
3598 goto free_ab_and_return;
3599 }
3600 }
3601
467ddc14 3602 if (o->irreversible_delete && lbl[1][0] == '/') {
a29b0a13
SB
3603 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3604 header.len, 0);
467ddc14
JH
3605 strbuf_reset(&header);
3606 goto free_ab_and_return;
0d1e0e78 3607 } else if (!o->flags.text &&
b78ea5fc
NTND
3608 ( (!textconv_one && diff_filespec_is_binary(o->repo, one)) ||
3609 (!textconv_two && diff_filespec_is_binary(o->repo, two)) )) {
4acaaa7a 3610 struct strbuf sb = STRBUF_INIT;
1aaf69e6
NTND
3611 if (!one->data && !two->data &&
3612 S_ISREG(one->mode) && S_ISREG(two->mode) &&
0d1e0e78 3613 !o->flags.binary) {
4a7e27e9 3614 if (oideq(&one->oid, &two->oid)) {
1aaf69e6 3615 if (must_show_header)
a29b0a13
SB
3616 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3617 header.buf, header.len,
3618 0);
1aaf69e6
NTND
3619 goto free_ab_and_return;
3620 }
a29b0a13
SB
3621 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3622 header.buf, header.len, 0);
4acaaa7a
SB
3623 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3624 diff_line_prefix(o), lbl[0], lbl[1]);
3625 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3626 sb.buf, sb.len, 0);
3627 strbuf_release(&sb);
1aaf69e6
NTND
3628 goto free_ab_and_return;
3629 }
b78ea5fc
NTND
3630 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3631 fill_mmfile(o->repo, &mf2, two) < 0)
b3373982 3632 die("unable to read files to diff");
0660626c
JH
3633 /* Quite common confusing case */
3634 if (mf1.size == mf2.size &&
296c6bb2
CC
3635 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3636 if (must_show_header)
a29b0a13
SB
3637 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3638 header.buf, header.len, 0);
0660626c 3639 goto free_ab_and_return;
296c6bb2 3640 }
a29b0a13 3641 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3e97c7c6 3642 strbuf_reset(&header);
0d1e0e78 3643 if (o->flags.binary)
4eed0ebd 3644 emit_binary_diff(o, &mf1, &mf2);
4acaaa7a
SB
3645 else {
3646 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3647 diff_line_prefix(o), lbl[0], lbl[1]);
3648 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3649 sb.buf, sb.len, 0);
3650 strbuf_release(&sb);
3651 }
34a5e1a2 3652 o->found_changes = 1;
467ddc14 3653 } else {
6973dcae 3654 /* Crazy xdl interfaces.. */
0da0e926 3655 const char *diffopts;
ae021d87 3656 const char *v;
6973dcae
JH
3657 xpparam_t xpp;
3658 xdemitconf_t xecfg;
6973dcae 3659 struct emit_callback ecbdata;
be58e70d 3660 const struct userdiff_funcname *pe;
f258475a 3661
b3f01ff2 3662 if (must_show_header) {
a29b0a13
SB
3663 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3664 header.buf, header.len, 0);
3e97c7c6
GB
3665 strbuf_reset(&header);
3666 }
3667
6afaf807
NTND
3668 mf1.size = fill_textconv(o->repo, textconv_one, one, &mf1.ptr);
3669 mf2.size = fill_textconv(o->repo, textconv_two, two, &mf2.ptr);
04427ac8 3670
acd00ea0 3671 pe = diff_funcname_pattern(o, one);
45e7ca0f 3672 if (!pe)
acd00ea0 3673 pe = diff_funcname_pattern(o, two);
6973dcae 3674
9ccd0a88 3675 memset(&xpp, 0, sizeof(xpp));
30b25010 3676 memset(&xecfg, 0, sizeof(xecfg));
cd112cef 3677 memset(&ecbdata, 0, sizeof(ecbdata));
1cdde296
JS
3678 if (o->flags.suppress_diff_headers)
3679 lbl[0] = NULL;
6973dcae 3680 ecbdata.label_path = lbl;
daa0c3d9 3681 ecbdata.color_diff = want_color(o->use_color);
26d024ec 3682 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
690ed843 3683 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
d68fe26f 3684 check_blank_at_eof(&mf1, &mf2, &ecbdata);
a3c158d4 3685 ecbdata.opt = o;
1cdde296
JS
3686 if (header.len && !o->flags.suppress_diff_headers)
3687 ecbdata.header = &header;
582aa00b 3688 xpp.flags = o->xdl_opts;
296d4a94
MK
3689 xpp.ignore_regex = o->ignore_regex;
3690 xpp.ignore_regex_nr = o->ignore_regex_nr;
2477ab2e
JT
3691 xpp.anchors = o->anchors;
3692 xpp.anchors_nr = o->anchors_nr;
ee1e5412 3693 xecfg.ctxlen = o->context;
6d0e674a 3694 xecfg.interhunkctxlen = o->interhunkcontext;
6973dcae 3695 xecfg.flags = XDL_EMIT_FUNCNAMES;
0d1e0e78 3696 if (o->flags.funccontext)
14937c2c 3697 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
45e7ca0f 3698 if (pe)
a013585b 3699 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
0da0e926
JK
3700
3701 diffopts = getenv("GIT_DIFF_OPTS");
6973dcae
JH
3702 if (!diffopts)
3703 ;
ae021d87
JK
3704 else if (skip_prefix(diffopts, "--unified=", &v))
3705 xecfg.ctxlen = strtoul(v, NULL, 10);
3706 else if (skip_prefix(diffopts, "-u", &v))
3707 xecfg.ctxlen = strtoul(v, NULL, 10);
0da0e926 3708
77d1a520
TR
3709 if (o->word_diff)
3710 init_diff_words_data(&ecbdata, o, one, two);
9346d6d1
JK
3711 if (xdi_diff_outf(&mf1, &mf2, NULL, fn_out_consume,
3712 &ecbdata, &xpp, &xecfg))
3efb9880 3713 die("unable to generate diff for %s", one->path);
882749a0 3714 if (o->word_diff)
f59a59e2 3715 free_diff_words_data(&ecbdata);
04427ac8
JK
3716 if (textconv_one)
3717 free(mf1.ptr);
3718 if (textconv_two)
3719 free(mf2.ptr);
8cfe5f1c 3720 xdiff_clear_find_func(&xecfg);
6973dcae
JH
3721 }
3722
3723 free_ab_and_return:
3e97c7c6 3724 strbuf_release(&header);
fc3abdf5
JH
3725 diff_free_filespec_data(one);
3726 diff_free_filespec_data(two);
6973dcae
JH
3727 free(a_one);
3728 free(b_two);
3729 return;
3730}
3731
ddf88fa6
NTND
3732static char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
3733{
3734 if (!is_renamed) {
3735 if (p->status == DIFF_STATUS_ADDED) {
3736 if (S_ISLNK(p->two->mode))
3737 return "new +l";
3738 else if ((p->two->mode & 0777) == 0755)
3739 return "new +x";
3740 else
3741 return "new";
3742 } else if (p->status == DIFF_STATUS_DELETED)
3743 return "gone";
3744 }
3745 if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
3746 return "mode -l";
3747 else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
3748 return "mode +l";
3749 else if ((p->one->mode & 0777) == 0644 &&
3750 (p->two->mode & 0777) == 0755)
3751 return "mode +x";
3752 else if ((p->one->mode & 0777) == 0755 &&
3753 (p->two->mode & 0777) == 0644)
3754 return "mode -x";
3755 return NULL;
3756}
3757
6973dcae
JH
3758static void builtin_diffstat(const char *name_a, const char *name_b,
3759 struct diff_filespec *one,
3760 struct diff_filespec *two,
710158e3 3761 struct diffstat_t *diffstat,
0d21efa5 3762 struct diff_options *o,
74faaa16 3763 struct diff_filepair *p)
6973dcae
JH
3764{
3765 mmfile_t mf1, mf2;
3766 struct diffstat_file *data;
ff0c7fa8 3767 int may_differ;
74faaa16
LT
3768 int complete_rewrite = 0;
3769
3770 if (!DIFF_PAIR_UNMERGED(p)) {
3771 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3772 complete_rewrite = 1;
3773 }
6973dcae
JH
3774
3775 data = diffstat_add(diffstat, name_a, name_b);
99bfd407 3776 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
ddf88fa6
NTND
3777 if (o->flags.stat_with_summary)
3778 data->comments = get_compact_summary(p, data->is_renamed);
6973dcae
JH
3779
3780 if (!one || !two) {
3781 data->is_unmerged = 1;
3782 return;
3783 }
ded0abc7 3784
ff0c7fa8
TGS
3785 /* saves some reads if true, not a guarantee of diff outcome */
3786 may_differ = !(one->oid_valid && two->oid_valid &&
3787 oideq(&one->oid, &two->oid));
352ca4e1 3788
b78ea5fc
NTND
3789 if (diff_filespec_is_binary(o->repo, one) ||
3790 diff_filespec_is_binary(o->repo, two)) {
ded0abc7 3791 data->is_binary = 1;
ff0c7fa8 3792 if (!may_differ) {
e18872b2
ZJS
3793 data->added = 0;
3794 data->deleted = 0;
3795 } else {
b78ea5fc
NTND
3796 data->added = diff_filespec_size(o->repo, two);
3797 data->deleted = diff_filespec_size(o->repo, one);
e18872b2 3798 }
ded0abc7
JK
3799 }
3800
3801 else if (complete_rewrite) {
1c37e86a
JT
3802 diff_populate_filespec(o->repo, one, NULL);
3803 diff_populate_filespec(o->repo, two, NULL);
710158e3
JH
3804 data->deleted = count_lines(one->data, one->size);
3805 data->added = count_lines(two->data, two->size);
710158e3 3806 }
6973dcae 3807
ff0c7fa8 3808 else if (may_differ) {
6973dcae
JH
3809 /* Crazy xdl interfaces.. */
3810 xpparam_t xpp;
3811 xdemitconf_t xecfg;
6973dcae 3812
b78ea5fc
NTND
3813 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3814 fill_mmfile(o->repo, &mf2, two) < 0)
ded0abc7
JK
3815 die("unable to read files to diff");
3816
9ccd0a88 3817 memset(&xpp, 0, sizeof(xpp));
30b25010 3818 memset(&xecfg, 0, sizeof(xecfg));
582aa00b 3819 xpp.flags = o->xdl_opts;
296d4a94
MK
3820 xpp.ignore_regex = o->ignore_regex;
3821 xpp.ignore_regex_nr = o->ignore_regex_nr;
2477ab2e
JT
3822 xpp.anchors = o->anchors;
3823 xpp.anchors_nr = o->anchors_nr;
f01cae91
JH
3824 xecfg.ctxlen = o->context;
3825 xecfg.interhunkctxlen = o->interhunkcontext;
5d934600
ÆAB
3826 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
3827 if (xdi_diff_outf(&mf1, &mf2, NULL,
3b40a090 3828 diffstat_consume, diffstat, &xpp, &xecfg))
3efb9880 3829 die("unable to generate diffstat for %s", one->path);
1cf3d5db
MR
3830
3831 if (DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two)) {
3832 struct diffstat_file *file =
3833 diffstat->files[diffstat->nr - 1];
3834 /*
3835 * Omit diffstats of modified files where nothing changed.
ff0c7fa8 3836 * Even if may_differ, this might be the case due to
1cf3d5db
MR
3837 * ignoring whitespace changes, etc.
3838 *
3839 * But note that we special-case additions, deletions,
3840 * renames, and mode changes as adding an empty file,
3841 * for example is still of interest.
3842 */
3843 if ((p->status == DIFF_STATUS_MODIFIED)
3844 && !file->added
3845 && !file->deleted
3846 && one->mode == two->mode) {
3847 free_diffstat_file(file);
3848 diffstat->nr--;
3849 }
3850 }
6973dcae 3851 }
fc3abdf5 3852
fc3abdf5
JH
3853 diff_free_filespec_data(one);
3854 diff_free_filespec_data(two);
6973dcae
JH
3855}
3856
88246898 3857static void builtin_checkdiff(const char *name_a, const char *name_b,
cd676a51 3858 const char *attr_path,
5ff10dd6
JH
3859 struct diff_filespec *one,
3860 struct diff_filespec *two,
3861 struct diff_options *o)
88246898
JS
3862{
3863 mmfile_t mf1, mf2;
3864 struct checkdiff_t data;
3865
3866 if (!two)
3867 return;
3868
3869 memset(&data, 0, sizeof(data));
88246898
JS
3870 data.filename = name_b ? name_b : name_a;
3871 data.lineno = 0;
1ba111d1 3872 data.o = o;
26d024ec 3873 data.ws_rule = whitespace_rule(o->repo->index, attr_path);
32eaa468 3874 data.conflict_marker_size = ll_merge_marker_size(o->repo->index, attr_path);
88246898 3875
b78ea5fc
NTND
3876 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3877 fill_mmfile(o->repo, &mf2, two) < 0)
88246898
JS
3878 die("unable to read files to diff");
3879
5ff10dd6
JH
3880 /*
3881 * All the other codepaths check both sides, but not checking
3882 * the "old" side here is deliberate. We are checking the newly
3883 * introduced changes, and as long as the "new" side is text, we
3884 * can and should check what it introduces.
3885 */
b78ea5fc 3886 if (diff_filespec_is_binary(o->repo, two))
fc3abdf5 3887 goto free_and_return;
88246898
JS
3888 else {
3889 /* Crazy xdl interfaces.. */
3890 xpparam_t xpp;
3891 xdemitconf_t xecfg;
88246898 3892
9ccd0a88 3893 memset(&xpp, 0, sizeof(xpp));
30b25010 3894 memset(&xecfg, 0, sizeof(xecfg));
c35539eb 3895 xecfg.ctxlen = 1; /* at least one context line */
582aa00b 3896 xpp.flags = 0;
75ab7630
JK
3897 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume_hunk,
3898 checkdiff_consume, &data,
3efb9880
JK
3899 &xpp, &xecfg))
3900 die("unable to generate checkdiff for %s", one->path);
877f23cc 3901
467babf8 3902 if (data.ws_rule & WS_BLANK_AT_EOF) {
d68fe26f
JH
3903 struct emit_callback ecbdata;
3904 int blank_at_eof;
3905
3906 ecbdata.ws_rule = data.ws_rule;
3907 check_blank_at_eof(&mf1, &mf2, &ecbdata);
8837d335 3908 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
d68fe26f 3909
467babf8
JH
3910 if (blank_at_eof) {
3911 static char *err;
3912 if (!err)
3913 err = whitespace_error_string(WS_BLANK_AT_EOF);
3914 fprintf(o->file, "%s:%d: %s.\n",
3915 data.filename, blank_at_eof, err);
3916 data.status = 1; /* report errors */
3917 }
877f23cc 3918 }
88246898 3919 }
fc3abdf5
JH
3920 free_and_return:
3921 diff_free_filespec_data(one);
3922 diff_free_filespec_data(two);
62c64895 3923 if (data.status)
0d1e0e78 3924 o->flags.check_failed = 1;
88246898
JS
3925}
3926
6973dcae
JH
3927struct diff_filespec *alloc_filespec(const char *path)
3928{
96ffc06f 3929 struct diff_filespec *spec;
6973dcae 3930
96ffc06f 3931 FLEXPTR_ALLOC_STR(spec, path, path);
9fb88419 3932 spec->count = 1;
122aa6f9 3933 spec->is_binary = -1;
6973dcae
JH
3934 return spec;
3935}
3936
9fb88419
LT
3937void free_filespec(struct diff_filespec *spec)
3938{
3939 if (!--spec->count) {
3940 diff_free_filespec_data(spec);
3941 free(spec);
3942 }
3943}
3944
f9704c2d
BW
3945void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3946 int oid_valid, unsigned short mode)
6973dcae
JH
3947{
3948 if (mode) {
3949 spec->mode = canon_mode(mode);
f9704c2d
BW
3950 oidcpy(&spec->oid, oid);
3951 spec->oid_valid = oid_valid;
6973dcae
JH
3952 }
3953}
3954
3955/*
5adf317b 3956 * Given a name and sha1 pair, if the index tells us the file in
6973dcae
JH
3957 * the work tree has that object contents, return true, so that
3958 * prepare_temp_file() does not have to inflate and extract.
3959 */
b78ea5fc
NTND
3960static int reuse_worktree_file(struct index_state *istate,
3961 const char *name,
3962 const struct object_id *oid,
3963 int want_file)
6973dcae 3964{
9c5e6c80 3965 const struct cache_entry *ce;
6973dcae
JH
3966 struct stat st;
3967 int pos, len;
3968
150115ad
JH
3969 /*
3970 * We do not read the cache ourselves here, because the
6973dcae
JH
3971 * benchmark with my previous version that always reads cache
3972 * shows that it makes things worse for diff-tree comparing
3973 * two linux-2.6 kernel trees in an already checked out work
3974 * tree. This is because most diff-tree comparisons deal with
3975 * only a small number of files, while reading the cache is
3976 * expensive for a large project, and its cost outweighs the
3977 * savings we get by not inflating the object to a temporary
3978 * file. Practically, this code only helps when we are used
3979 * by diff-cache --cached, which does read the cache before
3980 * calling us.
3981 */
b78ea5fc 3982 if (!istate->cache)
6973dcae
JH
3983 return 0;
3984
1510fea7
SP
3985 /* We want to avoid the working directory if our caller
3986 * doesn't need the data in a normal file, this system
3987 * is rather slow with its stat/open/mmap/close syscalls,
3988 * and the object is contained in a pack file. The pack
3989 * is probably already open and will be faster to obtain
3990 * the data through than the working directory. Loose
3991 * objects however would tend to be slower as they need
3992 * to be individually opened and inflated.
3993 */
14c3c80c 3994 if (!FAST_WORKING_DIRECTORY && !want_file && has_object_pack(oid))
1510fea7
SP
3995 return 0;
3996
06dec439
JK
3997 /*
3998 * Similarly, if we'd have to convert the file contents anyway, that
3999 * makes the optimization not worthwhile.
4000 */
b78ea5fc 4001 if (!want_file && would_convert_to_git(istate, name))
06dec439
JK
4002 return 0;
4003
ad90da73
DS
4004 /*
4005 * If this path does not match our sparse-checkout definition,
4006 * then the file will not be in the working directory.
4007 */
4008 if (!path_in_sparse_checkout(name, istate))
4009 return 0;
4010
6973dcae 4011 len = strlen(name);
b78ea5fc 4012 pos = index_name_pos(istate, name, len);
6973dcae
JH
4013 if (pos < 0)
4014 return 0;
b78ea5fc 4015 ce = istate->cache[pos];
eadb5831
JH
4016
4017 /*
4018 * This is not the sha1 we are looking for, or
4019 * unreusable because it is not a regular file.
4020 */
9001dc2a 4021 if (!oideq(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
6973dcae 4022 return 0;
eadb5831 4023
150115ad
JH
4024 /*
4025 * If ce is marked as "assume unchanged", there is no
4026 * guarantee that work tree matches what we are looking for.
4027 */
b4d1690d 4028 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
150115ad
JH
4029 return 0;
4030
eadb5831
JH
4031 /*
4032 * If ce matches the file in the work tree, we can reuse it.
6973dcae 4033 */
eadb5831 4034 if (ce_uptodate(ce) ||
b78ea5fc 4035 (!lstat(name, &st) && !ie_match_stat(istate, ce, &st, 0)))
eadb5831
JH
4036 return 1;
4037
4038 return 0;
6973dcae
JH
4039}
4040
04786756
LT
4041static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
4042{
b1ddfb91
JK
4043 struct strbuf buf = STRBUF_INIT;
4044 char *dirty = "";
8e08b419
JH
4045
4046 /* Are we looking at the work tree? */
85adbf2f 4047 if (s->dirty_submodule)
8e08b419
JH
4048 dirty = "-dirty";
4049
a0d12c44 4050 strbuf_addf(&buf, "Subproject commit %s%s\n",
4051 oid_to_hex(&s->oid), dirty);
b1ddfb91 4052 s->size = buf.len;
04786756
LT
4053 if (size_only) {
4054 s->data = NULL;
b1ddfb91
JK
4055 strbuf_release(&buf);
4056 } else {
4057 s->data = strbuf_detach(&buf, NULL);
4058 s->should_free = 1;
04786756
LT
4059 }
4060 return 0;
4061}
4062
6973dcae
JH
4063/*
4064 * While doing rename detection and pickaxe operation, we may need to
4065 * grab the data for the blob (or file) for our own in-core comparison.
4066 * diff_filespec has data and size fields for this purpose.
4067 */
b78ea5fc
NTND
4068int diff_populate_filespec(struct repository *r,
4069 struct diff_filespec *s,
1c37e86a 4070 const struct diff_populate_filespec_options *options)
6973dcae 4071{
1c37e86a
JT
4072 int size_only = options ? options->check_size_only : 0;
4073 int check_binary = options ? options->check_binary : 0;
6973dcae 4074 int err = 0;
8462ff43 4075 int conv_flags = global_conv_flags_eol;
5430bb28
JH
4076 /*
4077 * demote FAIL to WARN to allow inspecting the situation
4078 * instead of refusing.
4079 */
8462ff43
TB
4080 if (conv_flags & CONV_EOL_RNDTRP_DIE)
4081 conv_flags = CONV_EOL_RNDTRP_WARN;
5430bb28 4082
6973dcae
JH
4083 if (!DIFF_FILE_VALID(s))
4084 die("internal error: asking to populate invalid file.");
4085 if (S_ISDIR(s->mode))
4086 return -1;
4087
6973dcae 4088 if (s->data)
fc3abdf5 4089 return 0;
04786756 4090
6e0b8ed6
JH
4091 if (size_only && 0 < s->size)
4092 return 0;
4093
302b9282 4094 if (S_ISGITLINK(s->mode))
04786756
LT
4095 return diff_populate_gitlink(s, size_only);
4096
41c9560e 4097 if (!s->oid_valid ||
b78ea5fc 4098 reuse_worktree_file(r->index, s->path, &s->oid, 0)) {
f285a2d7 4099 struct strbuf buf = STRBUF_INIT;
6973dcae
JH
4100 struct stat st;
4101 int fd;
6c510bee 4102
6973dcae 4103 if (lstat(s->path, &st) < 0) {
10e0ca84
AO
4104 err_empty:
4105 err = -1;
4106 empty:
4107 s->data = (char *)"";
4108 s->size = 0;
4109 return err;
6973dcae 4110 }
dc49cd76 4111 s->size = xsize_t(st.st_size);
6973dcae
JH
4112 if (!s->size)
4113 goto empty;
6973dcae 4114 if (S_ISLNK(st.st_mode)) {
cf219d8c
LT
4115 struct strbuf sb = STRBUF_INIT;
4116
4117 if (strbuf_readlink(&sb, s->path, s->size))
6973dcae 4118 goto err_empty;
0956a6db
RS
4119 s->size = sb.len;
4120 s->data = strbuf_detach(&sb, NULL);
cf219d8c 4121 s->should_free = 1;
6973dcae
JH
4122 return 0;
4123 }
12426e11
JH
4124
4125 /*
4126 * Even if the caller would be happy with getting
4127 * only the size, we cannot return early at this
4128 * point if the path requires us to run the content
4129 * conversion.
4130 */
b78ea5fc 4131 if (size_only && !would_convert_to_git(r->index, s->path))
cf219d8c 4132 return 0;
12426e11
JH
4133
4134 /*
4135 * Note: this check uses xsize_t(st.st_size) that may
4136 * not be the true size of the blob after it goes
4137 * through convert_to_git(). This may not strictly be
4138 * correct, but the whole point of big_file_threshold
4139 * and is_binary check being that we want to avoid
4140 * opening the file and inspecting the contents, this
4141 * is probably fine.
4142 */
1c37e86a 4143 if (check_binary &&
6bf3b813
NTND
4144 s->size > big_file_threshold && s->is_binary == -1) {
4145 s->is_binary = 1;
4146 return 0;
4147 }
6973dcae
JH
4148 fd = open(s->path, O_RDONLY);
4149 if (fd < 0)
4150 goto err_empty;
c4712e45 4151 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
6973dcae 4152 close(fd);
6973dcae 4153 s->should_munmap = 1;
6c510bee
LT
4154
4155 /*
4156 * Convert from working tree format to canonical git format
4157 */
b78ea5fc 4158 if (convert_to_git(r->index, s->path, s->data, s->size, &buf, conv_flags)) {
c32f749f 4159 size_t size = 0;
6c510bee
LT
4160 munmap(s->data, s->size);
4161 s->should_munmap = 0;
c32f749f
RS
4162 s->data = strbuf_detach(&buf, &size);
4163 s->size = size;
6c510bee
LT
4164 s->should_free = 1;
4165 }
6973dcae
JH
4166 }
4167 else {
c14b6f83
JT
4168 struct object_info info = {
4169 .sizep = &s->size
4170 };
4171
4172 if (!(size_only || check_binary))
4173 /*
4174 * Set contentp, since there is no chance that merely
4175 * the size is sufficient.
4176 */
4177 info.contentp = &s->data;
4178
95acf11a
JT
4179 if (options && options->missing_object_cb) {
4180 if (!oid_object_info_extended(r, &s->oid, &info,
4181 OBJECT_INFO_LOOKUP_REPLACE |
4182 OBJECT_INFO_SKIP_FETCH_OBJECT))
4183 goto object_read;
4184 options->missing_object_cb(options->missing_object_data);
4185 }
c14b6f83
JT
4186 if (oid_object_info_extended(r, &s->oid, &info,
4187 OBJECT_INFO_LOOKUP_REPLACE))
4188 die("unable to read %s", oid_to_hex(&s->oid));
4189
95acf11a 4190object_read:
1c37e86a 4191 if (size_only || check_binary) {
6bf3b813
NTND
4192 if (size_only)
4193 return 0;
4194 if (s->size > big_file_threshold && s->is_binary == -1) {
4195 s->is_binary = 1;
4196 return 0;
4197 }
6973dcae 4198 }
c14b6f83
JT
4199 if (!info.contentp) {
4200 info.contentp = &s->data;
4201 if (oid_object_info_extended(r, &s->oid, &info,
4202 OBJECT_INFO_LOOKUP_REPLACE))
4203 die("unable to read %s", oid_to_hex(&s->oid));
4204 }
6bf3b813 4205 s->should_free = 1;
6973dcae
JH
4206 }
4207 return 0;
4208}
4209
8ae92e63 4210void diff_free_filespec_blob(struct diff_filespec *s)
6973dcae
JH
4211{
4212 if (s->should_free)
4213 free(s->data);
4214 else if (s->should_munmap)
4215 munmap(s->data, s->size);
fc3abdf5
JH
4216
4217 if (s->should_free || s->should_munmap) {
4218 s->should_free = s->should_munmap = 0;
4219 s->data = NULL;
4220 }
eede7b7d
JK
4221}
4222
4223void diff_free_filespec_data(struct diff_filespec *s)
4224{
24695934
JK
4225 if (!s)
4226 return;
4227
8ae92e63 4228 diff_free_filespec_blob(s);
6a83d902 4229 FREE_AND_NULL(s->cnt_data);
6973dcae
JH
4230}
4231
b78ea5fc
NTND
4232static void prep_temp_blob(struct index_state *istate,
4233 const char *path, struct diff_tempfile *temp,
6973dcae
JH
4234 void *blob,
4235 unsigned long size,
09bdff29 4236 const struct object_id *oid,
6973dcae
JH
4237 int mode)
4238{
4e218f54 4239 struct strbuf buf = STRBUF_INIT;
003b33a8
DA
4240 char *path_dup = xstrdup(path);
4241 const char *base = basename(path_dup);
c397aac0 4242 struct checkout_metadata meta;
4243
4244 init_checkout_metadata(&meta, NULL, NULL, oid);
6973dcae 4245
8af75937 4246 temp->tempfile = mks_tempfile_dt("git-blob-XXXXXX", base);
076aa2cb 4247 if (!temp->tempfile)
d824cbba 4248 die_errno("unable to create temp-file");
b78ea5fc 4249 if (convert_to_working_tree(istate, path,
c397aac0 4250 (const char *)blob, (size_t)size, &buf, &meta)) {
4e218f54
JS
4251 blob = buf.buf;
4252 size = buf.len;
4253 }
c50424a6 4254 if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
076aa2cb 4255 close_tempfile_gently(temp->tempfile))
0721c314 4256 die_errno("unable to write temp-file");
076aa2cb 4257 temp->name = get_tempfile_path(temp->tempfile);
09bdff29 4258 oid_to_hex_r(temp->hex, oid);
5096d490 4259 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
4e218f54 4260 strbuf_release(&buf);
003b33a8 4261 free(path_dup);
6973dcae
JH
4262}
4263
b78ea5fc 4264static struct diff_tempfile *prepare_temp_file(struct repository *r,
b78ea5fc 4265 struct diff_filespec *one)
6973dcae 4266{
479b0ae8
JK
4267 struct diff_tempfile *temp = claim_diff_tempfile();
4268
6973dcae
JH
4269 if (!DIFF_FILE_VALID(one)) {
4270 not_a_valid_file:
4271 /* A '-' entry produces this for file-2, and
4272 * a '+' entry produces this for file-1.
4273 */
4274 temp->name = "/dev/null";
5096d490
JK
4275 xsnprintf(temp->hex, sizeof(temp->hex), ".");
4276 xsnprintf(temp->mode, sizeof(temp->mode), ".");
479b0ae8
JK
4277 return temp;
4278 }
4279
aba47272 4280 if (!S_ISGITLINK(one->mode) &&
41c9560e 4281 (!one->oid_valid ||
f034bb1c 4282 reuse_worktree_file(r->index, one->path, &one->oid, 1))) {
6973dcae 4283 struct stat st;
f034bb1c 4284 if (lstat(one->path, &st) < 0) {
6973dcae
JH
4285 if (errno == ENOENT)
4286 goto not_a_valid_file;
f034bb1c 4287 die_errno("stat(%s)", one->path);
6973dcae
JH
4288 }
4289 if (S_ISLNK(st.st_mode)) {
3cd7388d 4290 struct strbuf sb = STRBUF_INIT;
f034bb1c
JK
4291 if (strbuf_readlink(&sb, one->path, st.st_size) < 0)
4292 die_errno("readlink(%s)", one->path);
4293 prep_temp_blob(r->index, one->path, temp, sb.buf, sb.len,
41c9560e 4294 (one->oid_valid ?
14228447 4295 &one->oid : null_oid()),
41c9560e 4296 (one->oid_valid ?
6973dcae 4297 one->mode : S_IFLNK));
3cd7388d 4298 strbuf_release(&sb);
6973dcae
JH
4299 }
4300 else {
4301 /* we can borrow from the file in the work tree */
f034bb1c 4302 temp->name = one->path;
41c9560e 4303 if (!one->oid_valid)
14228447 4304 oid_to_hex_r(temp->hex, null_oid());
6973dcae 4305 else
2490574d 4306 oid_to_hex_r(temp->hex, &one->oid);
6973dcae
JH
4307 /* Even though we may sometimes borrow the
4308 * contents from the work tree, we always want
4309 * one->mode. mode is trustworthy even when
74014152 4310 * !(one->oid_valid), as long as
6973dcae
JH
4311 * DIFF_FILE_VALID(one).
4312 */
5096d490 4313 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
6973dcae 4314 }
479b0ae8 4315 return temp;
6973dcae
JH
4316 }
4317 else {
1c37e86a 4318 if (diff_populate_filespec(r, one, NULL))
6973dcae 4319 die("cannot read data blob for %s", one->path);
f034bb1c 4320 prep_temp_blob(r->index, one->path, temp,
b78ea5fc 4321 one->data, one->size,
09bdff29 4322 &one->oid, one->mode);
6973dcae 4323 }
479b0ae8 4324 return temp;
6973dcae
JH
4325}
4326
b78ea5fc 4327static void add_external_diff_name(struct repository *r,
ef8d7ac4 4328 struct strvec *argv,
f3efe787
JK
4329 struct diff_filespec *df)
4330{
f034bb1c 4331 struct diff_tempfile *temp = prepare_temp_file(r, df);
ef8d7ac4
JK
4332 strvec_push(argv, temp->name);
4333 strvec_push(argv, temp->hex);
4334 strvec_push(argv, temp->mode);
f3efe787
JK
4335}
4336
6973dcae
JH
4337/* An external diff command takes:
4338 *
4339 * diff-cmd name infile1 infile1-sha1 infile1-mode \
4340 * infile2 infile2-sha1 infile2-mode [ rename-to ]
4341 *
4342 */
4343static void run_external_diff(const char *pgm,
4344 const char *name,
4345 const char *other,
4346 struct diff_filespec *one,
4347 struct diff_filespec *two,
4348 const char *xfrm_msg,
ee7fb0b1 4349 struct diff_options *o)
6973dcae 4350{
0e906739 4351 struct child_process cmd = CHILD_PROCESS_INIT;
ee7fb0b1 4352 struct diff_queue_struct *q = &diff_queued_diff;
6973dcae 4353
0e906739
RS
4354 strvec_push(&cmd.args, pgm);
4355 strvec_push(&cmd.args, name);
6973dcae 4356
6973dcae 4357 if (one && two) {
de8f14e1
JK
4358 add_external_diff_name(o->repo, &cmd.args, one);
4359 add_external_diff_name(o->repo, &cmd.args, two);
4360 if (other) {
0e906739
RS
4361 strvec_push(&cmd.args, other);
4362 strvec_push(&cmd.args, xfrm_msg);
6973dcae 4363 }
6973dcae 4364 }
ee7fb0b1 4365
0e906739
RS
4366 strvec_pushf(&cmd.env, "GIT_DIFF_PATH_COUNTER=%d",
4367 ++o->diff_path_counter);
4368 strvec_pushf(&cmd.env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
ee7fb0b1 4369
3aef54e8
JS
4370 diff_free_filespec_data(one);
4371 diff_free_filespec_data(two);
0e906739
RS
4372 cmd.use_shell = 1;
4373 if (run_command(&cmd))
89294d14 4374 die(_("external diff died, stopping at %s"), name);
ee7fb0b1 4375
6973dcae 4376 remove_tempfile();
6973dcae
JH
4377}
4378
b67b9612
JH
4379static int similarity_index(struct diff_filepair *p)
4380{
4381 return p->score * 100 / MAX_SCORE;
4382}
4383
4f03666a
JK
4384static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
4385{
4386 if (startup_info->have_repository)
d850b7a5 4387 return repo_find_unique_abbrev(the_repository, oid, abbrev);
4f03666a
JK
4388 else {
4389 char *hex = oid_to_hex(oid);
0d9c527d
JH
4390 if (abbrev < 0)
4391 abbrev = FALLBACK_DEFAULT_ABBREV;
02afca1e 4392 if (abbrev > the_hash_algo->hexsz)
033abf97 4393 BUG("oid abbreviation out of range: %d", abbrev);
43d1948b
JB
4394 if (abbrev)
4395 hex[abbrev] = '\0';
4f03666a
JK
4396 return hex;
4397 }
4398}
4399
b67b9612
JH
4400static void fill_metainfo(struct strbuf *msg,
4401 const char *name,
4402 const char *other,
4403 struct diff_filespec *one,
4404 struct diff_filespec *two,
4405 struct diff_options *o,
37466447 4406 struct diff_filepair *p,
5977744d 4407 int *must_show_header,
37466447 4408 int use_color)
b67b9612 4409{
37466447
BW
4410 const char *set = diff_get_color(use_color, DIFF_METAINFO);
4411 const char *reset = diff_get_color(use_color, DIFF_RESET);
30997bb8 4412 const char *line_prefix = diff_line_prefix(o);
2715e8a9 4413 struct string_list *more_headers = NULL;
7be57610 4414
296c6bb2 4415 *must_show_header = 1;
b67b9612
JH
4416 strbuf_init(msg, PATH_MAX * 2 + 300);
4417 switch (p->status) {
4418 case DIFF_STATUS_COPIED:
98ad90fb
JH
4419 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4420 line_prefix, set, similarity_index(p));
4421 strbuf_addf(msg, "%s\n%s%scopy from ",
4422 reset, line_prefix, set);
b67b9612 4423 quote_c_style(name, msg, NULL, 0);
98ad90fb 4424 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
b67b9612 4425 quote_c_style(other, msg, NULL, 0);
37466447 4426 strbuf_addf(msg, "%s\n", reset);
b67b9612
JH
4427 break;
4428 case DIFF_STATUS_RENAMED:
98ad90fb
JH
4429 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4430 line_prefix, set, similarity_index(p));
4431 strbuf_addf(msg, "%s\n%s%srename from ",
4432 reset, line_prefix, set);
b67b9612 4433 quote_c_style(name, msg, NULL, 0);
98ad90fb
JH
4434 strbuf_addf(msg, "%s\n%s%srename to ",
4435 reset, line_prefix, set);
b67b9612 4436 quote_c_style(other, msg, NULL, 0);
37466447 4437 strbuf_addf(msg, "%s\n", reset);
b67b9612
JH
4438 break;
4439 case DIFF_STATUS_MODIFIED:
4440 if (p->score) {
98ad90fb
JH
4441 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
4442 line_prefix,
37466447 4443 set, similarity_index(p), reset);
b67b9612
JH
4444 break;
4445 }
4446 /* fallthru */
4447 default:
296c6bb2 4448 *must_show_header = 0;
b67b9612 4449 }
95433eee
EN
4450 if ((more_headers = additional_headers(o, name))) {
4451 add_formatted_headers(msg, more_headers,
4452 line_prefix, set, reset);
4453 *must_show_header = 1;
4454 }
9001dc2a 4455 if (one && two && !oideq(&one->oid, &two->oid)) {
de1d81d5 4456 const unsigned hexsz = the_hash_algo->hexsz;
3046c7f6
ĐTCD
4457 int abbrev = o->abbrev ? o->abbrev : DEFAULT_ABBREV;
4458
4459 if (o->flags.full_index)
4460 abbrev = hexsz;
b67b9612 4461
0d1e0e78 4462 if (o->flags.binary) {
b67b9612 4463 mmfile_t mf;
b78ea5fc
NTND
4464 if ((!fill_mmfile(o->repo, &mf, one) &&
4465 diff_filespec_is_binary(o->repo, one)) ||
4466 (!fill_mmfile(o->repo, &mf, two) &&
4467 diff_filespec_is_binary(o->repo, two)))
de1d81d5 4468 abbrev = hexsz;
b67b9612 4469 }
4f03666a
JK
4470 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
4471 diff_abbrev_oid(&one->oid, abbrev),
4472 diff_abbrev_oid(&two->oid, abbrev));
b67b9612
JH
4473 if (one->mode == two->mode)
4474 strbuf_addf(msg, " %06o", one->mode);
37466447 4475 strbuf_addf(msg, "%s\n", reset);
b67b9612 4476 }
b67b9612
JH
4477}
4478
6973dcae
JH
4479static void run_diff_cmd(const char *pgm,
4480 const char *name,
4481 const char *other,
cd676a51 4482 const char *attr_path,
6973dcae
JH
4483 struct diff_filespec *one,
4484 struct diff_filespec *two,
b67b9612 4485 struct strbuf *msg,
051308f6 4486 struct diff_options *o,
b67b9612 4487 struct diff_filepair *p)
6973dcae 4488{
b67b9612
JH
4489 const char *xfrm_msg = NULL;
4490 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
296c6bb2 4491 int must_show_header = 0;
a4cf900e 4492 struct userdiff_driver *drv = NULL;
b67b9612 4493
a4cf900e 4494 if (o->flags.allow_external || !o->ignore_driver_algorithm)
acd00ea0 4495 drv = userdiff_find_by_path(o->repo->index, attr_path);
a4cf900e
JC
4496
4497 if (o->flags.allow_external && drv && drv->external)
4498 pgm = drv->external;
f1af60bd 4499
37466447
BW
4500 if (msg) {
4501 /*
4502 * don't use colors when the header is intended for an
4503 * external diff driver
4504 */
4505 fill_metainfo(msg, name, other, one, two, o, p,
5977744d 4506 &must_show_header,
daa0c3d9 4507 want_color(o->use_color) && !pgm);
37466447
BW
4508 xfrm_msg = msg->len ? msg->buf : NULL;
4509 }
4510
6973dcae 4511 if (pgm) {
4bc17927 4512 run_external_diff(pgm, name, other, one, two, xfrm_msg, o);
6973dcae
JH
4513 return;
4514 }
a4cf900e
JC
4515 if (one && two) {
4516 if (!o->ignore_driver_algorithm && drv && drv->algorithm)
4517 set_diff_algorithm(o, drv->algorithm);
4518
6973dcae 4519 builtin_diff(name, other ? other : name,
296c6bb2
CC
4520 one, two, xfrm_msg, must_show_header,
4521 o, complete_rewrite);
a4cf900e 4522 } else {
c0c77734 4523 fprintf(o->file, "* Unmerged path %s\n", name);
a4cf900e 4524 }
6973dcae
JH
4525}
4526
58bf2a4c 4527static void diff_fill_oid_info(struct diff_filespec *one, struct index_state *istate)
6973dcae
JH
4528{
4529 if (DIFF_FILE_VALID(one)) {
41c9560e 4530 if (!one->oid_valid) {
6973dcae 4531 struct stat st;
4682d852 4532 if (one->is_stdin) {
a0d12c44 4533 oidclr(&one->oid);
5332b2af
JS
4534 return;
4535 }
6973dcae 4536 if (lstat(one->path, &st) < 0)
0721c314 4537 die_errno("stat '%s'", one->path);
58bf2a4c 4538 if (index_path(istate, &one->oid, one->path, &st, 0))
d7530708 4539 die("cannot hash %s", one->path);
6973dcae
JH
4540 }
4541 }
4542 else
a0d12c44 4543 oidclr(&one->oid);
6973dcae
JH
4544}
4545
cd676a51
JH
4546static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
4547{
4548 /* Strip the prefix but do not molest /dev/null and absolute paths */
ffd04e92 4549 if (*namep && !is_absolute_path(*namep)) {
cd676a51 4550 *namep += prefix_length;
d8faea9d
JN
4551 if (**namep == '/')
4552 ++*namep;
4553 }
ffd04e92 4554 if (*otherp && !is_absolute_path(*otherp)) {
cd676a51 4555 *otherp += prefix_length;
d8faea9d
JN
4556 if (**otherp == '/')
4557 ++*otherp;
4558 }
cd676a51
JH
4559}
4560
6973dcae
JH
4561static void run_diff(struct diff_filepair *p, struct diff_options *o)
4562{
4563 const char *pgm = external_diff();
663af342 4564 struct strbuf msg;
663af342
PH
4565 struct diff_filespec *one = p->one;
4566 struct diff_filespec *two = p->two;
6973dcae
JH
4567 const char *name;
4568 const char *other;
cd676a51 4569 const char *attr_path;
663af342 4570
f2d2a5de
SB
4571 name = one->path;
4572 other = (strcmp(name, two->path) ? two->path : NULL);
cd676a51
JH
4573 attr_path = name;
4574 if (o->prefix_length)
4575 strip_prefix(o->prefix_length, &name, &other);
6973dcae 4576
0d1e0e78 4577 if (!o->flags.allow_external)
bd8c1a9b
JH
4578 pgm = NULL;
4579
6973dcae 4580 if (DIFF_PAIR_UNMERGED(p)) {
cd676a51 4581 run_diff_cmd(pgm, name, NULL, attr_path,
b67b9612 4582 NULL, NULL, NULL, o, p);
6973dcae
JH
4583 return;
4584 }
4585
58bf2a4c
NTND
4586 diff_fill_oid_info(one, o->repo->index);
4587 diff_fill_oid_info(two, o->repo->index);
6973dcae 4588
6973dcae
JH
4589 if (!pgm &&
4590 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
4591 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
b67b9612
JH
4592 /*
4593 * a filepair that changes between file and symlink
6973dcae
JH
4594 * needs to be split into deletion and creation.
4595 */
4596 struct diff_filespec *null = alloc_filespec(two->path);
cd676a51 4597 run_diff_cmd(NULL, name, other, attr_path,
b78ea5fc
NTND
4598 one, null, &msg,
4599 o, p);
6973dcae 4600 free(null);
b67b9612
JH
4601 strbuf_release(&msg);
4602
6973dcae 4603 null = alloc_filespec(one->path);
cd676a51 4604 run_diff_cmd(NULL, name, other, attr_path,
b67b9612 4605 null, two, &msg, o, p);
6973dcae
JH
4606 free(null);
4607 }
4608 else
cd676a51 4609 run_diff_cmd(pgm, name, other, attr_path,
b67b9612 4610 one, two, &msg, o, p);
6973dcae 4611
663af342 4612 strbuf_release(&msg);
6973dcae
JH
4613}
4614
4615static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
4616 struct diffstat_t *diffstat)
4617{
4618 const char *name;
4619 const char *other;
4620
a4cf900e
JC
4621 if (!o->ignore_driver_algorithm) {
4622 struct userdiff_driver *drv = userdiff_find_by_path(o->repo->index,
4623 p->one->path);
4624
4625 if (drv && drv->algorithm)
4626 set_diff_algorithm(o, drv->algorithm);
4627 }
4628
6973dcae
JH
4629 if (DIFF_PAIR_UNMERGED(p)) {
4630 /* unmerged */
b78ea5fc
NTND
4631 builtin_diffstat(p->one->path, NULL, NULL, NULL,
4632 diffstat, o, p);
6973dcae
JH
4633 return;
4634 }
4635
4636 name = p->one->path;
4637 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4638
cd676a51
JH
4639 if (o->prefix_length)
4640 strip_prefix(o->prefix_length, &name, &other);
4641
58bf2a4c
NTND
4642 diff_fill_oid_info(p->one, o->repo->index);
4643 diff_fill_oid_info(p->two, o->repo->index);
6973dcae 4644
b78ea5fc
NTND
4645 builtin_diffstat(name, other, p->one, p->two,
4646 diffstat, o, p);
6973dcae
JH
4647}
4648
88246898
JS
4649static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
4650{
4651 const char *name;
4652 const char *other;
cd676a51 4653 const char *attr_path;
88246898
JS
4654
4655 if (DIFF_PAIR_UNMERGED(p)) {
4656 /* unmerged */
4657 return;
4658 }
4659
4660 name = p->one->path;
4661 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
cd676a51
JH
4662 attr_path = other ? other : name;
4663
4664 if (o->prefix_length)
4665 strip_prefix(o->prefix_length, &name, &other);
88246898 4666
58bf2a4c
NTND
4667 diff_fill_oid_info(p->one, o->repo->index);
4668 diff_fill_oid_info(p->two, o->repo->index);
88246898 4669
cd676a51 4670 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
88246898
JS
4671}
4672
e6757652 4673void repo_diff_setup(struct repository *r, struct diff_options *options)
6973dcae 4674{
be4f2b40 4675 memcpy(options, &default_diff_options, sizeof(*options));
c0c77734
DB
4676
4677 options->file = stdout;
e6757652 4678 options->repo = r;
c0c77734 4679
7648b79e
SB
4680 options->output_indicators[OUTPUT_INDICATOR_NEW] = '+';
4681 options->output_indicators[OUTPUT_INDICATOR_OLD] = '-';
4682 options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = ' ';
43d1948b 4683 options->abbrev = DEFAULT_ABBREV;
6973dcae
JH
4684 options->line_termination = '\n';
4685 options->break_opt = -1;
4686 options->rename_limit = -1;
712d2c7d 4687 options->dirstat_permille = diff_dirstat_permille_default;
6468a4e5 4688 options->context = diff_context_default;
c4888677 4689 options->interhunkcontext = diff_interhunk_context_default;
a17505f2 4690 options->ws_error_highlight = ws_error_highlight_default;
0d1e0e78 4691 options->flags.rename_empty = 1;
c28ded83 4692 options->flags.relative_name = diff_relative;
15af58c1 4693 options->objfind = NULL;
6973dcae 4694
72441af7 4695 /* pathchange left =NULL by default */
6973dcae
JH
4696 options->change = diff_change;
4697 options->add_remove = diff_addremove;
f1c96261 4698 options->use_color = diff_use_color_default;
b68ea12e 4699 options->detect_rename = diff_detect_rename_default;
07ab4dec 4700 options->xdl_opts |= diff_algorithm;
433860f3
MH
4701 if (diff_indent_heuristic)
4702 DIFF_XDL_SET(options, INDENT_HEURISTIC);
eab9a40b 4703
6d8940b5
SB
4704 options->orderfile = diff_order_file_cfg;
4705
8ef93124
SJ
4706 if (!options->flags.ignore_submodule_set)
4707 options->flags.ignore_untracked_in_submodules = 1;
4708
f89504dd 4709 if (diff_no_prefix) {
6799aadf 4710 diff_set_noprefix(options);
f89504dd 4711 } else if (!diff_mnemonic_prefix) {
6799aadf 4712 diff_set_default_prefix(options);
a5a818ee 4713 }
2e2d5ac1
SB
4714
4715 options->color_moved = diff_color_moved_default;
626c0b5d 4716 options->color_moved_ws_handling = diff_color_moved_ws_default;
6973dcae
JH
4717}
4718
4d4d4eaa
JS
4719static const char diff_status_letters[] = {
4720 DIFF_STATUS_ADDED,
4721 DIFF_STATUS_COPIED,
4722 DIFF_STATUS_DELETED,
4723 DIFF_STATUS_MODIFIED,
4724 DIFF_STATUS_RENAMED,
4725 DIFF_STATUS_TYPE_CHANGED,
4726 DIFF_STATUS_UNKNOWN,
4727 DIFF_STATUS_UNMERGED,
4728 DIFF_STATUS_FILTER_AON,
4729 DIFF_STATUS_FILTER_BROKEN,
4730 '\0',
4731};
4732
4733static unsigned int filter_bit['Z' + 1];
4734
4735static void prepare_filter_bits(void)
4736{
4737 int i;
4738
4739 if (!filter_bit[DIFF_STATUS_ADDED]) {
4740 for (i = 0; diff_status_letters[i]; i++)
4741 filter_bit[(int) diff_status_letters[i]] = (1 << i);
4742 }
4743}
4744
4745static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4746{
4747 return opt->filter & filter_bit[(int) status];
4748}
4749
4750unsigned diff_filter_bit(char status)
4751{
4752 prepare_filter_bits();
4753 return filter_bit[(int) status];
4754}
4755
9eac5954
JK
4756int diff_check_follow_pathspec(struct pathspec *ps, int die_on_error)
4757{
8260bc59
JK
4758 unsigned forbidden_magic;
4759
9eac5954
JK
4760 if (ps->nr != 1) {
4761 if (die_on_error)
4762 die(_("--follow requires exactly one pathspec"));
4763 return 0;
4764 }
8260bc59
JK
4765
4766 forbidden_magic = ps->items[0].magic & ~(PATHSPEC_FROMTOP |
4767 PATHSPEC_LITERAL);
4768 if (forbidden_magic) {
4769 if (die_on_error) {
4770 struct strbuf sb = STRBUF_INIT;
4771 pathspec_magic_names(forbidden_magic, &sb);
4772 die(_("pathspec magic not supported by --follow: %s"),
4773 sb.buf);
4774 }
4775 return 0;
4776 }
4777
9eac5954
JK
4778 return 1;
4779}
4780
28452655 4781void diff_setup_done(struct diff_options *options)
6973dcae 4782{
4d8c51aa
SB
4783 unsigned check_mask = DIFF_FORMAT_NAME |
4784 DIFF_FORMAT_NAME_STATUS |
4785 DIFF_FORMAT_CHECKDIFF |
4786 DIFF_FORMAT_NO_OUTPUT;
de1d81d5 4787 /*
4788 * This must be signed because we're comparing against a potentially
4789 * negative value.
4790 */
4791 const int hexsz = the_hash_algo->hexsz;
d7de00f7 4792
6c374008
JH
4793 if (options->set_default)
4794 options->set_default(options);
4795
4d8c51aa 4796 if (HAS_MULTI_BITS(options->output_format & check_mask))
246cac85
JNA
4797 die(_("options '%s', '%s', '%s', and '%s' cannot be used together"),
4798 "--name-only", "--name-status", "--check", "-s");
d7de00f7 4799
5e505257 4800 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
246cac85
JNA
4801 die(_("options '%s', '%s', and '%s' cannot be used together"),
4802 "-G", "-S", "--find-object");
5e505257 4803
188e9e28 4804 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_G_REGEX_MASK))
246cac85
JNA
4805 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s'"),
4806 "-G", "--pickaxe-regex", "--pickaxe-regex", "-S");
188e9e28 4807
d26ec880 4808 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_ALL_OBJFIND_MASK))
246cac85
JNA
4809 die(_("options '%s' and '%s' cannot be used together, use '%s' with '%s' and '%s'"),
4810 "--pickaxe-all", "--find-object", "--pickaxe-all", "-G", "-S");
d26ec880 4811
f245194f
JH
4812 /*
4813 * Most of the time we can say "there are changes"
4814 * only by checking if there are changed paths, but
4815 * --ignore-whitespace* options force us to look
97bf2a08 4816 * inside contents.
f245194f
JH
4817 */
4818
50f04394
JH
4819 if ((options->xdl_opts & XDF_WHITESPACE_FLAGS) ||
4820 options->ignore_regex_nr)
0d1e0e78 4821 options->flags.diff_from_contents = 1;
f245194f 4822 else
0d1e0e78 4823 options->flags.diff_from_contents = 0;
f245194f 4824
0d1e0e78 4825 if (options->flags.find_copies_harder)
03b9d560
JH
4826 options->detect_rename = DIFF_DETECT_COPY;
4827
0d1e0e78 4828 if (!options->flags.relative_name)
cd676a51
JH
4829 options->prefix = NULL;
4830 if (options->prefix)
4831 options->prefix_length = strlen(options->prefix);
4832 else
4833 options->prefix_length = 0;
4834
c6744349
TH
4835 if (options->output_format & (DIFF_FORMAT_NAME |
4836 DIFF_FORMAT_NAME_STATUS |
4837 DIFF_FORMAT_CHECKDIFF |
4838 DIFF_FORMAT_NO_OUTPUT))
4839 options->output_format &= ~(DIFF_FORMAT_RAW |
74e2abe5 4840 DIFF_FORMAT_NUMSTAT |
c6744349 4841 DIFF_FORMAT_DIFFSTAT |
ebd124c6 4842 DIFF_FORMAT_SHORTSTAT |
7df7c019 4843 DIFF_FORMAT_DIRSTAT |
c6744349
TH
4844 DIFF_FORMAT_SUMMARY |
4845 DIFF_FORMAT_PATCH);
4846
6973dcae
JH
4847 /*
4848 * These cases always need recursive; we do not drop caller-supplied
4849 * recursive bits for other formats here.
4850 */
c6744349 4851 if (options->output_format & (DIFF_FORMAT_PATCH |
74e2abe5 4852 DIFF_FORMAT_NUMSTAT |
c6744349 4853 DIFF_FORMAT_DIFFSTAT |
ebd124c6 4854 DIFF_FORMAT_SHORTSTAT |
7df7c019 4855 DIFF_FORMAT_DIRSTAT |
d7014dc0 4856 DIFF_FORMAT_SUMMARY |
c6744349 4857 DIFF_FORMAT_CHECKDIFF))
0d1e0e78 4858 options->flags.recursive = 1;
5e363541 4859 /*
3969cf7d 4860 * Also pickaxe would not work very well if you do not say recursive
5e363541 4861 */
cf63051a 4862 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
0d1e0e78 4863 options->flags.recursive = 1;
ae6d5c1b
JL
4864 /*
4865 * When patches are generated, submodules diffed against the work tree
4866 * must be checked for dirtiness too so it can be shown in the output
4867 */
4868 if (options->output_format & DIFF_FORMAT_PATCH)
0d1e0e78 4869 options->flags.dirty_submodules = 1;
5e363541 4870
6973dcae
JH
4871 if (options->detect_rename && options->rename_limit < 0)
4872 options->rename_limit = diff_rename_limit_default;
de1d81d5 4873 if (hexsz < options->abbrev)
4874 options->abbrev = hexsz; /* full */
6973dcae 4875
68aacb2f
JH
4876 /*
4877 * It does not make sense to show the first hit we happened
4878 * to have found. It does not make sense not to return with
4879 * exit code in such a case either.
4880 */
0d1e0e78 4881 if (options->flags.quick) {
68aacb2f 4882 options->output_format = DIFF_FORMAT_NO_OUTPUT;
0d1e0e78 4883 options->flags.exit_with_status = 1;
68aacb2f 4884 }
ee7fb0b1 4885
0ea7d5b6 4886 options->diff_path_counter = 0;
b0e2c999 4887
9eac5954
JK
4888 if (options->flags.follow_renames)
4889 diff_check_follow_pathspec(&options->pathspec, 1);
2e2d5ac1
SB
4890
4891 if (!options->use_color || external_diff())
4892 options->color_moved = 0;
4a288478 4893
75408ca9
JS
4894 if (options->filter_not) {
4895 if (!options->filter)
4896 options->filter = ~filter_bit[DIFF_STATUS_FILTER_AON];
4897 options->filter &= ~options->filter_not;
4898 }
6973dcae
JH
4899}
4900
dea007fb
MM
4901int parse_long_opt(const char *opt, const char **argv,
4902 const char **optarg)
4903{
4904 const char *arg = argv[0];
95b567c7 4905 if (!skip_prefix(arg, "--", &arg))
dea007fb 4906 return 0;
95b567c7 4907 if (!skip_prefix(arg, opt, &arg))
dea007fb 4908 return 0;
b0d12fc9 4909 if (*arg == '=') { /* stuck form: --option=value */
dea007fb
MM
4910 *optarg = arg + 1;
4911 return 1;
4912 }
4913 if (*arg != '\0')
4914 return 0;
4915 /* separate form: --option value */
4916 if (!argv[1])
4917 die("Option '--%s' requires a value", opt);
4918 *optarg = argv[1];
4919 return 2;
4920}
4921
84b5089e 4922static int diff_opt_stat(const struct option *opt, const char *value, int unset)
4d7f7a4a 4923{
84b5089e 4924 struct diff_options *options = opt->value;
4d7f7a4a
JN
4925 int width = options->stat_width;
4926 int name_width = options->stat_name_width;
969fe57b 4927 int graph_width = options->stat_graph_width;
808e1db2 4928 int count = options->stat_count;
84b5089e 4929 char *end;
4d7f7a4a 4930
84b5089e 4931 BUG_ON_OPT_NEG(unset);
4d7f7a4a 4932
84b5089e
NTND
4933 if (!strcmp(opt->long_name, "stat")) {
4934 if (value) {
4935 width = strtoul(value, &end, 10);
4936 if (*end == ',')
4937 name_width = strtoul(end+1, &end, 10);
4938 if (*end == ',')
4939 count = strtoul(end+1, &end, 10);
4940 if (*end)
4941 return error(_("invalid --stat value: %s"), value);
1e57208e 4942 }
84b5089e
NTND
4943 } else if (!strcmp(opt->long_name, "stat-width")) {
4944 width = strtoul(value, &end, 10);
4945 if (*end)
4946 return error(_("%s expects a numerical value"),
4947 opt->long_name);
4948 } else if (!strcmp(opt->long_name, "stat-name-width")) {
4949 name_width = strtoul(value, &end, 10);
4950 if (*end)
4951 return error(_("%s expects a numerical value"),
4952 opt->long_name);
4953 } else if (!strcmp(opt->long_name, "stat-graph-width")) {
4954 graph_width = strtoul(value, &end, 10);
4955 if (*end)
4956 return error(_("%s expects a numerical value"),
4957 opt->long_name);
4958 } else if (!strcmp(opt->long_name, "stat-count")) {
4959 count = strtoul(value, &end, 10);
4960 if (*end)
4961 return error(_("%s expects a numerical value"),
4962 opt->long_name);
4963 } else
4964 BUG("%s should not get here", opt->long_name);
4d7f7a4a 4965
9d484b92 4966 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
4d7f7a4a
JN
4967 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4968 options->stat_name_width = name_width;
969fe57b 4969 options->stat_graph_width = graph_width;
4d7f7a4a 4970 options->stat_width = width;
808e1db2 4971 options->stat_count = count;
84b5089e 4972 return 0;
4d7f7a4a
JN
4973}
4974
333f3fb0
JH
4975static int parse_dirstat_opt(struct diff_options *options, const char *params)
4976{
51670fc8
JH
4977 struct strbuf errmsg = STRBUF_INIT;
4978 if (parse_dirstat_params(options, params, &errmsg))
7478ac57 4979 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
51670fc8
JH
4980 errmsg.buf);
4981 strbuf_release(&errmsg);
333f3fb0
JH
4982 /*
4983 * The caller knows a dirstat-related option is given from the command
4984 * line; allow it to say "return this_function();"
4985 */
9d484b92 4986 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
333f3fb0
JH
4987 options->output_format |= DIFF_FORMAT_DIRSTAT;
4988 return 1;
4989}
4990
d2d3f273
NTND
4991static int diff_opt_diff_filter(const struct option *option,
4992 const char *optarg, int unset)
1ecc1cbd 4993{
d2d3f273 4994 struct diff_options *opt = option->value;
1ecc1cbd
JH
4995 int i, optch;
4996
d2d3f273 4997 BUG_ON_OPT_NEG(unset);
1ecc1cbd 4998 prepare_filter_bits();
7f2ea5f0 4999
1ecc1cbd
JH
5000 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
5001 unsigned int bit;
7f2ea5f0
JH
5002 int negate;
5003
5004 if ('a' <= optch && optch <= 'z') {
5005 negate = 1;
5006 optch = toupper(optch);
5007 } else {
5008 negate = 0;
5009 }
1ecc1cbd
JH
5010
5011 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
5012 if (!bit)
d2d3f273
NTND
5013 return error(_("unknown change class '%c' in --diff-filter=%s"),
5014 optarg[i], optarg);
7f2ea5f0 5015 if (negate)
75408ca9 5016 opt->filter_not |= bit;
7f2ea5f0
JH
5017 else
5018 opt->filter |= bit;
1ecc1cbd
JH
5019 }
5020 return 0;
5021}
5022
3b335762
NTND
5023static void enable_patch_output(int *fmt)
5024{
71482d38
MM
5025 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
5026 *fmt |= DIFF_FORMAT_PATCH;
5027}
5028
5a749d9f
NTND
5029static int diff_opt_ws_error_highlight(const struct option *option,
5030 const char *arg, int unset)
b8767f79 5031{
5a749d9f 5032 struct diff_options *opt = option->value;
077965f8 5033 int val = parse_ws_error_highlight(arg);
b8767f79 5034
5a749d9f
NTND
5035 BUG_ON_OPT_NEG(unset);
5036 if (val < 0)
5037 return error(_("unknown value after ws-error-highlight=%.*s"),
5038 -1 - val, arg);
b8767f79 5039 opt->ws_error_highlight = val;
5a749d9f 5040 return 0;
b8767f79
JH
5041}
5042
a75f28cb
NTND
5043static int diff_opt_find_object(const struct option *option,
5044 const char *arg, int unset)
15af58c1 5045{
a75f28cb 5046 struct diff_options *opt = option->value;
15af58c1
SB
5047 struct object_id oid;
5048
a75f28cb 5049 BUG_ON_OPT_NEG(unset);
d850b7a5 5050 if (repo_get_oid(the_repository, arg, &oid))
a75f28cb 5051 return error(_("unable to resolve '%s'"), arg);
15af58c1
SB
5052
5053 if (!opt->objfind)
ca56dadb 5054 CALLOC_ARRAY(opt->objfind, 1);
15af58c1
SB
5055
5056 opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
5057 opt->flags.recursive = 1;
5058 opt->flags.tree_in_recursive = 1;
5059 oidset_insert(opt->objfind, &oid);
a75f28cb 5060 return 0;
15af58c1
SB
5061}
5062
df84a436
NTND
5063static int diff_opt_anchored(const struct option *opt,
5064 const char *arg, int unset)
5065{
5066 struct diff_options *options = opt->value;
5067
5068 BUG_ON_OPT_NEG(unset);
5069 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
5070 ALLOC_GROW(options->anchors, options->anchors_nr + 1,
5071 options->anchors_alloc);
5072 options->anchors[options->anchors_nr++] = xstrdup(arg);
5073 return 0;
5074}
5075
6d9af6f4
NTND
5076static int diff_opt_binary(const struct option *opt,
5077 const char *arg, int unset)
5078{
5079 struct diff_options *options = opt->value;
5080
5081 BUG_ON_OPT_NEG(unset);
5082 BUG_ON_OPT_ARG(arg);
5083 enable_patch_output(&options->output_format);
5084 options->flags.binary = 1;
5085 return 0;
5086}
5087
ced4e179
NTND
5088static int diff_opt_break_rewrites(const struct option *opt,
5089 const char *arg, int unset)
5090{
5091 int *break_opt = opt->value;
5092 int opt1, opt2;
5093
5094 BUG_ON_OPT_NEG(unset);
5095 if (!arg)
5096 arg = "";
5097 opt1 = parse_rename_score(&arg);
5098 if (*arg == 0)
5099 opt2 = 0;
5100 else if (*arg != '/')
5101 return error(_("%s expects <n>/<m> form"), opt->long_name);
5102 else {
5103 arg++;
5104 opt2 = parse_rename_score(&arg);
5105 }
5106 if (*arg != 0)
5107 return error(_("%s expects <n>/<m> form"), opt->long_name);
5108 *break_opt = opt1 | (opt2 << 16);
5109 return 0;
5110}
5111
af2f3680
NTND
5112static int diff_opt_char(const struct option *opt,
5113 const char *arg, int unset)
5114{
5115 char *value = opt->value;
5116
5117 BUG_ON_OPT_NEG(unset);
5118 if (arg[1])
5119 return error(_("%s expects a character, got '%s'"),
5120 opt->long_name, arg);
5121 *value = arg[0];
5122 return 0;
5123}
5124
59311a98
NTND
5125static int diff_opt_color_moved(const struct option *opt,
5126 const char *arg, int unset)
5127{
5128 struct diff_options *options = opt->value;
5129
5130 if (unset) {
5131 options->color_moved = COLOR_MOVED_NO;
5132 } else if (!arg) {
5133 if (diff_color_moved_default)
5134 options->color_moved = diff_color_moved_default;
5135 if (options->color_moved == COLOR_MOVED_NO)
5136 options->color_moved = COLOR_MOVED_DEFAULT;
5137 } else {
5138 int cm = parse_color_moved(arg);
5139 if (cm < 0)
5140 return error(_("bad --color-moved argument: %s"), arg);
5141 options->color_moved = cm;
5142 }
5143 return 0;
5144}
5145
8ce2020f
NTND
5146static int diff_opt_color_moved_ws(const struct option *opt,
5147 const char *arg, int unset)
5148{
5149 struct diff_options *options = opt->value;
5150 unsigned cm;
5151
bb987290
NTND
5152 if (unset) {
5153 options->color_moved_ws_handling = 0;
5154 return 0;
5155 }
5156
8ce2020f
NTND
5157 cm = parse_color_moved_ws(arg);
5158 if (cm & COLOR_MOVED_WS_ERROR)
5159 return error(_("invalid mode '%s' in --color-moved-ws"), arg);
5160 options->color_moved_ws_handling = cm;
5161 return 0;
5162}
5163
212db69d
NTND
5164static int diff_opt_color_words(const struct option *opt,
5165 const char *arg, int unset)
5166{
5167 struct diff_options *options = opt->value;
5168
5169 BUG_ON_OPT_NEG(unset);
5170 options->use_color = 1;
5171 options->word_diff = DIFF_WORDS_COLOR;
5172 options->word_regex = arg;
5173 return 0;
5174}
5175
7d7942b7
NTND
5176static int diff_opt_compact_summary(const struct option *opt,
5177 const char *arg, int unset)
5178{
5179 struct diff_options *options = opt->value;
5180
5181 BUG_ON_OPT_ARG(arg);
5182 if (unset) {
5183 options->flags.stat_with_summary = 0;
5184 } else {
5185 options->flags.stat_with_summary = 1;
9d484b92 5186 options->output_format &= ~DIFF_FORMAT_NO_OUTPUT;
7d7942b7
NTND
5187 options->output_format |= DIFF_FORMAT_DIFFSTAT;
5188 }
5189 return 0;
5190}
5191
10f35b1c
NTND
5192static int diff_opt_diff_algorithm(const struct option *opt,
5193 const char *arg, int unset)
5194{
5195 struct diff_options *options = opt->value;
10f35b1c
NTND
5196
5197 BUG_ON_OPT_NEG(unset);
11e95e16
JC
5198
5199 if (set_diff_algorithm(options, arg))
10f35b1c
NTND
5200 return error(_("option diff-algorithm accepts \"myers\", "
5201 "\"minimal\", \"patience\" and \"histogram\""));
5202
a4cf900e
JC
5203 options->ignore_driver_algorithm = 1;
5204
11e95e16
JC
5205 return 0;
5206}
5207
5208static int diff_opt_diff_algorithm_no_arg(const struct option *opt,
5209 const char *arg, int unset)
5210{
5211 struct diff_options *options = opt->value;
5212
5213 BUG_ON_OPT_NEG(unset);
5214 BUG_ON_OPT_ARG(arg);
5215
5216 if (set_diff_algorithm(options, opt->long_name))
5217 BUG("available diff algorithms include \"myers\", "
5218 "\"minimal\", \"patience\" and \"histogram\"");
5219
a4cf900e
JC
5220 options->ignore_driver_algorithm = 1;
5221
10f35b1c
NTND
5222 return 0;
5223}
5224
4ce7aab5
NTND
5225static int diff_opt_dirstat(const struct option *opt,
5226 const char *arg, int unset)
5227{
5228 struct diff_options *options = opt->value;
5229
5230 BUG_ON_OPT_NEG(unset);
5231 if (!strcmp(opt->long_name, "cumulative")) {
5232 if (arg)
5233 BUG("how come --cumulative take a value?");
5234 arg = "cumulative";
5235 } else if (!strcmp(opt->long_name, "dirstat-by-file"))
5236 parse_dirstat_opt(options, "files");
5237 parse_dirstat_opt(options, arg ? arg : "");
5238 return 0;
5239}
5240
7f64850d
NTND
5241static int diff_opt_find_copies(const struct option *opt,
5242 const char *arg, int unset)
5243{
5244 struct diff_options *options = opt->value;
5245
5246 BUG_ON_OPT_NEG(unset);
5247 if (!arg)
5248 arg = "";
5249 options->rename_score = parse_rename_score(&arg);
5250 if (*arg != 0)
5251 return error(_("invalid argument to %s"), opt->long_name);
5252
5253 if (options->detect_rename == DIFF_DETECT_COPY)
5254 options->flags.find_copies_harder = 1;
5255 else
5256 options->detect_rename = DIFF_DETECT_COPY;
5257
5258 return 0;
5259}
5260
f476308b
NTND
5261static int diff_opt_find_renames(const struct option *opt,
5262 const char *arg, int unset)
5263{
5264 struct diff_options *options = opt->value;
5265
5266 BUG_ON_OPT_NEG(unset);
5267 if (!arg)
5268 arg = "";
5269 options->rename_score = parse_rename_score(&arg);
5270 if (*arg != 0)
5271 return error(_("invalid argument to %s"), opt->long_name);
5272
5273 options->detect_rename = DIFF_DETECT_RENAME;
5274 return 0;
5275}
5276
1e9250b5
NTND
5277static int diff_opt_follow(const struct option *opt,
5278 const char *arg, int unset)
5279{
5280 struct diff_options *options = opt->value;
5281
5282 BUG_ON_OPT_ARG(arg);
5283 if (unset) {
5284 options->flags.follow_renames = 0;
5285 options->flags.default_follow_renames = 0;
5286 } else {
5287 options->flags.follow_renames = 1;
5288 }
5289 return 0;
5290}
5291
b680ee14
NTND
5292static int diff_opt_ignore_submodules(const struct option *opt,
5293 const char *arg, int unset)
5294{
5295 struct diff_options *options = opt->value;
5296
5297 BUG_ON_OPT_NEG(unset);
5298 if (!arg)
5299 arg = "all";
5300 options->flags.override_submodule_config = 1;
5301 handle_ignore_submodules_arg(options, arg);
5302 return 0;
5303}
5304
2f81cf98
NTND
5305static int diff_opt_line_prefix(const struct option *opt,
5306 const char *optarg, int unset)
5307{
5308 struct diff_options *options = opt->value;
5309
5310 BUG_ON_OPT_NEG(unset);
5311 options->line_prefix = optarg;
5312 options->line_prefix_length = strlen(options->line_prefix);
5313 graph_setup_line_prefix(options);
5314 return 0;
5315}
5316
11c659d8
NTND
5317static int diff_opt_no_prefix(const struct option *opt,
5318 const char *optarg, int unset)
5319{
5320 struct diff_options *options = opt->value;
5321
5322 BUG_ON_OPT_NEG(unset);
5323 BUG_ON_OPT_ARG(optarg);
6799aadf 5324 diff_set_noprefix(options);
11c659d8
NTND
5325 return 0;
5326}
5327
b39a5697
JK
5328static int diff_opt_default_prefix(const struct option *opt,
5329 const char *optarg, int unset)
5330{
5331 struct diff_options *options = opt->value;
5332
5333 BUG_ON_OPT_NEG(unset);
5334 BUG_ON_OPT_ARG(optarg);
5335 diff_set_default_prefix(options);
11c659d8
NTND
5336 return 0;
5337}
5338
af2f3680
NTND
5339static enum parse_opt_result diff_opt_output(struct parse_opt_ctx_t *ctx,
5340 const struct option *opt,
5341 const char *arg, int unset)
5342{
5343 struct diff_options *options = opt->value;
5344 char *path;
5345
5346 BUG_ON_OPT_NEG(unset);
5347 path = prefix_filename(ctx->prefix, arg);
5348 options->file = xfopen(path, "w");
5349 options->close_file = 1;
5350 if (options->use_color != GIT_COLOR_ALWAYS)
5351 options->use_color = GIT_COLOR_NEVER;
5352 free(path);
5353 return 0;
5354}
5355
31fd640e
NTND
5356static int diff_opt_patience(const struct option *opt,
5357 const char *arg, int unset)
5358{
5359 struct diff_options *options = opt->value;
5360 int i;
5361
5362 BUG_ON_OPT_NEG(unset);
5363 BUG_ON_OPT_ARG(arg);
31fd640e
NTND
5364 /*
5365 * Both --patience and --anchored use PATIENCE_DIFF
5366 * internally, so remove any anchors previously
5367 * specified.
5368 */
5369 for (i = 0; i < options->anchors_nr; i++)
5370 free(options->anchors[i]);
5371 options->anchors_nr = 0;
a4cf900e 5372 options->ignore_driver_algorithm = 1;
11e95e16
JC
5373
5374 return set_diff_algorithm(options, "patience");
31fd640e
NTND
5375}
5376
296d4a94
MK
5377static int diff_opt_ignore_regex(const struct option *opt,
5378 const char *arg, int unset)
5379{
5380 struct diff_options *options = opt->value;
5381 regex_t *regex;
5382
5383 BUG_ON_OPT_NEG(unset);
5384 regex = xmalloc(sizeof(*regex));
5385 if (regcomp(regex, arg, REG_EXTENDED | REG_NEWLINE))
5386 return error(_("invalid regex given to -I: '%s'"), arg);
5387 ALLOC_GROW(options->ignore_regex, options->ignore_regex_nr + 1,
5388 options->ignore_regex_alloc);
5389 options->ignore_regex[options->ignore_regex_nr++] = regex;
5390 return 0;
5391}
5392
a41cfb32
NTND
5393static int diff_opt_pickaxe_regex(const struct option *opt,
5394 const char *arg, int unset)
5395{
5396 struct diff_options *options = opt->value;
5397
5398 BUG_ON_OPT_NEG(unset);
5399 options->pickaxe = arg;
5400 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
5401 return 0;
5402}
5403
5404static int diff_opt_pickaxe_string(const struct option *opt,
5405 const char *arg, int unset)
5406{
5407 struct diff_options *options = opt->value;
5408
5409 BUG_ON_OPT_NEG(unset);
5410 options->pickaxe = arg;
5411 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
5412 return 0;
5413}
5414
0b1c5b59
NTND
5415static int diff_opt_relative(const struct option *opt,
5416 const char *arg, int unset)
5417{
5418 struct diff_options *options = opt->value;
5419
c28ded83 5420 options->flags.relative_name = !unset;
0b1c5b59
NTND
5421 if (arg)
5422 options->prefix = arg;
5423 return 0;
5424}
5425
125dcea9
NTND
5426static int diff_opt_submodule(const struct option *opt,
5427 const char *arg, int unset)
5428{
5429 struct diff_options *options = opt->value;
5430
5431 BUG_ON_OPT_NEG(unset);
5432 if (!arg)
5433 arg = "log";
5434 if (parse_submodule_params(options, arg))
5435 return error(_("failed to parse --submodule option parameter: '%s'"),
5436 arg);
5437 return 0;
5438}
5439
8ab76977
NTND
5440static int diff_opt_textconv(const struct option *opt,
5441 const char *arg, int unset)
5442{
5443 struct diff_options *options = opt->value;
5444
5445 BUG_ON_OPT_ARG(arg);
5446 if (unset) {
5447 options->flags.allow_textconv = 0;
5448 } else {
5449 options->flags.allow_textconv = 1;
5450 options->flags.textconv_set_via_cmdline = 1;
5451 }
5452 return 0;
5453}
5454
d473e2e0
NTND
5455static int diff_opt_unified(const struct option *opt,
5456 const char *arg, int unset)
5457{
5458 struct diff_options *options = opt->value;
5459 char *s;
5460
5461 BUG_ON_OPT_NEG(unset);
5462
8ef05193
NTND
5463 if (arg) {
5464 options->context = strtol(arg, &s, 10);
5465 if (*s)
5466 return error(_("%s expects a numerical value"), "--unified");
5467 }
d473e2e0
NTND
5468 enable_patch_output(&options->output_format);
5469
5470 return 0;
5471}
5472
e9fb39b6
NTND
5473static int diff_opt_word_diff(const struct option *opt,
5474 const char *arg, int unset)
5475{
5476 struct diff_options *options = opt->value;
5477
5478 BUG_ON_OPT_NEG(unset);
5479 if (arg) {
5480 if (!strcmp(arg, "plain"))
5481 options->word_diff = DIFF_WORDS_PLAIN;
5482 else if (!strcmp(arg, "color")) {
5483 options->use_color = 1;
5484 options->word_diff = DIFF_WORDS_COLOR;
5485 }
5486 else if (!strcmp(arg, "porcelain"))
5487 options->word_diff = DIFF_WORDS_PORCELAIN;
5488 else if (!strcmp(arg, "none"))
5489 options->word_diff = DIFF_WORDS_NONE;
5490 else
5491 return error(_("bad --word-diff argument: %s"), arg);
5492 } else {
5493 if (options->word_diff == DIFF_WORDS_NONE)
5494 options->word_diff = DIFF_WORDS_PLAIN;
5495 }
5496 return 0;
5497}
5498
797df119
NTND
5499static int diff_opt_word_diff_regex(const struct option *opt,
5500 const char *arg, int unset)
5501{
5502 struct diff_options *options = opt->value;
5503
5504 BUG_ON_OPT_NEG(unset);
5505 if (options->word_diff == DIFF_WORDS_NONE)
5506 options->word_diff = DIFF_WORDS_PLAIN;
5507 options->word_regex = arg;
5508 return 0;
5509}
5510
1eb4136a
JH
5511static int diff_opt_rotate_to(const struct option *opt, const char *arg, int unset)
5512{
5513 struct diff_options *options = opt->value;
5514
5515 BUG_ON_OPT_NEG(unset);
5516 if (!strcmp(opt->long_name, "skip-to"))
5517 options->skip_instead_of_rotate = 1;
5518 else
5519 options->skip_instead_of_rotate = 0;
5520 options->rotate_to = arg;
5521 return 0;
5522}
5523
0a868031
PB
5524/*
5525 * Consider adding new flags to __git_diff_common_options
5526 * in contrib/completion/git-completion.bash
5527 */
c5630c48
RS
5528struct option *add_diff_options(const struct option *opts,
5529 struct diff_options *options)
4a288478
NTND
5530{
5531 struct option parseopts[] = {
cc013c22
NTND
5532 OPT_GROUP(N_("Diff output format options")),
5533 OPT_BITOP('p', "patch", &options->output_format,
5534 N_("generate patch"),
5535 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
9d484b92
JH
5536 OPT_SET_INT('s', "no-patch", &options->output_format,
5537 N_("suppress diff output"), DIFF_FORMAT_NO_OUTPUT),
cc013c22
NTND
5538 OPT_BITOP('u', NULL, &options->output_format,
5539 N_("generate patch"),
5540 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
d473e2e0
NTND
5541 OPT_CALLBACK_F('U', "unified", options, N_("<n>"),
5542 N_("generate diffs with <n> lines context"),
8ef05193 5543 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_unified),
7fd9a1ba
NTND
5544 OPT_BOOL('W', "function-context", &options->flags.funccontext,
5545 N_("generate diffs with <n> lines context")),
9d484b92 5546 OPT_BITOP(0, "raw", &options->output_format,
ed881486 5547 N_("generate the diff in raw format"),
9d484b92 5548 DIFF_FORMAT_RAW, DIFF_FORMAT_NO_OUTPUT),
c659f303
NTND
5549 OPT_BITOP(0, "patch-with-raw", &options->output_format,
5550 N_("synonym for '-p --raw'"),
5551 DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW,
5552 DIFF_FORMAT_NO_OUTPUT),
e550f585
NTND
5553 OPT_BITOP(0, "patch-with-stat", &options->output_format,
5554 N_("synonym for '-p --stat'"),
5555 DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT,
5556 DIFF_FORMAT_NO_OUTPUT),
9d484b92 5557 OPT_BITOP(0, "numstat", &options->output_format,
e5673620 5558 N_("machine friendly --stat"),
9d484b92
JH
5559 DIFF_FORMAT_NUMSTAT, DIFF_FORMAT_NO_OUTPUT),
5560 OPT_BITOP(0, "shortstat", &options->output_format,
e5673620 5561 N_("output only the last line of --stat"),
9d484b92 5562 DIFF_FORMAT_SHORTSTAT, DIFF_FORMAT_NO_OUTPUT),
4ce7aab5
NTND
5563 OPT_CALLBACK_F('X', "dirstat", options, N_("<param1,param2>..."),
5564 N_("output the distribution of relative amount of changes for each sub-directory"),
5565 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5566 diff_opt_dirstat),
5567 OPT_CALLBACK_F(0, "cumulative", options, NULL,
5568 N_("synonym for --dirstat=cumulative"),
5569 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5570 diff_opt_dirstat),
5571 OPT_CALLBACK_F(0, "dirstat-by-file", options, N_("<param1,param2>..."),
5572 N_("synonym for --dirstat=files,param1,param2..."),
5573 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5574 diff_opt_dirstat),
fc6af3e9
NTND
5575 OPT_BIT_F(0, "check", &options->output_format,
5576 N_("warn if changes introduce conflict markers or whitespace errors"),
5577 DIFF_FORMAT_CHECKDIFF, PARSE_OPT_NONEG),
9d484b92 5578 OPT_BITOP(0, "summary", &options->output_format,
70a30417 5579 N_("condensed summary such as creations, renames and mode changes"),
9d484b92 5580 DIFF_FORMAT_SUMMARY, DIFF_FORMAT_NO_OUTPUT),
0e840e2a
NTND
5581 OPT_BIT_F(0, "name-only", &options->output_format,
5582 N_("show only names of changed files"),
5583 DIFF_FORMAT_NAME, PARSE_OPT_NONEG),
a2387472
NTND
5584 OPT_BIT_F(0, "name-status", &options->output_format,
5585 N_("show only names and status of changed files"),
5586 DIFF_FORMAT_NAME_STATUS, PARSE_OPT_NONEG),
84b5089e
NTND
5587 OPT_CALLBACK_F(0, "stat", options, N_("<width>[,<name-width>[,<count>]]"),
5588 N_("generate diffstat"),
5589 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_stat),
5590 OPT_CALLBACK_F(0, "stat-width", options, N_("<width>"),
5591 N_("generate diffstat with a given width"),
5592 PARSE_OPT_NONEG, diff_opt_stat),
5593 OPT_CALLBACK_F(0, "stat-name-width", options, N_("<width>"),
5594 N_("generate diffstat with a given name width"),
5595 PARSE_OPT_NONEG, diff_opt_stat),
5596 OPT_CALLBACK_F(0, "stat-graph-width", options, N_("<width>"),
5597 N_("generate diffstat with a given graph width"),
5598 PARSE_OPT_NONEG, diff_opt_stat),
5599 OPT_CALLBACK_F(0, "stat-count", options, N_("<count>"),
5600 N_("generate diffstat with limited lines"),
5601 PARSE_OPT_NONEG, diff_opt_stat),
7d7942b7
NTND
5602 OPT_CALLBACK_F(0, "compact-summary", options, NULL,
5603 N_("generate compact summary in diffstat"),
5604 PARSE_OPT_NOARG, diff_opt_compact_summary),
6d9af6f4
NTND
5605 OPT_CALLBACK_F(0, "binary", options, NULL,
5606 N_("output a binary diff that can be applied"),
5607 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_binary),
4fe01672
NTND
5608 OPT_BOOL(0, "full-index", &options->flags.full_index,
5609 N_("show full pre- and post-image object names on the \"index\" lines")),
8b81c26e
NTND
5610 OPT_COLOR_FLAG(0, "color", &options->use_color,
5611 N_("show colored diff")),
5a749d9f
NTND
5612 OPT_CALLBACK_F(0, "ws-error-highlight", options, N_("<kind>"),
5613 N_("highlight whitespace errors in the 'context', 'old' or 'new' lines in the diff"),
5614 PARSE_OPT_NONEG, diff_opt_ws_error_highlight),
1a1eb164
NTND
5615 OPT_SET_INT('z', NULL, &options->line_termination,
5616 N_("do not munge pathnames and use NULs as output field terminators in --raw or --numstat"),
5617 0),
d8774183 5618 OPT__ABBREV(&options->abbrev),
31fba9d3
NTND
5619 OPT_STRING_F(0, "src-prefix", &options->a_prefix, N_("<prefix>"),
5620 N_("show the given source prefix instead of \"a/\""),
5621 PARSE_OPT_NONEG),
5622 OPT_STRING_F(0, "dst-prefix", &options->b_prefix, N_("<prefix>"),
8a1569d6 5623 N_("show the given destination prefix instead of \"b/\""),
31fba9d3 5624 PARSE_OPT_NONEG),
2f81cf98
NTND
5625 OPT_CALLBACK_F(0, "line-prefix", options, N_("<prefix>"),
5626 N_("prepend an additional prefix to every line of output"),
5627 PARSE_OPT_NONEG, diff_opt_line_prefix),
11c659d8
NTND
5628 OPT_CALLBACK_F(0, "no-prefix", options, NULL,
5629 N_("do not show any source or destination prefix"),
5630 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_no_prefix),
b39a5697
JK
5631 OPT_CALLBACK_F(0, "default-prefix", options, NULL,
5632 N_("use default prefixes a/ and b/"),
5633 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_default_prefix),
16ed6c97
NTND
5634 OPT_INTEGER_F(0, "inter-hunk-context", &options->interhunkcontext,
5635 N_("show context between diff hunks up to the specified number of lines"),
5636 PARSE_OPT_NONEG),
af2f3680
NTND
5637 OPT_CALLBACK_F(0, "output-indicator-new",
5638 &options->output_indicators[OUTPUT_INDICATOR_NEW],
5639 N_("<char>"),
5640 N_("specify the character to indicate a new line instead of '+'"),
5641 PARSE_OPT_NONEG, diff_opt_char),
5642 OPT_CALLBACK_F(0, "output-indicator-old",
5643 &options->output_indicators[OUTPUT_INDICATOR_OLD],
5644 N_("<char>"),
5645 N_("specify the character to indicate an old line instead of '-'"),
5646 PARSE_OPT_NONEG, diff_opt_char),
5647 OPT_CALLBACK_F(0, "output-indicator-context",
5648 &options->output_indicators[OUTPUT_INDICATOR_CONTEXT],
5649 N_("<char>"),
5650 N_("specify the character to indicate a context instead of ' '"),
5651 PARSE_OPT_NONEG, diff_opt_char),
5652
ced4e179
NTND
5653 OPT_GROUP(N_("Diff rename options")),
5654 OPT_CALLBACK_F('B', "break-rewrites", &options->break_opt, N_("<n>[/<m>]"),
5655 N_("break complete rewrite changes into pairs of delete and create"),
5656 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5657 diff_opt_break_rewrites),
f476308b
NTND
5658 OPT_CALLBACK_F('M', "find-renames", options, N_("<n>"),
5659 N_("detect renames"),
5660 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5661 diff_opt_find_renames),
1e533296
NTND
5662 OPT_SET_INT_F('D', "irreversible-delete", &options->irreversible_delete,
5663 N_("omit the preimage for deletes"),
5664 1, PARSE_OPT_NONEG),
7f64850d
NTND
5665 OPT_CALLBACK_F('C', "find-copies", options, N_("<n>"),
5666 N_("detect copies"),
5667 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5668 diff_opt_find_copies),
bdd4741b
NTND
5669 OPT_BOOL(0, "find-copies-harder", &options->flags.find_copies_harder,
5670 N_("use unmodified files as source to find copies")),
cdc43eb0
NTND
5671 OPT_SET_INT_F(0, "no-renames", &options->detect_rename,
5672 N_("disable rename detection"),
5673 0, PARSE_OPT_NONEG),
5674 OPT_BOOL(0, "rename-empty", &options->flags.rename_empty,
5675 N_("use empty blobs as rename source")),
1e9250b5
NTND
5676 OPT_CALLBACK_F(0, "follow", options, NULL,
5677 N_("continue listing the history of a file beyond renames"),
5678 PARSE_OPT_NOARG, diff_opt_follow),
bffee749
NTND
5679 OPT_INTEGER('l', NULL, &options->rename_limit,
5680 N_("prevent rename/copy detection if the number of rename/copy targets exceeds given limit")),
ced4e179 5681
2e75f922 5682 OPT_GROUP(N_("Diff algorithm options")),
11e95e16
JC
5683 OPT_CALLBACK_F(0, "minimal", options, NULL,
5684 N_("produce the smallest possible diff"),
5685 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5686 diff_opt_diff_algorithm_no_arg),
87649a16
NTND
5687 OPT_BIT_F('w', "ignore-all-space", &options->xdl_opts,
5688 N_("ignore whitespace when comparing lines"),
5689 XDF_IGNORE_WHITESPACE, PARSE_OPT_NONEG),
5690 OPT_BIT_F('b', "ignore-space-change", &options->xdl_opts,
5691 N_("ignore changes in amount of whitespace"),
5692 XDF_IGNORE_WHITESPACE_CHANGE, PARSE_OPT_NONEG),
5693 OPT_BIT_F(0, "ignore-space-at-eol", &options->xdl_opts,
5694 N_("ignore changes in whitespace at EOL"),
5695 XDF_IGNORE_WHITESPACE_AT_EOL, PARSE_OPT_NONEG),
5696 OPT_BIT_F(0, "ignore-cr-at-eol", &options->xdl_opts,
5697 N_("ignore carrier-return at the end of line"),
5698 XDF_IGNORE_CR_AT_EOL, PARSE_OPT_NONEG),
5699 OPT_BIT_F(0, "ignore-blank-lines", &options->xdl_opts,
5700 N_("ignore changes whose lines are all blank"),
5701 XDF_IGNORE_BLANK_LINES, PARSE_OPT_NONEG),
296d4a94
MK
5702 OPT_CALLBACK_F('I', "ignore-matching-lines", options, N_("<regex>"),
5703 N_("ignore changes whose all lines match <regex>"),
5704 0, diff_opt_ignore_regex),
06f77518
NTND
5705 OPT_BIT(0, "indent-heuristic", &options->xdl_opts,
5706 N_("heuristic to shift diff hunk boundaries for easy reading"),
5707 XDF_INDENT_HEURISTIC),
31fd640e
NTND
5708 OPT_CALLBACK_F(0, "patience", options, NULL,
5709 N_("generate diff using the \"patience diff\" algorithm"),
5710 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5711 diff_opt_patience),
11e95e16
JC
5712 OPT_CALLBACK_F(0, "histogram", options, NULL,
5713 N_("generate diff using the \"histogram diff\" algorithm"),
5714 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5715 diff_opt_diff_algorithm_no_arg),
10f35b1c
NTND
5716 OPT_CALLBACK_F(0, "diff-algorithm", options, N_("<algorithm>"),
5717 N_("choose a diff algorithm"),
5718 PARSE_OPT_NONEG, diff_opt_diff_algorithm),
df84a436
NTND
5719 OPT_CALLBACK_F(0, "anchored", options, N_("<text>"),
5720 N_("generate diff using the \"anchored diff\" algorithm"),
5721 PARSE_OPT_NONEG, diff_opt_anchored),
e9fb39b6
NTND
5722 OPT_CALLBACK_F(0, "word-diff", options, N_("<mode>"),
5723 N_("show word diff, using <mode> to delimit changed words"),
5724 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_word_diff),
797df119
NTND
5725 OPT_CALLBACK_F(0, "word-diff-regex", options, N_("<regex>"),
5726 N_("use <regex> to decide what a word is"),
5727 PARSE_OPT_NONEG, diff_opt_word_diff_regex),
212db69d
NTND
5728 OPT_CALLBACK_F(0, "color-words", options, N_("<regex>"),
5729 N_("equivalent to --word-diff=color --word-diff-regex=<regex>"),
5730 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_color_words),
59311a98 5731 OPT_CALLBACK_F(0, "color-moved", options, N_("<mode>"),
8bcd8f4c 5732 N_("moved lines of code are colored differently"),
59311a98 5733 PARSE_OPT_OPTARG, diff_opt_color_moved),
8ce2020f
NTND
5734 OPT_CALLBACK_F(0, "color-moved-ws", options, N_("<mode>"),
5735 N_("how white spaces are ignored in --color-moved"),
bb987290 5736 0, diff_opt_color_moved_ws),
2e75f922 5737
8bcd8f4c 5738 OPT_GROUP(N_("Other diff options")),
0b1c5b59
NTND
5739 OPT_CALLBACK_F(0, "relative", options, N_("<prefix>"),
5740 N_("when run from subdir, exclude changes outside and show relative paths"),
c28ded83 5741 PARSE_OPT_OPTARG,
0b1c5b59 5742 diff_opt_relative),
c37d4c0a
NTND
5743 OPT_BOOL('a', "text", &options->flags.text,
5744 N_("treat all files as text")),
4f99f299
NTND
5745 OPT_BOOL('R', NULL, &options->flags.reverse_diff,
5746 N_("swap two inputs, reverse the diff")),
1086ea0c
NTND
5747 OPT_BOOL(0, "exit-code", &options->flags.exit_with_status,
5748 N_("exit with 1 if there were differences, 0 otherwise")),
9bbaf1ce
NTND
5749 OPT_BOOL(0, "quiet", &options->flags.quick,
5750 N_("disable all output of the program")),
0cda1003
NTND
5751 OPT_BOOL(0, "ext-diff", &options->flags.allow_external,
5752 N_("allow an external diff helper to be executed")),
8ab76977
NTND
5753 OPT_CALLBACK_F(0, "textconv", options, NULL,
5754 N_("run external text conversion filters when comparing binary files"),
5755 PARSE_OPT_NOARG, diff_opt_textconv),
b680ee14
NTND
5756 OPT_CALLBACK_F(0, "ignore-submodules", options, N_("<when>"),
5757 N_("ignore changes to submodules in the diff generation"),
5758 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5759 diff_opt_ignore_submodules),
125dcea9
NTND
5760 OPT_CALLBACK_F(0, "submodule", options, N_("<format>"),
5761 N_("specify how differences in submodules are shown"),
5762 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5763 diff_opt_submodule),
96860e48
NTND
5764 OPT_SET_INT_F(0, "ita-invisible-in-index", &options->ita_invisible_in_index,
5765 N_("hide 'git add -N' entries from the index"),
5766 1, PARSE_OPT_NONEG),
5767 OPT_SET_INT_F(0, "ita-visible-in-index", &options->ita_invisible_in_index,
5768 N_("treat 'git add -N' entries as real in the index"),
5769 0, PARSE_OPT_NONEG),
a41cfb32
NTND
5770 OPT_CALLBACK_F('S', NULL, options, N_("<string>"),
5771 N_("look for differences that change the number of occurrences of the specified string"),
5772 0, diff_opt_pickaxe_string),
5773 OPT_CALLBACK_F('G', NULL, options, N_("<regex>"),
5774 N_("look for differences that change the number of occurrences of the specified regex"),
5775 0, diff_opt_pickaxe_regex),
85f8e889
NTND
5776 OPT_BIT_F(0, "pickaxe-all", &options->pickaxe_opts,
5777 N_("show all changes in the changeset with -S or -G"),
5778 DIFF_PICKAXE_ALL, PARSE_OPT_NONEG),
5779 OPT_BIT_F(0, "pickaxe-regex", &options->pickaxe_opts,
5780 N_("treat <string> in -S as extended POSIX regular expression"),
5781 DIFF_PICKAXE_REGEX, PARSE_OPT_NONEG),
f731814b
NTND
5782 OPT_FILENAME('O', NULL, &options->orderfile,
5783 N_("control the order in which files appear in the output")),
1eb4136a
JH
5784 OPT_CALLBACK_F(0, "rotate-to", options, N_("<path>"),
5785 N_("show the change in the specified path first"),
5786 PARSE_OPT_NONEG, diff_opt_rotate_to),
5787 OPT_CALLBACK_F(0, "skip-to", options, N_("<path>"),
5788 N_("skip the output to the specified path"),
5789 PARSE_OPT_NONEG, diff_opt_rotate_to),
a75f28cb
NTND
5790 OPT_CALLBACK_F(0, "find-object", options, N_("<object-id>"),
5791 N_("look for differences that change the number of occurrences of the specified object"),
5792 PARSE_OPT_NONEG, diff_opt_find_object),
d2d3f273
NTND
5793 OPT_CALLBACK_F(0, "diff-filter", options, N_("[(A|C|D|M|R|T|U|X|B)...[*]]"),
5794 N_("select files by diff type"),
5795 PARSE_OPT_NONEG, diff_opt_diff_filter),
af2f3680 5796 { OPTION_CALLBACK, 0, "output", options, N_("<file>"),
9e1f22c8 5797 N_("output to a specific file"),
af2f3680
NTND
5798 PARSE_OPT_NONEG, NULL, 0, diff_opt_output },
5799
4a288478
NTND
5800 OPT_END()
5801 };
5802
189e97bc 5803 return parse_options_concat(opts, parseopts);
4a288478
NTND
5804}
5805
a97262c6
NTND
5806int diff_opt_parse(struct diff_options *options,
5807 const char **av, int ac, const char *prefix)
6973dcae 5808{
6c6048fa
RS
5809 struct option no_options[] = { OPT_END() };
5810 struct option *parseopts = add_diff_options(no_options, options);
5811
a97262c6
NTND
5812 if (!prefix)
5813 prefix = "";
5814
6c6048fa 5815 ac = parse_options(ac, av, prefix, parseopts, NULL,
4a288478 5816 PARSE_OPT_KEEP_DASHDASH |
99d86d60 5817 PARSE_OPT_KEEP_UNKNOWN_OPT |
4a288478
NTND
5818 PARSE_OPT_NO_INTERNAL_HELP |
5819 PARSE_OPT_ONE_SHOT |
5820 PARSE_OPT_STOP_AT_NON_OPTION);
6c6048fa 5821 free(parseopts);
4a288478 5822
8ce2020f 5823 return ac;
6973dcae
JH
5824}
5825
10ae7526 5826int parse_rename_score(const char **cp_p)
6973dcae
JH
5827{
5828 unsigned long num, scale;
5829 int ch, dot;
5830 const char *cp = *cp_p;
5831
5832 num = 0;
5833 scale = 1;
5834 dot = 0;
eeefa7c9 5835 for (;;) {
6973dcae
JH
5836 ch = *cp;
5837 if ( !dot && ch == '.' ) {
5838 scale = 1;
5839 dot = 1;
5840 } else if ( ch == '%' ) {
5841 scale = dot ? scale*100 : 100;
5842 cp++; /* % is always at the end */
5843 break;
5844 } else if ( ch >= '0' && ch <= '9' ) {
5845 if ( scale < 100000 ) {
5846 scale *= 10;
5847 num = (num*10) + (ch-'0');
5848 }
5849 } else {
5850 break;
5851 }
5852 cp++;
5853 }
5854 *cp_p = cp;
5855
5856 /* user says num divided by scale and we say internally that
5857 * is MAX_SCORE * num / scale.
5858 */
dc49cd76 5859 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
6973dcae
JH
5860}
5861
6973dcae
JH
5862struct diff_queue_struct diff_queued_diff;
5863
5864void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
5865{
4c960a43 5866 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
6973dcae
JH
5867 queue->queue[queue->nr++] = dp;
5868}
5869
5870struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
5871 struct diff_filespec *one,
5872 struct diff_filespec *two)
5873{
ef677686 5874 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
6973dcae
JH
5875 dp->one = one;
5876 dp->two = two;
6973dcae
JH
5877 if (queue)
5878 diff_q(queue, dp);
5879 return dp;
5880}
5881
5882void diff_free_filepair(struct diff_filepair *p)
5883{
9fb88419
LT
5884 free_filespec(p->one);
5885 free_filespec(p->two);
6973dcae
JH
5886 free(p);
5887}
5888
04ae0006
SG
5889void diff_free_queue(struct diff_queue_struct *q)
5890{
5891 for (int i = 0; i < q->nr; i++)
5892 diff_free_filepair(q->queue[i]);
5893 free(q->queue);
5894}
5895
d6cece51 5896const char *diff_aligned_abbrev(const struct object_id *oid, int len)
6973dcae
JH
5897{
5898 int abblen;
5899 const char *abbrev;
6973dcae 5900
7cb6ac1e 5901 /* Do we want all 40 hex characters? */
02afca1e 5902 if (len == the_hash_algo->hexsz)
d6cece51
JK
5903 return oid_to_hex(oid);
5904
7cb6ac1e 5905 /* An abbreviated value is fine, possibly followed by an ellipsis. */
4f03666a 5906 abbrev = diff_abbrev_oid(oid, len);
7cb6ac1e
AR
5907
5908 if (!print_sha1_ellipsis())
5909 return abbrev;
5910
6973dcae 5911 abblen = strlen(abbrev);
d709f1fb
JH
5912
5913 /*
7cb6ac1e 5914 * In well-behaved cases, where the abbreviated result is the
d709f1fb
JH
5915 * same as the requested length, append three dots after the
5916 * abbreviation (hence the whole logic is limited to the case
5917 * where abblen < 37); when the actual abbreviated result is a
5918 * bit longer than the requested length, we reduce the number
5919 * of dots so that they match the well-behaved ones. However,
5920 * if the actual abbreviation is longer than the requested
5921 * length by more than three, we give up on aligning, and add
5922 * three dots anyway, to indicate that the output is not the
5923 * full object name. Yes, this may be suboptimal, but this
5924 * appears only in "diff --raw --abbrev" output and it is not
5925 * worth the effort to change it now. Note that this would
5926 * likely to work fine when the automatic sizing of default
5927 * abbreviation length is used--we would be fed -1 in "len" in
5928 * that case, and will end up always appending three-dots, but
5929 * the automatic sizing is supposed to give abblen that ensures
5930 * uniqueness across all objects (statistically speaking).
5931 */
02afca1e 5932 if (abblen < the_hash_algo->hexsz - 3) {
dc01505f 5933 static char hex[GIT_MAX_HEXSZ + 1];
6973dcae 5934 if (len < abblen && abblen <= len + 2)
5096d490 5935 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
6973dcae 5936 else
5096d490 5937 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
6973dcae
JH
5938 return hex;
5939 }
d6cece51
JK
5940
5941 return oid_to_hex(oid);
6973dcae
JH
5942}
5943
663af342 5944static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
6973dcae 5945{
663af342
PH
5946 int line_termination = opt->line_termination;
5947 int inter_name_termination = line_termination ? '\t' : '\0';
6973dcae 5948
30997bb8 5949 fprintf(opt->file, "%s", diff_line_prefix(opt));
663af342 5950 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
c0c77734 5951 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
d6cece51 5952 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
a0d12c44 5953 fprintf(opt->file, "%s ",
d6cece51 5954 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
6973dcae 5955 }
663af342 5956 if (p->score) {
c0c77734
DB
5957 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
5958 inter_name_termination);
663af342 5959 } else {
c0c77734 5960 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
6973dcae 5961 }
6973dcae 5962
cd676a51
JH
5963 if (p->status == DIFF_STATUS_COPIED ||
5964 p->status == DIFF_STATUS_RENAMED) {
5965 const char *name_a, *name_b;
5966 name_a = p->one->path;
5967 name_b = p->two->path;
5968 strip_prefix(opt->prefix_length, &name_a, &name_b);
c0c77734
DB
5969 write_name_quoted(name_a, opt->file, inter_name_termination);
5970 write_name_quoted(name_b, opt->file, line_termination);
663af342 5971 } else {
cd676a51
JH
5972 const char *name_a, *name_b;
5973 name_a = p->one->mode ? p->one->path : p->two->path;
5974 name_b = NULL;
5975 strip_prefix(opt->prefix_length, &name_a, &name_b);
c0c77734 5976 write_name_quoted(name_a, opt->file, line_termination);
663af342 5977 }
6973dcae
JH
5978}
5979
5980int diff_unmodified_pair(struct diff_filepair *p)
5981{
5982 /* This function is written stricter than necessary to support
5983 * the currently implemented transformers, but the idea is to
5984 * let transformers to produce diff_filepairs any way they want,
5985 * and filter and clean them up here before producing the output.
5986 */
663af342 5987 struct diff_filespec *one = p->one, *two = p->two;
6973dcae
JH
5988
5989 if (DIFF_PAIR_UNMERGED(p))
5990 return 0; /* unmerged is interesting */
5991
6973dcae
JH
5992 /* deletion, addition, mode or type change
5993 * and rename are all interesting.
5994 */
5995 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
5996 DIFF_PAIR_MODE_CHANGED(p) ||
5997 strcmp(one->path, two->path))
5998 return 0;
5999
6000 /* both are valid and point at the same path. that is, we are
6001 * dealing with a change.
6002 */
41c9560e 6003 if (one->oid_valid && two->oid_valid &&
4a7e27e9 6004 oideq(&one->oid, &two->oid) &&
85adbf2f 6005 !one->dirty_submodule && !two->dirty_submodule)
6973dcae 6006 return 1; /* no change */
41c9560e 6007 if (!one->oid_valid && !two->oid_valid)
6973dcae
JH
6008 return 1; /* both look at the same file on the filesystem. */
6009 return 0;
6010}
6011
6012static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
6013{
95433eee
EN
6014 int include_conflict_headers =
6015 (additional_headers(o, p->one->path) &&
71a146dc 6016 !o->pickaxe_opts &&
95433eee
EN
6017 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
6018
6019 /*
6020 * Check if we can return early without showing a diff. Note that
6021 * diff_filepair only stores {oid, path, mode, is_valid}
6022 * information for each path, and thus diff_unmodified_pair() only
6023 * considers those bits of info. However, we do not want pairs
6024 * created by create_filepairs_for_header_only_notifications()
6025 * (which always look like unmodified pairs) to be ignored, so
6026 * return early if both p is unmodified AND we don't want to
6027 * include_conflict_headers.
6028 */
6029 if (diff_unmodified_pair(p) && !include_conflict_headers)
6973dcae
JH
6030 return;
6031
95433eee 6032 /* Actually, we can also return early to avoid showing tree diffs */
6973dcae
JH
6033 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6034 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
95433eee 6035 return;
6973dcae
JH
6036
6037 run_diff(p, o);
6038}
6039
6040static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
6041 struct diffstat_t *diffstat)
6042{
6043 if (diff_unmodified_pair(p))
6044 return;
6045
6046 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6047 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
c3fced64 6048 return; /* no useful stat for tree diffs */
6973dcae
JH
6049
6050 run_diffstat(p, o, diffstat);
6051}
6052
88246898
JS
6053static void diff_flush_checkdiff(struct diff_filepair *p,
6054 struct diff_options *o)
6055{
6056 if (diff_unmodified_pair(p))
6057 return;
6058
6059 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6060 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
c3fced64 6061 return; /* nothing to check in tree diffs */
88246898
JS
6062
6063 run_checkdiff(p, o);
6064}
6065
95433eee 6066int diff_queue_is_empty(struct diff_options *o)
6973dcae
JH
6067{
6068 struct diff_queue_struct *q = &diff_queued_diff;
6069 int i;
95433eee
EN
6070 int include_conflict_headers =
6071 (o->additional_path_headers &&
67360b75 6072 strmap_get_size(o->additional_path_headers) &&
71a146dc 6073 !o->pickaxe_opts &&
95433eee
EN
6074 (!o->filter || filter_bit_tst(DIFF_STATUS_UNMERGED, o)));
6075
6076 if (include_conflict_headers)
6077 return 0;
6078
6973dcae
JH
6079 for (i = 0; i < q->nr; i++)
6080 if (!diff_unmodified_pair(q->queue[i]))
6081 return 0;
6082 return 1;
6083}
6084
6085#if DIFF_DEBUG
6086void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
6087{
6088 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
6089 x, one ? one : "",
6090 s->path,
6091 DIFF_FILE_VALID(s) ? "valid" : "invalid",
6092 s->mode,
41c9560e 6093 s->oid_valid ? oid_to_hex(&s->oid) : "");
428d52a5 6094 fprintf(stderr, "queue[%d] %s size %lu\n",
6973dcae 6095 x, one ? one : "",
428d52a5 6096 s->size);
6973dcae
JH
6097}
6098
6099void diff_debug_filepair(const struct diff_filepair *p, int i)
6100{
6101 diff_debug_filespec(p->one, i, "one");
6102 diff_debug_filespec(p->two, i, "two");
64479711 6103 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
6973dcae 6104 p->score, p->status ? p->status : '?',
64479711 6105 p->one->rename_used, p->broken_pair);
6973dcae
JH
6106}
6107
6108void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
6109{
6110 int i;
6111 if (msg)
6112 fprintf(stderr, "%s\n", msg);
6113 fprintf(stderr, "q->nr = %d\n", q->nr);
6114 for (i = 0; i < q->nr; i++) {
6115 struct diff_filepair *p = q->queue[i];
6116 diff_debug_filepair(p, i);
6117 }
6118}
6119#endif
6120
6121static void diff_resolve_rename_copy(void)
6122{
64479711
LT
6123 int i;
6124 struct diff_filepair *p;
6973dcae
JH
6125 struct diff_queue_struct *q = &diff_queued_diff;
6126
6127 diff_debug_queue("resolve-rename-copy", q);
6128
6129 for (i = 0; i < q->nr; i++) {
6130 p = q->queue[i];
6131 p->status = 0; /* undecided */
6132 if (DIFF_PAIR_UNMERGED(p))
6133 p->status = DIFF_STATUS_UNMERGED;
6134 else if (!DIFF_FILE_VALID(p->one))
6135 p->status = DIFF_STATUS_ADDED;
6136 else if (!DIFF_FILE_VALID(p->two))
6137 p->status = DIFF_STATUS_DELETED;
6138 else if (DIFF_PAIR_TYPE_CHANGED(p))
6139 p->status = DIFF_STATUS_TYPE_CHANGED;
6140
6141 /* from this point on, we are dealing with a pair
6142 * whose both sides are valid and of the same type, i.e.
6143 * either in-place edit or rename/copy edit.
6144 */
6145 else if (DIFF_PAIR_RENAME(p)) {
64479711
LT
6146 /*
6147 * A rename might have re-connected a broken
6148 * pair up, causing the pathnames to be the
6149 * same again. If so, that's not a rename at
6150 * all, just a modification..
6151 *
6152 * Otherwise, see if this source was used for
6153 * multiple renames, in which case we decrement
6154 * the count, and call it a copy.
6973dcae 6155 */
64479711
LT
6156 if (!strcmp(p->one->path, p->two->path))
6157 p->status = DIFF_STATUS_MODIFIED;
6158 else if (--p->one->rename_used > 0)
6973dcae 6159 p->status = DIFF_STATUS_COPIED;
64479711 6160 else
6973dcae
JH
6161 p->status = DIFF_STATUS_RENAMED;
6162 }
9001dc2a 6163 else if (!oideq(&p->one->oid, &p->two->oid) ||
d516c2d1 6164 p->one->mode != p->two->mode ||
85adbf2f
JL
6165 p->one->dirty_submodule ||
6166 p->two->dirty_submodule ||
a0d12c44 6167 is_null_oid(&p->one->oid))
6973dcae
JH
6168 p->status = DIFF_STATUS_MODIFIED;
6169 else {
6170 /* This is a "no-change" entry and should not
6171 * happen anymore, but prepare for broken callers.
6172 */
6173 error("feeding unmodified %s to diffcore",
6174 p->one->path);
6175 p->status = DIFF_STATUS_UNKNOWN;
6176 }
6177 }
6178 diff_debug_queue("resolve-rename-copy done", q);
6179}
6180
c6744349 6181static int check_pair_status(struct diff_filepair *p)
6973dcae 6182{
6973dcae
JH
6183 switch (p->status) {
6184 case DIFF_STATUS_UNKNOWN:
c6744349 6185 return 0;
6973dcae
JH
6186 case 0:
6187 die("internal error in diff-resolve-rename-copy");
6973dcae 6188 default:
c6744349 6189 return 1;
6973dcae
JH
6190 }
6191}
6192
c6744349
TH
6193static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
6194{
6195 int fmt = opt->output_format;
6196
6197 if (fmt & DIFF_FORMAT_CHECKDIFF)
6198 diff_flush_checkdiff(p, opt);
6199 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
6200 diff_flush_raw(p, opt);
cd676a51
JH
6201 else if (fmt & DIFF_FORMAT_NAME) {
6202 const char *name_a, *name_b;
6203 name_a = p->two->path;
6204 name_b = NULL;
6205 strip_prefix(opt->prefix_length, &name_a, &name_b);
f5022b5f 6206 fprintf(opt->file, "%s", diff_line_prefix(opt));
c0c77734 6207 write_name_quoted(name_a, opt->file, opt->line_termination);
cd676a51 6208 }
c6744349
TH
6209}
6210
146fdb0d 6211static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
4bbd261b 6212{
146fdb0d 6213 struct strbuf sb = STRBUF_INIT;
4bbd261b 6214 if (fs->mode)
146fdb0d 6215 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
4bbd261b 6216 else
146fdb0d 6217 strbuf_addf(&sb, " %s ", newdelete);
4bbd261b 6218
146fdb0d
SB
6219 quote_c_style(fs->path, &sb, NULL, 0);
6220 strbuf_addch(&sb, '\n');
6221 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6222 sb.buf, sb.len, 0);
6223 strbuf_release(&sb);
6224}
4bbd261b 6225
146fdb0d
SB
6226static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
6227 int show_name)
4bbd261b
SE
6228{
6229 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
146fdb0d
SB
6230 struct strbuf sb = STRBUF_INIT;
6231 strbuf_addf(&sb, " mode change %06o => %06o",
6232 p->one->mode, p->two->mode);
0d26a64e 6233 if (show_name) {
146fdb0d
SB
6234 strbuf_addch(&sb, ' ');
6235 quote_c_style(p->two->path, &sb, NULL, 0);
0d26a64e 6236 }
58aaced4 6237 strbuf_addch(&sb, '\n');
146fdb0d
SB
6238 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6239 sb.buf, sb.len, 0);
6240 strbuf_release(&sb);
4bbd261b
SE
6241 }
6242}
6243
146fdb0d
SB
6244static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
6245 struct diff_filepair *p)
4bbd261b 6246{
146fdb0d 6247 struct strbuf sb = STRBUF_INIT;
c905cbc4
NTND
6248 struct strbuf names = STRBUF_INIT;
6249
6250 pprint_rename(&names, p->one->path, p->two->path);
146fdb0d 6251 strbuf_addf(&sb, " %s %s (%d%%)\n",
c905cbc4
NTND
6252 renamecopy, names.buf, similarity_index(p));
6253 strbuf_release(&names);
146fdb0d
SB
6254 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6255 sb.buf, sb.len, 0);
6256 show_mode_change(opt, p, 0);
348eda24 6257 strbuf_release(&sb);
4bbd261b
SE
6258}
6259
7be57610 6260static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
4bbd261b
SE
6261{
6262 switch(p->status) {
6263 case DIFF_STATUS_DELETED:
146fdb0d 6264 show_file_mode_name(opt, "delete", p->one);
4bbd261b
SE
6265 break;
6266 case DIFF_STATUS_ADDED:
146fdb0d 6267 show_file_mode_name(opt, "create", p->two);
4bbd261b
SE
6268 break;
6269 case DIFF_STATUS_COPIED:
146fdb0d 6270 show_rename_copy(opt, "copy", p);
4bbd261b
SE
6271 break;
6272 case DIFF_STATUS_RENAMED:
146fdb0d 6273 show_rename_copy(opt, "rename", p);
4bbd261b
SE
6274 break;
6275 default:
6276 if (p->score) {
146fdb0d
SB
6277 struct strbuf sb = STRBUF_INIT;
6278 strbuf_addstr(&sb, " rewrite ");
6279 quote_c_style(p->two->path, &sb, NULL, 0);
6280 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
6281 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
6282 sb.buf, sb.len, 0);
fa842d84 6283 strbuf_release(&sb);
663af342 6284 }
146fdb0d 6285 show_mode_change(opt, p, !p->score);
4bbd261b
SE
6286 break;
6287 }
6288}
6289
fcb3d0ad 6290struct patch_id_t {
36261e42 6291 git_hash_ctx *ctx;
fcb3d0ad
JS
6292 int patchlen;
6293};
6294
6295static int remove_space(char *line, int len)
6296{
6297 int i;
663af342
PH
6298 char *dst = line;
6299 unsigned char c;
fcb3d0ad 6300
663af342
PH
6301 for (i = 0; i < len; i++)
6302 if (!isspace((c = line[i])))
6303 *dst++ = c;
fcb3d0ad 6304
663af342 6305 return dst - line;
fcb3d0ad
JS
6306}
6307
36261e42 6308void flush_one_hunk(struct object_id *result, git_hash_ctx *ctx)
a8f6855f
SB
6309{
6310 unsigned char hash[GIT_MAX_RAWSZ];
6311 unsigned short carry = 0;
6312 int i;
6313
36261e42 6314 the_hash_algo->final_fn(hash, ctx);
6315 the_hash_algo->init_fn(ctx);
a8f6855f 6316 /* 20-byte sum, with carry */
36261e42 6317 for (i = 0; i < the_hash_algo->rawsz; ++i) {
a8f6855f
SB
6318 carry += result->hash[i] + hash[i];
6319 result->hash[i] = carry;
6320 carry >>= 8;
6321 }
6322}
6323
a8d5eb6d 6324static int patch_id_consume(void *priv, char *line, unsigned long len)
fcb3d0ad
JS
6325{
6326 struct patch_id_t *data = priv;
6327 int new_len;
6328
82a62015 6329 if (len > 12 && starts_with(line, "\\ "))
a8d5eb6d 6330 return 0;
fcb3d0ad
JS
6331 new_len = remove_space(line, len);
6332
36261e42 6333 the_hash_algo->update_fn(data->ctx, line, new_len);
fcb3d0ad 6334 data->patchlen += new_len;
a8d5eb6d 6335 return 0;
fcb3d0ad
JS
6336}
6337
36261e42 6338static void patch_id_add_string(git_hash_ctx *ctx, const char *str)
977db6b4 6339{
36261e42 6340 the_hash_algo->update_fn(ctx, str, strlen(str));
977db6b4
JK
6341}
6342
36261e42 6343static void patch_id_add_mode(git_hash_ctx *ctx, unsigned mode)
977db6b4
JK
6344{
6345 /* large enough for 2^32 in octal */
6346 char buf[12];
6347 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
36261e42 6348 the_hash_algo->update_fn(ctx, buf, len);
977db6b4
JK
6349}
6350
a8f6855f 6351/* returns 0 upon success, and writes result into oid */
51276c18 6352static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
fcb3d0ad
JS
6353{
6354 struct diff_queue_struct *q = &diff_queued_diff;
6355 int i;
36261e42 6356 git_hash_ctx ctx;
fcb3d0ad 6357 struct patch_id_t data;
fcb3d0ad 6358
36261e42 6359 the_hash_algo->init_fn(&ctx);
fcb3d0ad
JS
6360 memset(&data, 0, sizeof(struct patch_id_t));
6361 data.ctx = &ctx;
a8f6855f 6362 oidclr(oid);
fcb3d0ad
JS
6363
6364 for (i = 0; i < q->nr; i++) {
6365 xpparam_t xpp;
6366 xdemitconf_t xecfg;
fcb3d0ad
JS
6367 mmfile_t mf1, mf2;
6368 struct diff_filepair *p = q->queue[i];
6369 int len1, len2;
6370
9ccd0a88 6371 memset(&xpp, 0, sizeof(xpp));
30b25010 6372 memset(&xecfg, 0, sizeof(xecfg));
fcb3d0ad
JS
6373 if (p->status == 0)
6374 return error("internal diff status error");
6375 if (p->status == DIFF_STATUS_UNKNOWN)
6376 continue;
6377 if (diff_unmodified_pair(p))
6378 continue;
6379 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6380 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6381 continue;
6382 if (DIFF_PAIR_UNMERGED(p))
6383 continue;
6384
58bf2a4c
NTND
6385 diff_fill_oid_info(p->one, options->repo->index);
6386 diff_fill_oid_info(p->two, options->repo->index);
fcb3d0ad 6387
fcb3d0ad
JS
6388 len1 = remove_space(p->one->path, strlen(p->one->path));
6389 len2 = remove_space(p->two->path, strlen(p->two->path));
977db6b4
JK
6390 patch_id_add_string(&ctx, "diff--git");
6391 patch_id_add_string(&ctx, "a/");
36261e42 6392 the_hash_algo->update_fn(&ctx, p->one->path, len1);
977db6b4 6393 patch_id_add_string(&ctx, "b/");
36261e42 6394 the_hash_algo->update_fn(&ctx, p->two->path, len2);
977db6b4
JK
6395
6396 if (p->one->mode == 0) {
6397 patch_id_add_string(&ctx, "newfilemode");
6398 patch_id_add_mode(&ctx, p->two->mode);
977db6b4
JK
6399 } else if (p->two->mode == 0) {
6400 patch_id_add_string(&ctx, "deletedfilemode");
6401 patch_id_add_mode(&ctx, p->one->mode);
93105aba
JZ
6402 } else if (p->one->mode != p->two->mode) {
6403 patch_id_add_string(&ctx, "oldmode");
6404 patch_id_add_mode(&ctx, p->one->mode);
6405 patch_id_add_string(&ctx, "newmode");
6406 patch_id_add_mode(&ctx, p->two->mode);
977db6b4 6407 }
fcb3d0ad 6408
0570be79
JZ
6409 if (diff_header_only) {
6410 /* don't do anything since we're only populating header info */
6411 } else if (diff_filespec_is_binary(options->repo, p->one) ||
b78ea5fc 6412 diff_filespec_is_binary(options->repo, p->two)) {
36261e42 6413 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->one->oid),
6414 the_hash_algo->hexsz);
6415 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->two->oid),
6416 the_hash_algo->hexsz);
0570be79
JZ
6417 } else {
6418 if (p->one->mode == 0) {
6419 patch_id_add_string(&ctx, "---/dev/null");
6420 patch_id_add_string(&ctx, "+++b/");
6421 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6422 } else if (p->two->mode == 0) {
6423 patch_id_add_string(&ctx, "---a/");
6424 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6425 patch_id_add_string(&ctx, "+++/dev/null");
6426 } else {
6427 patch_id_add_string(&ctx, "---a/");
6428 the_hash_algo->update_fn(&ctx, p->one->path, len1);
6429 patch_id_add_string(&ctx, "+++b/");
6430 the_hash_algo->update_fn(&ctx, p->two->path, len2);
6431 }
a8f6855f 6432
0570be79
JZ
6433 if (fill_mmfile(options->repo, &mf1, p->one) < 0 ||
6434 fill_mmfile(options->repo, &mf2, p->two) < 0)
6435 return error("unable to read files to diff");
6436 xpp.flags = 0;
6437 xecfg.ctxlen = 3;
6438 xecfg.flags = XDL_EMIT_NO_HUNK_HDR;
6439 if (xdi_diff_outf(&mf1, &mf2, NULL,
6440 patch_id_consume, &data, &xpp, &xecfg))
6441 return error("unable to generate patch-id diff for %s",
6442 p->one->path);
6443 }
51276c18 6444 flush_one_hunk(oid, &ctx);
fcb3d0ad
JS
6445 }
6446
fcb3d0ad
JS
6447 return 0;
6448}
6449
51276c18 6450int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
fcb3d0ad
JS
6451{
6452 struct diff_queue_struct *q = &diff_queued_diff;
51276c18 6453 int result = diff_get_patch_id(options, oid, diff_header_only);
fcb3d0ad 6454
586d8b50 6455 diff_free_queue(q);
9ca5df90 6456 DIFF_QUEUE_CLEAR(q);
fcb3d0ad
JS
6457
6458 return result;
6459}
6460
946c3784 6461static int is_summary_empty(const struct diff_queue_struct *q)
6973dcae 6462{
6973dcae 6463 int i;
6973dcae 6464
946c3784
TH
6465 for (i = 0; i < q->nr; i++) {
6466 const struct diff_filepair *p = q->queue[i];
6467
6468 switch (p->status) {
6469 case DIFF_STATUS_DELETED:
6470 case DIFF_STATUS_ADDED:
6471 case DIFF_STATUS_COPIED:
6472 case DIFF_STATUS_RENAMED:
6473 return 0;
6474 default:
6475 if (p->score)
6476 return 0;
6477 if (p->one->mode && p->two->mode &&
6478 p->one->mode != p->two->mode)
6479 return 0;
6480 break;
6481 }
6973dcae 6482 }
946c3784
TH
6483 return 1;
6484}
6485
f31027c9 6486static const char rename_limit_warning[] =
05d2c61c 6487N_("exhaustive rename detection was skipped due to too many files.");
f31027c9
JH
6488
6489static const char degrade_cc_to_c_warning[] =
db424979 6490N_("only found copies from modified paths due to too many files.");
f31027c9
JH
6491
6492static const char rename_limit_advice[] =
db424979
VA
6493N_("you may want to set your %s variable to at least "
6494 "%d and retry the command.");
f31027c9
JH
6495
6496void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
6497{
4e056c98 6498 fflush(stdout);
f31027c9 6499 if (degraded_cc)
db424979 6500 warning(_(degrade_cc_to_c_warning));
f31027c9 6501 else if (needed)
db424979 6502 warning(_(rename_limit_warning));
f31027c9
JH
6503 else
6504 return;
9f7e4bfa 6505 if (0 < needed)
db424979 6506 warning(_(rename_limit_advice), varname, needed);
f31027c9
JH
6507}
6508
95433eee
EN
6509static void create_filepairs_for_header_only_notifications(struct diff_options *o)
6510{
6511 struct strset present;
6512 struct diff_queue_struct *q = &diff_queued_diff;
6513 struct hashmap_iter iter;
6514 struct strmap_entry *e;
6515 int i;
6516
6517 strset_init_with_options(&present, /*pool*/ NULL, /*strdup*/ 0);
6518
6519 /*
6520 * Find out which paths exist in diff_queued_diff, preferring
6521 * one->path for any pair that has multiple paths.
6522 */
6523 for (i = 0; i < q->nr; i++) {
6524 struct diff_filepair *p = q->queue[i];
6525 char *path = p->one->path ? p->one->path : p->two->path;
6526
6527 if (strmap_contains(o->additional_path_headers, path))
6528 strset_add(&present, path);
6529 }
6530
6531 /*
6532 * Loop over paths in additional_path_headers; for each NOT already
6533 * in diff_queued_diff, create a synthetic filepair and insert that
6534 * into diff_queued_diff.
6535 */
6536 strmap_for_each_entry(o->additional_path_headers, &iter, e) {
6537 if (!strset_contains(&present, e->key)) {
6538 struct diff_filespec *one, *two;
6539 struct diff_filepair *p;
6540
6541 one = alloc_filespec(e->key);
6542 two = alloc_filespec(e->key);
6543 fill_filespec(one, null_oid(), 0, 0);
6544 fill_filespec(two, null_oid(), 0, 0);
6545 p = diff_queue(q, one, two);
6546 p->status = DIFF_STATUS_MODIFIED;
6547 }
6548 }
6549
6550 /* Re-sort the filepairs */
6551 diffcore_fix_diff_index();
6552
6553 /* Cleanup */
6554 strset_clear(&present);
6555}
6556
ec331506
SB
6557static void diff_flush_patch_all_file_pairs(struct diff_options *o)
6558{
6559 int i;
e6e045f8 6560 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
ec331506 6561 struct diff_queue_struct *q = &diff_queued_diff;
091f8e28
SB
6562
6563 if (WSEH_NEW & WS_RULE_MASK)
033abf97 6564 BUG("WS rules bit mask overlaps with diff symbol flags");
091f8e28 6565
2e2d5ac1
SB
6566 if (o->color_moved)
6567 o->emitted_symbols = &esm;
e6e045f8 6568
95433eee
EN
6569 if (o->additional_path_headers)
6570 create_filepairs_for_header_only_notifications(o);
6571
ec331506
SB
6572 for (i = 0; i < q->nr; i++) {
6573 struct diff_filepair *p = q->queue[i];
6574 if (check_pair_status(p))
6575 diff_flush_patch(p, o);
6576 }
e6e045f8
SB
6577
6578 if (o->emitted_symbols) {
2e2d5ac1 6579 if (o->color_moved) {
72962e8b
PW
6580 struct mem_pool entry_pool;
6581 struct moved_entry_list *entry_list;
2e2d5ac1 6582
72962e8b
PW
6583 mem_pool_init(&entry_pool, 1024 * 1024);
6584 entry_list = add_lines_to_move_detection(o,
6585 &entry_pool);
6586 mark_color_as_moved(o, entry_list);
86b452e2
SB
6587 if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
6588 dim_moved_lines(o);
2e2d5ac1 6589
72962e8b
PW
6590 mem_pool_discard(&entry_pool, 0);
6591 free(entry_list);
2e2d5ac1
SB
6592 }
6593
e6e045f8
SB
6594 for (i = 0; i < esm.nr; i++)
6595 emit_diff_symbol_from_struct(o, &esm.buf[i]);
6596
6597 for (i = 0; i < esm.nr; i++)
6598 free((void *)esm.buf[i].line);
48edf3a0
JK
6599 esm.nr = 0;
6600
6601 o->emitted_symbols = NULL;
e6e045f8 6602 }
ec331506
SB
6603}
6604
e900d494
ÆAB
6605static void diff_free_file(struct diff_options *options)
6606{
6607 if (options->close_file)
6608 fclose(options->file);
6609}
6610
c45dc9cf
ÆAB
6611static void diff_free_ignore_regex(struct diff_options *options)
6612{
6613 int i;
6614
6615 for (i = 0; i < options->ignore_regex_nr; i++) {
6616 regfree(options->ignore_regex[i]);
6617 free(options->ignore_regex[i]);
6618 }
6619 free(options->ignore_regex);
6620}
6621
e900d494
ÆAB
6622void diff_free(struct diff_options *options)
6623{
6624 if (options->no_free)
6625 return;
6626
6627 diff_free_file(options);
c45dc9cf 6628 diff_free_ignore_regex(options);
244c2724 6629 clear_pathspec(&options->pathspec);
e900d494
ÆAB
6630}
6631
6973dcae
JH
6632void diff_flush(struct diff_options *options)
6633{
6634 struct diff_queue_struct *q = &diff_queued_diff;
c6744349 6635 int i, output_format = options->output_format;
946c3784 6636 int separator = 0;
1c57a627 6637 int dirstat_by_line = 0;
6973dcae 6638
c6744349
TH
6639 /*
6640 * Order: raw, stat, summary, patch
6641 * or: name/name-status/checkdiff (other bits clear)
6642 */
95433eee 6643 if (!q->nr && !options->additional_path_headers)
946c3784 6644 goto free_queue;
6973dcae 6645
c6744349
TH
6646 if (output_format & (DIFF_FORMAT_RAW |
6647 DIFF_FORMAT_NAME |
6648 DIFF_FORMAT_NAME_STATUS |
6649 DIFF_FORMAT_CHECKDIFF)) {
6973dcae
JH
6650 for (i = 0; i < q->nr; i++) {
6651 struct diff_filepair *p = q->queue[i];
c6744349
TH
6652 if (check_pair_status(p))
6653 flush_one_pair(p, options);
6973dcae 6654 }
946c3784 6655 separator++;
6973dcae 6656 }
c6744349 6657
0d1e0e78 6658 if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
1c57a627
JH
6659 dirstat_by_line = 1;
6660
6661 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
6662 dirstat_by_line) {
5e2b0636 6663 struct diffstat_t diffstat;
c6744349 6664
e4cb659e 6665 compute_diffstat(options, &diffstat, q);
74e2abe5
JH
6666 if (output_format & DIFF_FORMAT_NUMSTAT)
6667 show_numstat(&diffstat, options);
6668 if (output_format & DIFF_FORMAT_DIFFSTAT)
6669 show_stats(&diffstat, options);
f604652e 6670 if (output_format & DIFF_FORMAT_SHORTSTAT)
c0c77734 6671 show_shortstats(&diffstat, options);
ab27389a 6672 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
1c57a627 6673 show_dirstat_by_line(&diffstat, options);
f604652e 6674 free_diffstat_info(&diffstat);
3969cf7d 6675 separator++;
6973dcae 6676 }
1c57a627 6677 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
c04a7155 6678 show_dirstat(options);
6973dcae 6679
946c3784 6680 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
7be57610
BY
6681 for (i = 0; i < q->nr; i++) {
6682 diff_summary(options, q->queue[i]);
6683 }
3969cf7d 6684 separator++;
6973dcae
JH
6685 }
6686
6977c250 6687 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
0d1e0e78
BW
6688 options->flags.exit_with_status &&
6689 options->flags.diff_from_contents) {
6977c250
LA
6690 /*
6691 * run diff_flush_patch for the exit status. setting
749f763d 6692 * options->file to /dev/null should be safe, because we
6977c250
LA
6693 * aren't supposed to produce any output anyway.
6694 */
e900d494 6695 diff_free_file(options);
23a9e071 6696 options->file = xfopen("/dev/null", "w");
6977c250 6697 options->close_file = 1;
2e2d5ac1 6698 options->color_moved = 0;
6977c250
LA
6699 for (i = 0; i < q->nr; i++) {
6700 struct diff_filepair *p = q->queue[i];
6701 if (check_pair_status(p))
6702 diff_flush_patch(p, options);
6703 if (options->found_changes)
6704 break;
6705 }
6706 }
6707
c6744349 6708 if (output_format & DIFF_FORMAT_PATCH) {
946c3784 6709 if (separator) {
091f8e28 6710 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
30b7e1e7 6711 if (options->stat_sep)
946c3784 6712 /* attach patch instead of inline */
30b7e1e7
SB
6713 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
6714 NULL, 0, 0);
c6744349
TH
6715 }
6716
ec331506 6717 diff_flush_patch_all_file_pairs(options);
4bbd261b
SE
6718 }
6719
04245581
JK
6720 if (output_format & DIFF_FORMAT_CALLBACK)
6721 options->format_callback(q, options, options->format_callback_data);
6722
946c3784 6723free_queue:
586d8b50 6724 diff_free_queue(q);
9ca5df90 6725 DIFF_QUEUE_CLEAR(q);
e900d494 6726 diff_free(options);
f245194f
JH
6727
6728 /*
97bf2a08 6729 * Report the content-level differences with HAS_CHANGES;
f245194f
JH
6730 * diff_addremove/diff_change does not set the bit when
6731 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
6732 */
0d1e0e78 6733 if (options->flags.diff_from_contents) {
f245194f 6734 if (options->found_changes)
0d1e0e78 6735 options->flags.has_changes = 1;
f245194f 6736 else
0d1e0e78 6737 options->flags.has_changes = 0;
f245194f 6738 }
6973dcae
JH
6739}
6740
08578fa1
JH
6741static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
6742{
6743 return (((p->status == DIFF_STATUS_MODIFIED) &&
6744 ((p->score &&
1ecc1cbd 6745 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
08578fa1 6746 (!p->score &&
1ecc1cbd 6747 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
08578fa1 6748 ((p->status != DIFF_STATUS_MODIFIED) &&
1ecc1cbd 6749 filter_bit_tst(p->status, options)));
08578fa1
JH
6750}
6751
949226fe 6752static void diffcore_apply_filter(struct diff_options *options)
6973dcae
JH
6753{
6754 int i;
6755 struct diff_queue_struct *q = &diff_queued_diff;
6756 struct diff_queue_struct outq;
949226fe 6757
9ca5df90 6758 DIFF_QUEUE_CLEAR(&outq);
6973dcae 6759
1ecc1cbd 6760 if (!options->filter)
6973dcae
JH
6761 return;
6762
1ecc1cbd 6763 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
6973dcae
JH
6764 int found;
6765 for (i = found = 0; !found && i < q->nr; i++) {
08578fa1 6766 if (match_filter(options, q->queue[i]))
6973dcae
JH
6767 found++;
6768 }
6769 if (found)
6770 return;
6771
6772 /* otherwise we will clear the whole queue
6773 * by copying the empty outq at the end of this
6774 * function, but first clear the current entries
6775 * in the queue.
6776 */
6777 for (i = 0; i < q->nr; i++)
6778 diff_free_filepair(q->queue[i]);
6779 }
6780 else {
6781 /* Only the matching ones */
6782 for (i = 0; i < q->nr; i++) {
6783 struct diff_filepair *p = q->queue[i];
08578fa1 6784 if (match_filter(options, p))
6973dcae
JH
6785 diff_q(&outq, p);
6786 else
6787 diff_free_filepair(p);
6788 }
6789 }
6790 free(q->queue);
6791 *q = outq;
6792}
6793
5701115a 6794/* Check whether two filespecs with the same mode and size are identical */
b78ea5fc
NTND
6795static int diff_filespec_is_identical(struct repository *r,
6796 struct diff_filespec *one,
5701115a
SV
6797 struct diff_filespec *two)
6798{
2b459b48
JH
6799 if (S_ISGITLINK(one->mode))
6800 return 0;
1c37e86a 6801 if (diff_populate_filespec(r, one, NULL))
5701115a 6802 return 0;
1c37e86a 6803 if (diff_populate_filespec(r, two, NULL))
5701115a
SV
6804 return 0;
6805 return !memcmp(one->data, two->data, one->size);
6806}
6807
b78ea5fc
NTND
6808static int diff_filespec_check_stat_unmatch(struct repository *r,
6809 struct diff_filepair *p)
fceb9072 6810{
1c37e86a
JT
6811 struct diff_populate_filespec_options dpf_options = {
6812 .check_size_only = 1,
95acf11a
JT
6813 .missing_object_cb = diff_queued_diff_prefetch,
6814 .missing_object_data = r,
1c37e86a
JT
6815 };
6816
f34b205f
NTND
6817 if (p->done_skip_stat_unmatch)
6818 return p->skip_stat_unmatch_result;
6819
6820 p->done_skip_stat_unmatch = 1;
6821 p->skip_stat_unmatch_result = 0;
fceb9072
NTND
6822 /*
6823 * 1. Entries that come from stat info dirtiness
6824 * always have both sides (iow, not create/delete),
6825 * one side of the object name is unknown, with
6826 * the same mode and size. Keep the ones that
6827 * do not match these criteria. They have real
6828 * differences.
6829 *
6830 * 2. At this point, the file is known to be modified,
6831 * with the same mode and size, and the object
6832 * name of one side is unknown. Need to inspect
6833 * the identical contents.
6834 */
6835 if (!DIFF_FILE_VALID(p->one) || /* (1) */
6836 !DIFF_FILE_VALID(p->two) ||
41c9560e 6837 (p->one->oid_valid && p->two->oid_valid) ||
fceb9072 6838 (p->one->mode != p->two->mode) ||
1c37e86a
JT
6839 diff_populate_filespec(r, p->one, &dpf_options) ||
6840 diff_populate_filespec(r, p->two, &dpf_options) ||
fceb9072 6841 (p->one->size != p->two->size) ||
b78ea5fc 6842 !diff_filespec_is_identical(r, p->one, p->two)) /* (2) */
f34b205f
NTND
6843 p->skip_stat_unmatch_result = 1;
6844 return p->skip_stat_unmatch_result;
fceb9072
NTND
6845}
6846
fb13227e
JH
6847static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
6848{
6849 int i;
6850 struct diff_queue_struct *q = &diff_queued_diff;
6851 struct diff_queue_struct outq;
9ca5df90 6852 DIFF_QUEUE_CLEAR(&outq);
fb13227e
JH
6853
6854 for (i = 0; i < q->nr; i++) {
6855 struct diff_filepair *p = q->queue[i];
6856
b78ea5fc 6857 if (diff_filespec_check_stat_unmatch(diffopt->repo, p))
fb13227e
JH
6858 diff_q(&outq, p);
6859 else {
6860 /*
6861 * The caller can subtract 1 from skip_stat_unmatch
6862 * to determine how many paths were dirty only
6863 * due to stat info mismatch.
6864 */
0d1e0e78 6865 if (!diffopt->flags.no_index)
6d2d9e86 6866 diffopt->skip_stat_unmatch++;
fb13227e
JH
6867 diff_free_filepair(p);
6868 }
6869 }
6870 free(q->queue);
6871 *q = outq;
6872}
6873
730f7284
JH
6874static int diffnamecmp(const void *a_, const void *b_)
6875{
6876 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
6877 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
6878 const char *name_a, *name_b;
6879
6880 name_a = a->one ? a->one->path : a->two->path;
6881 name_b = b->one ? b->one->path : b->two->path;
6882 return strcmp(name_a, name_b);
6883}
6884
784c0dae 6885void diffcore_fix_diff_index(void)
730f7284
JH
6886{
6887 struct diff_queue_struct *q = &diff_queued_diff;
9ed0d8d6 6888 QSORT(q->queue, q->nr, diffnamecmp);
730f7284
JH
6889}
6890
95acf11a
JT
6891void diff_add_if_missing(struct repository *r,
6892 struct oid_array *to_fetch,
6893 const struct diff_filespec *filespec)
7fbbcb21
JT
6894{
6895 if (filespec && filespec->oid_valid &&
a63694f5 6896 !S_ISGITLINK(filespec->mode) &&
7fbbcb21
JT
6897 oid_object_info_extended(r, &filespec->oid, NULL,
6898 OBJECT_INFO_FOR_PREFETCH))
6899 oid_array_append(to_fetch, &filespec->oid);
6900}
6901
95acf11a 6902void diff_queued_diff_prefetch(void *repository)
6973dcae 6903{
95acf11a
JT
6904 struct repository *repo = repository;
6905 int i;
6906 struct diff_queue_struct *q = &diff_queued_diff;
6907 struct oid_array to_fetch = OID_ARRAY_INIT;
7fbbcb21 6908
95acf11a
JT
6909 for (i = 0; i < q->nr; i++) {
6910 struct diff_filepair *p = q->queue[i];
6911 diff_add_if_missing(repo, &to_fetch, p->one);
6912 diff_add_if_missing(repo, &to_fetch, p->two);
7fbbcb21
JT
6913 }
6914
95acf11a
JT
6915 /*
6916 * NEEDSWORK: Consider deduplicating the OIDs sent.
6917 */
6918 promisor_remote_get_direct(repo, to_fetch.oid, to_fetch.nr);
6919
6920 oid_array_clear(&to_fetch);
6921}
6922
6923void diffcore_std(struct diff_options *options)
6924{
6925 int output_formats_to_prefetch = DIFF_FORMAT_DIFFSTAT |
6926 DIFF_FORMAT_NUMSTAT |
6927 DIFF_FORMAT_PATCH |
6928 DIFF_FORMAT_SHORTSTAT |
6929 DIFF_FORMAT_DIRSTAT;
6930
6931 /*
6932 * Check if the user requested a blob-data-requiring diff output and/or
6933 * break-rewrite detection (which requires blob data). If yes, prefetch
6934 * the diff pairs.
6935 *
6936 * If no prefetching occurs, diffcore_rename() will prefetch if it
6937 * decides that it needs inexact rename detection.
6938 */
a5183d76 6939 if (options->repo == the_repository && repo_has_promisor_remote(the_repository) &&
95acf11a
JT
6940 (options->output_format & output_formats_to_prefetch ||
6941 options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
6942 diff_queued_diff_prefetch(options->repo);
6943
7195fbfa 6944 /* NOTE please keep the following in sync with diff_tree_combined() */
9d865356 6945 if (options->skip_stat_unmatch)
fb13227e 6946 diffcore_skip_stat_unmatch(options);
44c48a90
JH
6947 if (!options->found_follow) {
6948 /* See try_to_follow_renames() in tree-diff.c */
6949 if (options->break_opt != -1)
b78ea5fc
NTND
6950 diffcore_break(options->repo,
6951 options->break_opt);
44c48a90
JH
6952 if (options->detect_rename)
6953 diffcore_rename(options);
6954 if (options->break_opt != -1)
6955 diffcore_merge_broken();
6956 }
cf63051a 6957 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
382f013b 6958 diffcore_pickaxe(options);
6973dcae
JH
6959 if (options->orderfile)
6960 diffcore_order(options->orderfile);
1eb4136a
JH
6961 if (options->rotate_to)
6962 diffcore_rotate(options);
44c48a90
JH
6963 if (!options->found_follow)
6964 /* See try_to_follow_renames() in tree-diff.c */
6965 diff_resolve_rename_copy();
949226fe 6966 diffcore_apply_filter(options);
68aacb2f 6967
0d1e0e78
BW
6968 if (diff_queued_diff.nr && !options->flags.diff_from_contents)
6969 options->flags.has_changes = 1;
8f67f8ae 6970 else
0d1e0e78 6971 options->flags.has_changes = 0;
1da6175d 6972
44c48a90 6973 options->found_follow = 0;
6973dcae
JH
6974}
6975
da31b358
JH
6976int diff_result_code(struct diff_options *opt, int status)
6977{
6978 int result = 0;
f31027c9 6979
c9fc4415 6980 diff_warn_rename_limit("diff.renameLimit",
f31027c9
JH
6981 opt->needed_rename_limit,
6982 opt->degraded_cc_to_c);
0d1e0e78 6983 if (!opt->flags.exit_with_status &&
da31b358
JH
6984 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
6985 return status;
0d1e0e78
BW
6986 if (opt->flags.exit_with_status &&
6987 opt->flags.has_changes)
da31b358
JH
6988 result |= 01;
6989 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
0d1e0e78 6990 opt->flags.check_failed)
da31b358
JH
6991 result |= 02;
6992 return result;
6993}
6973dcae 6994
28b9264d
JH
6995int diff_can_quit_early(struct diff_options *opt)
6996{
0d1e0e78 6997 return (opt->flags.quick &&
28b9264d 6998 !opt->filter &&
0d1e0e78 6999 opt->flags.has_changes);
28b9264d
JH
7000}
7001
aee9c7d6
JL
7002/*
7003 * Shall changes to this submodule be ignored?
7004 *
7005 * Submodule changes can be configured to be ignored separately for each path,
7006 * but that configuration can be overridden from the command line.
7007 */
7008static int is_submodule_ignored(const char *path, struct diff_options *options)
7009{
7010 int ignored = 0;
02f2f56b 7011 struct diff_flags orig_flags = options->flags;
0d1e0e78 7012 if (!options->flags.override_submodule_config)
aee9c7d6 7013 set_diffopt_flags_from_submodule_config(options, path);
0d1e0e78 7014 if (options->flags.ignore_submodules)
aee9c7d6
JL
7015 ignored = 1;
7016 options->flags = orig_flags;
7017 return ignored;
7018}
7019
e4cb659e
DF
7020void compute_diffstat(struct diff_options *options,
7021 struct diffstat_t *diffstat,
7022 struct diff_queue_struct *q)
7023{
7024 int i;
7025
7026 memset(diffstat, 0, sizeof(struct diffstat_t));
7027 for (i = 0; i < q->nr; i++) {
7028 struct diff_filepair *p = q->queue[i];
7029 if (check_pair_status(p))
7030 diff_flush_stat(p, options, diffstat);
7031 }
7032}
7033
6973dcae
JH
7034void diff_addremove(struct diff_options *options,
7035 int addremove, unsigned mode,
c26022ea
BW
7036 const struct object_id *oid,
7037 int oid_valid,
e3d42c47 7038 const char *concatpath, unsigned dirty_submodule)
6973dcae 7039{
6973dcae
JH
7040 struct diff_filespec *one, *two;
7041
aee9c7d6 7042 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
50fd9bd8
JS
7043 return;
7044
6973dcae
JH
7045 /* This may look odd, but it is a preparation for
7046 * feeding "there are unchanged files which should
7047 * not produce diffs, but when you are doing copy
7048 * detection you would need them, so here they are"
7049 * entries to the diff-core. They will be prefixed
7050 * with something like '=' or '*' (I haven't decided
7051 * which but should not make any difference).
a6080a0a 7052 * Feeding the same new and old to diff_change()
6973dcae
JH
7053 * also has the same effect.
7054 * Before the final output happens, they are pruned after
7055 * merged into rename/copy pairs as appropriate.
7056 */
0d1e0e78 7057 if (options->flags.reverse_diff)
6973dcae
JH
7058 addremove = (addremove == '+' ? '-' :
7059 addremove == '-' ? '+' : addremove);
7060
cd676a51
JH
7061 if (options->prefix &&
7062 strncmp(concatpath, options->prefix, options->prefix_length))
7063 return;
7064
6973dcae
JH
7065 one = alloc_filespec(concatpath);
7066 two = alloc_filespec(concatpath);
7067
7068 if (addremove != '+')
f9704c2d 7069 fill_filespec(one, oid, oid_valid, mode);
e3d42c47 7070 if (addremove != '-') {
f9704c2d 7071 fill_filespec(two, oid, oid_valid, mode);
e3d42c47
JL
7072 two->dirty_submodule = dirty_submodule;
7073 }
6973dcae
JH
7074
7075 diff_queue(&diff_queued_diff, one, two);
0d1e0e78
BW
7076 if (!options->flags.diff_from_contents)
7077 options->flags.has_changes = 1;
6973dcae
JH
7078}
7079
7080void diff_change(struct diff_options *options,
7081 unsigned old_mode, unsigned new_mode,
94a0097a
BW
7082 const struct object_id *old_oid,
7083 const struct object_id *new_oid,
7084 int old_oid_valid, int new_oid_valid,
e3d42c47
JL
7085 const char *concatpath,
7086 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
6973dcae 7087{
6973dcae 7088 struct diff_filespec *one, *two;
f34b205f 7089 struct diff_filepair *p;
6973dcae 7090
aee9c7d6
JL
7091 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
7092 is_submodule_ignored(concatpath, options))
50fd9bd8
JS
7093 return;
7094
0d1e0e78 7095 if (options->flags.reverse_diff) {
35d803bc 7096 SWAP(old_mode, new_mode);
94a0097a
BW
7097 SWAP(old_oid, new_oid);
7098 SWAP(old_oid_valid, new_oid_valid);
35d803bc 7099 SWAP(old_dirty_submodule, new_dirty_submodule);
6973dcae 7100 }
cd676a51
JH
7101
7102 if (options->prefix &&
7103 strncmp(concatpath, options->prefix, options->prefix_length))
7104 return;
7105
6973dcae
JH
7106 one = alloc_filespec(concatpath);
7107 two = alloc_filespec(concatpath);
f9704c2d
BW
7108 fill_filespec(one, old_oid, old_oid_valid, old_mode);
7109 fill_filespec(two, new_oid, new_oid_valid, new_mode);
e3d42c47
JL
7110 one->dirty_submodule = old_dirty_submodule;
7111 two->dirty_submodule = new_dirty_submodule;
f34b205f 7112 p = diff_queue(&diff_queued_diff, one, two);
6973dcae 7113
0d1e0e78 7114 if (options->flags.diff_from_contents)
f34b205f
NTND
7115 return;
7116
0d1e0e78 7117 if (options->flags.quick && options->skip_stat_unmatch &&
d2d7fbe1
JK
7118 !diff_filespec_check_stat_unmatch(options->repo, p)) {
7119 diff_free_filespec_data(p->one);
7120 diff_free_filespec_data(p->two);
f34b205f 7121 return;
d2d7fbe1 7122 }
f34b205f 7123
0d1e0e78 7124 options->flags.has_changes = 1;
6973dcae
JH
7125}
7126
fa7b2908 7127struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
6973dcae 7128{
76399c01 7129 struct diff_filepair *pair;
6973dcae 7130 struct diff_filespec *one, *two;
cd676a51
JH
7131
7132 if (options->prefix &&
7133 strncmp(path, options->prefix, options->prefix_length))
76399c01 7134 return NULL;
cd676a51 7135
6973dcae
JH
7136 one = alloc_filespec(path);
7137 two = alloc_filespec(path);
76399c01
JH
7138 pair = diff_queue(&diff_queued_diff, one, two);
7139 pair->is_unmerged = 1;
7140 return pair;
6973dcae 7141}
9cb92c39 7142
b78ea5fc
NTND
7143static char *run_textconv(struct repository *r,
7144 const char *pgm,
7145 struct diff_filespec *spec,
7146 size_t *outsize)
9cb92c39 7147{
479b0ae8 7148 struct diff_tempfile *temp;
d3180279 7149 struct child_process child = CHILD_PROCESS_INIT;
9cb92c39 7150 struct strbuf buf = STRBUF_INIT;
da1fbed3 7151 int err = 0;
9cb92c39 7152
f034bb1c 7153 temp = prepare_temp_file(r, spec);
7f14609e
ÆAB
7154 strvec_push(&child.args, pgm);
7155 strvec_push(&child.args, temp->name);
9cb92c39 7156
41a457e4 7157 child.use_shell = 1;
9cb92c39 7158 child.out = -1;
da1fbed3 7159 if (start_command(&child)) {
479b0ae8 7160 remove_tempfile();
9cb92c39
JK
7161 return NULL;
7162 }
da1fbed3
JS
7163
7164 if (strbuf_read(&buf, child.out, 0) < 0)
7165 err = error("error reading from textconv command '%s'", pgm);
70d70999 7166 close(child.out);
da1fbed3
JS
7167
7168 if (finish_command(&child) || err) {
7169 strbuf_release(&buf);
7170 remove_tempfile();
7171 return NULL;
7172 }
479b0ae8 7173 remove_tempfile();
9cb92c39
JK
7174
7175 return strbuf_detach(&buf, outsize);
7176}
840383b2 7177
6afaf807
NTND
7178size_t fill_textconv(struct repository *r,
7179 struct userdiff_driver *driver,
a788d7d5
AB
7180 struct diff_filespec *df,
7181 char **outbuf)
840383b2
JK
7182{
7183 size_t size;
7184
a64e6a44 7185 if (!driver) {
840383b2
JK
7186 if (!DIFF_FILE_VALID(df)) {
7187 *outbuf = "";
7188 return 0;
7189 }
1c37e86a 7190 if (diff_populate_filespec(r, df, NULL))
840383b2
JK
7191 die("unable to read files to diff");
7192 *outbuf = df->data;
7193 return df->size;
7194 }
7195
a64e6a44 7196 if (!driver->textconv)
033abf97 7197 BUG("fill_textconv called with non-textconv driver");
a64e6a44 7198
41c9560e 7199 if (driver->textconv_cache && df->oid_valid) {
a0d12c44 7200 *outbuf = notes_cache_get(driver->textconv_cache,
569aa376 7201 &df->oid,
d9bae1a1
JK
7202 &size);
7203 if (*outbuf)
7204 return size;
7205 }
7206
b78ea5fc 7207 *outbuf = run_textconv(r, driver->textconv, df, &size);
840383b2
JK
7208 if (!*outbuf)
7209 die("unable to read files to diff");
d9bae1a1 7210
41c9560e 7211 if (driver->textconv_cache && df->oid_valid) {
d9bae1a1 7212 /* ignore errors, as we might be in a readonly repository */
569aa376 7213 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
d9bae1a1
JK
7214 size);
7215 /*
7216 * we could save up changes and flush them all at the end,
7217 * but we would need an extra call after all diffing is done.
7218 * Since generating a cache entry is the slow path anyway,
7219 * this extra overhead probably isn't a big deal.
7220 */
7221 notes_cache_write(driver->textconv_cache);
7222 }
7223
840383b2
JK
7224 return size;
7225}
4914c962 7226
6afaf807
NTND
7227int textconv_object(struct repository *r,
7228 const char *path,
3a35cb2e
JS
7229 unsigned mode,
7230 const struct object_id *oid,
7231 int oid_valid,
7232 char **buf,
7233 unsigned long *buf_size)
7234{
7235 struct diff_filespec *df;
7236 struct userdiff_driver *textconv;
7237
7238 df = alloc_filespec(path);
a6f38c10 7239 fill_filespec(df, oid, oid_valid, mode);
bd7ad45b 7240 textconv = get_textconv(r, df);
3a35cb2e
JS
7241 if (!textconv) {
7242 free_filespec(df);
7243 return 0;
7244 }
7245
6afaf807 7246 *buf_size = fill_textconv(r, textconv, df, buf);
3a35cb2e
JS
7247 free_filespec(df);
7248 return 1;
7249}
7250
4914c962
NTND
7251void setup_diff_pager(struct diff_options *opt)
7252{
7253 /*
7254 * If the user asked for our exit code, then either they want --quiet
7255 * or --exit-code. We should definitely not bother with a pager in the
7256 * former case, as we will generate no output. Since we still properly
7257 * report our exit code even when a pager is run, we _could_ run a
7258 * pager with --exit-code. But since we have not done so historically,
7259 * and because it is easy to find people oneline advising "git diff
7260 * --exit-code" in hooks and other scripts, we do not do so.
7261 */
0d1e0e78 7262 if (!opt->flags.exit_with_status &&
4914c962
NTND
7263 check_pager_config("diff") != 0)
7264 setup_pager();
7265}