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