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