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