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