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