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