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