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