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