]> git.ipfire.org Git - thirdparty/git.git/blame - diff.c
Merge branch 'jt/t5500-unflake'
[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);
c397aac0 4098 struct checkout_metadata meta;
4099
4100 init_checkout_metadata(&meta, NULL, NULL, oid);
6973dcae 4101
003b33a8 4102 /* Generate "XXXXXX_basename.ext" */
c2a46a7c
BW
4103 strbuf_addstr(&tempfile, "XXXXXX_");
4104 strbuf_addstr(&tempfile, base);
003b33a8 4105
c2a46a7c 4106 temp->tempfile = mks_tempfile_ts(tempfile.buf, strlen(base) + 1);
076aa2cb 4107 if (!temp->tempfile)
d824cbba 4108 die_errno("unable to create temp-file");
b78ea5fc 4109 if (convert_to_working_tree(istate, path,
c397aac0 4110 (const char *)blob, (size_t)size, &buf, &meta)) {
4e218f54
JS
4111 blob = buf.buf;
4112 size = buf.len;
4113 }
c50424a6 4114 if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
076aa2cb 4115 close_tempfile_gently(temp->tempfile))
0721c314 4116 die_errno("unable to write temp-file");
076aa2cb 4117 temp->name = get_tempfile_path(temp->tempfile);
09bdff29 4118 oid_to_hex_r(temp->hex, oid);
5096d490 4119 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
4e218f54 4120 strbuf_release(&buf);
c2a46a7c 4121 strbuf_release(&tempfile);
003b33a8 4122 free(path_dup);
6973dcae
JH
4123}
4124
b78ea5fc
NTND
4125static struct diff_tempfile *prepare_temp_file(struct repository *r,
4126 const char *name,
4127 struct diff_filespec *one)
6973dcae 4128{
479b0ae8
JK
4129 struct diff_tempfile *temp = claim_diff_tempfile();
4130
6973dcae
JH
4131 if (!DIFF_FILE_VALID(one)) {
4132 not_a_valid_file:
4133 /* A '-' entry produces this for file-2, and
4134 * a '+' entry produces this for file-1.
4135 */
4136 temp->name = "/dev/null";
5096d490
JK
4137 xsnprintf(temp->hex, sizeof(temp->hex), ".");
4138 xsnprintf(temp->mode, sizeof(temp->mode), ".");
479b0ae8
JK
4139 return temp;
4140 }
4141
aba47272 4142 if (!S_ISGITLINK(one->mode) &&
41c9560e 4143 (!one->oid_valid ||
b78ea5fc 4144 reuse_worktree_file(r->index, name, &one->oid, 1))) {
6973dcae
JH
4145 struct stat st;
4146 if (lstat(name, &st) < 0) {
4147 if (errno == ENOENT)
4148 goto not_a_valid_file;
d824cbba 4149 die_errno("stat(%s)", name);
6973dcae
JH
4150 }
4151 if (S_ISLNK(st.st_mode)) {
3cd7388d
JK
4152 struct strbuf sb = STRBUF_INIT;
4153 if (strbuf_readlink(&sb, name, st.st_size) < 0)
0721c314 4154 die_errno("readlink(%s)", name);
b78ea5fc 4155 prep_temp_blob(r->index, name, temp, sb.buf, sb.len,
41c9560e 4156 (one->oid_valid ?
09bdff29 4157 &one->oid : &null_oid),
41c9560e 4158 (one->oid_valid ?
6973dcae 4159 one->mode : S_IFLNK));
3cd7388d 4160 strbuf_release(&sb);
6973dcae
JH
4161 }
4162 else {
4163 /* we can borrow from the file in the work tree */
4164 temp->name = name;
41c9560e 4165 if (!one->oid_valid)
74014152 4166 oid_to_hex_r(temp->hex, &null_oid);
6973dcae 4167 else
2490574d 4168 oid_to_hex_r(temp->hex, &one->oid);
6973dcae
JH
4169 /* Even though we may sometimes borrow the
4170 * contents from the work tree, we always want
4171 * one->mode. mode is trustworthy even when
74014152 4172 * !(one->oid_valid), as long as
6973dcae
JH
4173 * DIFF_FILE_VALID(one).
4174 */
5096d490 4175 xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
6973dcae 4176 }
479b0ae8 4177 return temp;
6973dcae
JH
4178 }
4179 else {
1c37e86a 4180 if (diff_populate_filespec(r, one, NULL))
6973dcae 4181 die("cannot read data blob for %s", one->path);
b78ea5fc
NTND
4182 prep_temp_blob(r->index, name, temp,
4183 one->data, one->size,
09bdff29 4184 &one->oid, one->mode);
6973dcae 4185 }
479b0ae8 4186 return temp;
6973dcae
JH
4187}
4188
b78ea5fc
NTND
4189static void add_external_diff_name(struct repository *r,
4190 struct argv_array *argv,
f3efe787
JK
4191 const char *name,
4192 struct diff_filespec *df)
4193{
b78ea5fc 4194 struct diff_tempfile *temp = prepare_temp_file(r, name, df);
f3efe787
JK
4195 argv_array_push(argv, temp->name);
4196 argv_array_push(argv, temp->hex);
4197 argv_array_push(argv, temp->mode);
4198}
4199
6973dcae
JH
4200/* An external diff command takes:
4201 *
4202 * diff-cmd name infile1 infile1-sha1 infile1-mode \
4203 * infile2 infile2-sha1 infile2-mode [ rename-to ]
4204 *
4205 */
4206static void run_external_diff(const char *pgm,
4207 const char *name,
4208 const char *other,
4209 struct diff_filespec *one,
4210 struct diff_filespec *two,
4211 const char *xfrm_msg,
ee7fb0b1 4212 struct diff_options *o)
6973dcae 4213{
82fbf269 4214 struct argv_array argv = ARGV_ARRAY_INIT;
ae049c95 4215 struct argv_array env = ARGV_ARRAY_INIT;
ee7fb0b1 4216 struct diff_queue_struct *q = &diff_queued_diff;
6973dcae 4217
0d4217d9
JK
4218 argv_array_push(&argv, pgm);
4219 argv_array_push(&argv, name);
6973dcae 4220
6973dcae 4221 if (one && two) {
b78ea5fc 4222 add_external_diff_name(o->repo, &argv, name, one);
f3efe787 4223 if (!other)
b78ea5fc 4224 add_external_diff_name(o->repo, &argv, name, two);
f3efe787 4225 else {
b78ea5fc 4226 add_external_diff_name(o->repo, &argv, other, two);
82fbf269
JK
4227 argv_array_push(&argv, other);
4228 argv_array_push(&argv, xfrm_msg);
6973dcae 4229 }
6973dcae 4230 }
ee7fb0b1 4231
ae049c95
JK
4232 argv_array_pushf(&env, "GIT_DIFF_PATH_COUNTER=%d", ++o->diff_path_counter);
4233 argv_array_pushf(&env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
ee7fb0b1 4234
3aef54e8
JS
4235 diff_free_filespec_data(one);
4236 diff_free_filespec_data(two);
89294d14
JK
4237 if (run_command_v_opt_cd_env(argv.argv, RUN_USING_SHELL, NULL, env.argv))
4238 die(_("external diff died, stopping at %s"), name);
ee7fb0b1 4239
6973dcae 4240 remove_tempfile();
82fbf269 4241 argv_array_clear(&argv);
ae049c95 4242 argv_array_clear(&env);
6973dcae
JH
4243}
4244
b67b9612
JH
4245static int similarity_index(struct diff_filepair *p)
4246{
4247 return p->score * 100 / MAX_SCORE;
4248}
4249
4f03666a
JK
4250static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
4251{
4252 if (startup_info->have_repository)
aab9583f 4253 return find_unique_abbrev(oid, abbrev);
4f03666a
JK
4254 else {
4255 char *hex = oid_to_hex(oid);
0d9c527d
JH
4256 if (abbrev < 0)
4257 abbrev = FALLBACK_DEFAULT_ABBREV;
02afca1e 4258 if (abbrev > the_hash_algo->hexsz)
033abf97 4259 BUG("oid abbreviation out of range: %d", abbrev);
43d1948b
JB
4260 if (abbrev)
4261 hex[abbrev] = '\0';
4f03666a
JK
4262 return hex;
4263 }
4264}
4265
b67b9612
JH
4266static void fill_metainfo(struct strbuf *msg,
4267 const char *name,
4268 const char *other,
4269 struct diff_filespec *one,
4270 struct diff_filespec *two,
4271 struct diff_options *o,
37466447 4272 struct diff_filepair *p,
5977744d 4273 int *must_show_header,
37466447 4274 int use_color)
b67b9612 4275{
37466447
BW
4276 const char *set = diff_get_color(use_color, DIFF_METAINFO);
4277 const char *reset = diff_get_color(use_color, DIFF_RESET);
30997bb8 4278 const char *line_prefix = diff_line_prefix(o);
7be57610 4279
296c6bb2 4280 *must_show_header = 1;
b67b9612
JH
4281 strbuf_init(msg, PATH_MAX * 2 + 300);
4282 switch (p->status) {
4283 case DIFF_STATUS_COPIED:
98ad90fb
JH
4284 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4285 line_prefix, set, similarity_index(p));
4286 strbuf_addf(msg, "%s\n%s%scopy from ",
4287 reset, line_prefix, set);
b67b9612 4288 quote_c_style(name, msg, NULL, 0);
98ad90fb 4289 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
b67b9612 4290 quote_c_style(other, msg, NULL, 0);
37466447 4291 strbuf_addf(msg, "%s\n", reset);
b67b9612
JH
4292 break;
4293 case DIFF_STATUS_RENAMED:
98ad90fb
JH
4294 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4295 line_prefix, set, similarity_index(p));
4296 strbuf_addf(msg, "%s\n%s%srename from ",
4297 reset, line_prefix, set);
b67b9612 4298 quote_c_style(name, msg, NULL, 0);
98ad90fb
JH
4299 strbuf_addf(msg, "%s\n%s%srename to ",
4300 reset, line_prefix, set);
b67b9612 4301 quote_c_style(other, msg, NULL, 0);
37466447 4302 strbuf_addf(msg, "%s\n", reset);
b67b9612
JH
4303 break;
4304 case DIFF_STATUS_MODIFIED:
4305 if (p->score) {
98ad90fb
JH
4306 strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
4307 line_prefix,
37466447 4308 set, similarity_index(p), reset);
b67b9612
JH
4309 break;
4310 }
4311 /* fallthru */
4312 default:
296c6bb2 4313 *must_show_header = 0;
b67b9612 4314 }
9001dc2a 4315 if (one && two && !oideq(&one->oid, &two->oid)) {
de1d81d5 4316 const unsigned hexsz = the_hash_algo->hexsz;
4317 int abbrev = o->flags.full_index ? hexsz : DEFAULT_ABBREV;
b67b9612 4318
0d1e0e78 4319 if (o->flags.binary) {
b67b9612 4320 mmfile_t mf;
b78ea5fc
NTND
4321 if ((!fill_mmfile(o->repo, &mf, one) &&
4322 diff_filespec_is_binary(o->repo, one)) ||
4323 (!fill_mmfile(o->repo, &mf, two) &&
4324 diff_filespec_is_binary(o->repo, two)))
de1d81d5 4325 abbrev = hexsz;
b67b9612 4326 }
4f03666a
JK
4327 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
4328 diff_abbrev_oid(&one->oid, abbrev),
4329 diff_abbrev_oid(&two->oid, abbrev));
b67b9612
JH
4330 if (one->mode == two->mode)
4331 strbuf_addf(msg, " %06o", one->mode);
37466447 4332 strbuf_addf(msg, "%s\n", reset);
b67b9612 4333 }
b67b9612
JH
4334}
4335
6973dcae
JH
4336static void run_diff_cmd(const char *pgm,
4337 const char *name,
4338 const char *other,
cd676a51 4339 const char *attr_path,
6973dcae
JH
4340 struct diff_filespec *one,
4341 struct diff_filespec *two,
b67b9612 4342 struct strbuf *msg,
051308f6 4343 struct diff_options *o,
b67b9612 4344 struct diff_filepair *p)
6973dcae 4345{
b67b9612
JH
4346 const char *xfrm_msg = NULL;
4347 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
296c6bb2 4348 int must_show_header = 0;
b67b9612 4349
bd8c1a9b 4350
0d1e0e78 4351 if (o->flags.allow_external) {
acd00ea0
NTND
4352 struct userdiff_driver *drv;
4353
4354 drv = userdiff_find_by_path(o->repo->index, attr_path);
be58e70d
JK
4355 if (drv && drv->external)
4356 pgm = drv->external;
f1af60bd
JH
4357 }
4358
37466447
BW
4359 if (msg) {
4360 /*
4361 * don't use colors when the header is intended for an
4362 * external diff driver
4363 */
4364 fill_metainfo(msg, name, other, one, two, o, p,
5977744d 4365 &must_show_header,
daa0c3d9 4366 want_color(o->use_color) && !pgm);
37466447
BW
4367 xfrm_msg = msg->len ? msg->buf : NULL;
4368 }
4369
6973dcae 4370 if (pgm) {
4bc17927 4371 run_external_diff(pgm, name, other, one, two, xfrm_msg, o);
6973dcae
JH
4372 return;
4373 }
4374 if (one && two)
4375 builtin_diff(name, other ? other : name,
296c6bb2
CC
4376 one, two, xfrm_msg, must_show_header,
4377 o, complete_rewrite);
6973dcae 4378 else
c0c77734 4379 fprintf(o->file, "* Unmerged path %s\n", name);
6973dcae
JH
4380}
4381
58bf2a4c 4382static void diff_fill_oid_info(struct diff_filespec *one, struct index_state *istate)
6973dcae
JH
4383{
4384 if (DIFF_FILE_VALID(one)) {
41c9560e 4385 if (!one->oid_valid) {
6973dcae 4386 struct stat st;
4682d852 4387 if (one->is_stdin) {
a0d12c44 4388 oidclr(&one->oid);
5332b2af
JS
4389 return;
4390 }
6973dcae 4391 if (lstat(one->path, &st) < 0)
0721c314 4392 die_errno("stat '%s'", one->path);
58bf2a4c 4393 if (index_path(istate, &one->oid, one->path, &st, 0))
d7530708 4394 die("cannot hash %s", one->path);
6973dcae
JH
4395 }
4396 }
4397 else
a0d12c44 4398 oidclr(&one->oid);
6973dcae
JH
4399}
4400
cd676a51
JH
4401static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
4402{
4403 /* Strip the prefix but do not molest /dev/null and absolute paths */
ffd04e92 4404 if (*namep && !is_absolute_path(*namep)) {
cd676a51 4405 *namep += prefix_length;
d8faea9d
JN
4406 if (**namep == '/')
4407 ++*namep;
4408 }
ffd04e92 4409 if (*otherp && !is_absolute_path(*otherp)) {
cd676a51 4410 *otherp += prefix_length;
d8faea9d
JN
4411 if (**otherp == '/')
4412 ++*otherp;
4413 }
cd676a51
JH
4414}
4415
6973dcae
JH
4416static void run_diff(struct diff_filepair *p, struct diff_options *o)
4417{
4418 const char *pgm = external_diff();
663af342 4419 struct strbuf msg;
663af342
PH
4420 struct diff_filespec *one = p->one;
4421 struct diff_filespec *two = p->two;
6973dcae
JH
4422 const char *name;
4423 const char *other;
cd676a51 4424 const char *attr_path;
663af342 4425
f2d2a5de
SB
4426 name = one->path;
4427 other = (strcmp(name, two->path) ? two->path : NULL);
cd676a51
JH
4428 attr_path = name;
4429 if (o->prefix_length)
4430 strip_prefix(o->prefix_length, &name, &other);
6973dcae 4431
0d1e0e78 4432 if (!o->flags.allow_external)
bd8c1a9b
JH
4433 pgm = NULL;
4434
6973dcae 4435 if (DIFF_PAIR_UNMERGED(p)) {
cd676a51 4436 run_diff_cmd(pgm, name, NULL, attr_path,
b67b9612 4437 NULL, NULL, NULL, o, p);
6973dcae
JH
4438 return;
4439 }
4440
58bf2a4c
NTND
4441 diff_fill_oid_info(one, o->repo->index);
4442 diff_fill_oid_info(two, o->repo->index);
6973dcae 4443
6973dcae
JH
4444 if (!pgm &&
4445 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
4446 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
b67b9612
JH
4447 /*
4448 * a filepair that changes between file and symlink
6973dcae
JH
4449 * needs to be split into deletion and creation.
4450 */
4451 struct diff_filespec *null = alloc_filespec(two->path);
cd676a51 4452 run_diff_cmd(NULL, name, other, attr_path,
b78ea5fc
NTND
4453 one, null, &msg,
4454 o, p);
6973dcae 4455 free(null);
b67b9612
JH
4456 strbuf_release(&msg);
4457
6973dcae 4458 null = alloc_filespec(one->path);
cd676a51 4459 run_diff_cmd(NULL, name, other, attr_path,
b67b9612 4460 null, two, &msg, o, p);
6973dcae
JH
4461 free(null);
4462 }
4463 else
cd676a51 4464 run_diff_cmd(pgm, name, other, attr_path,
b67b9612 4465 one, two, &msg, o, p);
6973dcae 4466
663af342 4467 strbuf_release(&msg);
6973dcae
JH
4468}
4469
4470static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
4471 struct diffstat_t *diffstat)
4472{
4473 const char *name;
4474 const char *other;
4475
4476 if (DIFF_PAIR_UNMERGED(p)) {
4477 /* unmerged */
b78ea5fc
NTND
4478 builtin_diffstat(p->one->path, NULL, NULL, NULL,
4479 diffstat, o, p);
6973dcae
JH
4480 return;
4481 }
4482
4483 name = p->one->path;
4484 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4485
cd676a51
JH
4486 if (o->prefix_length)
4487 strip_prefix(o->prefix_length, &name, &other);
4488
58bf2a4c
NTND
4489 diff_fill_oid_info(p->one, o->repo->index);
4490 diff_fill_oid_info(p->two, o->repo->index);
6973dcae 4491
b78ea5fc
NTND
4492 builtin_diffstat(name, other, p->one, p->two,
4493 diffstat, o, p);
6973dcae
JH
4494}
4495
88246898
JS
4496static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
4497{
4498 const char *name;
4499 const char *other;
cd676a51 4500 const char *attr_path;
88246898
JS
4501
4502 if (DIFF_PAIR_UNMERGED(p)) {
4503 /* unmerged */
4504 return;
4505 }
4506
4507 name = p->one->path;
4508 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
cd676a51
JH
4509 attr_path = other ? other : name;
4510
4511 if (o->prefix_length)
4512 strip_prefix(o->prefix_length, &name, &other);
88246898 4513
58bf2a4c
NTND
4514 diff_fill_oid_info(p->one, o->repo->index);
4515 diff_fill_oid_info(p->two, o->repo->index);
88246898 4516
cd676a51 4517 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
88246898
JS
4518}
4519
4a288478
NTND
4520static void prep_parse_options(struct diff_options *options);
4521
e6757652 4522void repo_diff_setup(struct repository *r, struct diff_options *options)
6973dcae 4523{
be4f2b40 4524 memcpy(options, &default_diff_options, sizeof(*options));
c0c77734
DB
4525
4526 options->file = stdout;
e6757652 4527 options->repo = r;
c0c77734 4528
7648b79e
SB
4529 options->output_indicators[OUTPUT_INDICATOR_NEW] = '+';
4530 options->output_indicators[OUTPUT_INDICATOR_OLD] = '-';
4531 options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = ' ';
43d1948b 4532 options->abbrev = DEFAULT_ABBREV;
6973dcae
JH
4533 options->line_termination = '\n';
4534 options->break_opt = -1;
4535 options->rename_limit = -1;
712d2c7d 4536 options->dirstat_permille = diff_dirstat_permille_default;
6468a4e5 4537 options->context = diff_context_default;
c4888677 4538 options->interhunkcontext = diff_interhunk_context_default;
a17505f2 4539 options->ws_error_highlight = ws_error_highlight_default;
0d1e0e78 4540 options->flags.rename_empty = 1;
15af58c1 4541 options->objfind = NULL;
6973dcae 4542
72441af7 4543 /* pathchange left =NULL by default */
6973dcae
JH
4544 options->change = diff_change;
4545 options->add_remove = diff_addremove;
f1c96261 4546 options->use_color = diff_use_color_default;
b68ea12e 4547 options->detect_rename = diff_detect_rename_default;
07ab4dec 4548 options->xdl_opts |= diff_algorithm;
433860f3
MH
4549 if (diff_indent_heuristic)
4550 DIFF_XDL_SET(options, INDENT_HEURISTIC);
eab9a40b 4551
6d8940b5
SB
4552 options->orderfile = diff_order_file_cfg;
4553
f89504dd
EC
4554 if (diff_no_prefix) {
4555 options->a_prefix = options->b_prefix = "";
4556 } else if (!diff_mnemonic_prefix) {
a5a818ee
JH
4557 options->a_prefix = "a/";
4558 options->b_prefix = "b/";
4559 }
2e2d5ac1
SB
4560
4561 options->color_moved = diff_color_moved_default;
626c0b5d 4562 options->color_moved_ws_handling = diff_color_moved_ws_default;
4a288478
NTND
4563
4564 prep_parse_options(options);
6973dcae
JH
4565}
4566
28452655 4567void diff_setup_done(struct diff_options *options)
6973dcae 4568{
4d8c51aa
SB
4569 unsigned check_mask = DIFF_FORMAT_NAME |
4570 DIFF_FORMAT_NAME_STATUS |
4571 DIFF_FORMAT_CHECKDIFF |
4572 DIFF_FORMAT_NO_OUTPUT;
de1d81d5 4573 /*
4574 * This must be signed because we're comparing against a potentially
4575 * negative value.
4576 */
4577 const int hexsz = the_hash_algo->hexsz;
d7de00f7 4578
6c374008
JH
4579 if (options->set_default)
4580 options->set_default(options);
4581
4d8c51aa 4582 if (HAS_MULTI_BITS(options->output_format & check_mask))
a2f05c94 4583 die(_("--name-only, --name-status, --check and -s are mutually exclusive"));
d7de00f7 4584
5e505257
SB
4585 if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
4586 die(_("-G, -S and --find-object are mutually exclusive"));
4587
f245194f
JH
4588 /*
4589 * Most of the time we can say "there are changes"
4590 * only by checking if there are changed paths, but
4591 * --ignore-whitespace* options force us to look
97bf2a08 4592 * inside contents.
f245194f
JH
4593 */
4594
446d12cb 4595 if ((options->xdl_opts & XDF_WHITESPACE_FLAGS))
0d1e0e78 4596 options->flags.diff_from_contents = 1;
f245194f 4597 else
0d1e0e78 4598 options->flags.diff_from_contents = 0;
f245194f 4599
0d1e0e78 4600 if (options->flags.find_copies_harder)
03b9d560
JH
4601 options->detect_rename = DIFF_DETECT_COPY;
4602
0d1e0e78 4603 if (!options->flags.relative_name)
cd676a51
JH
4604 options->prefix = NULL;
4605 if (options->prefix)
4606 options->prefix_length = strlen(options->prefix);
4607 else
4608 options->prefix_length = 0;
4609
c6744349
TH
4610 if (options->output_format & (DIFF_FORMAT_NAME |
4611 DIFF_FORMAT_NAME_STATUS |
4612 DIFF_FORMAT_CHECKDIFF |
4613 DIFF_FORMAT_NO_OUTPUT))
4614 options->output_format &= ~(DIFF_FORMAT_RAW |
74e2abe5 4615 DIFF_FORMAT_NUMSTAT |
c6744349 4616 DIFF_FORMAT_DIFFSTAT |
ebd124c6 4617 DIFF_FORMAT_SHORTSTAT |
7df7c019 4618 DIFF_FORMAT_DIRSTAT |
c6744349
TH
4619 DIFF_FORMAT_SUMMARY |
4620 DIFF_FORMAT_PATCH);
4621
6973dcae
JH
4622 /*
4623 * These cases always need recursive; we do not drop caller-supplied
4624 * recursive bits for other formats here.
4625 */
c6744349 4626 if (options->output_format & (DIFF_FORMAT_PATCH |
74e2abe5 4627 DIFF_FORMAT_NUMSTAT |
c6744349 4628 DIFF_FORMAT_DIFFSTAT |
ebd124c6 4629 DIFF_FORMAT_SHORTSTAT |
7df7c019 4630 DIFF_FORMAT_DIRSTAT |
d7014dc0 4631 DIFF_FORMAT_SUMMARY |
c6744349 4632 DIFF_FORMAT_CHECKDIFF))
0d1e0e78 4633 options->flags.recursive = 1;
5e363541 4634 /*
3969cf7d 4635 * Also pickaxe would not work very well if you do not say recursive
5e363541 4636 */
cf63051a 4637 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
0d1e0e78 4638 options->flags.recursive = 1;
ae6d5c1b
JL
4639 /*
4640 * When patches are generated, submodules diffed against the work tree
4641 * must be checked for dirtiness too so it can be shown in the output
4642 */
4643 if (options->output_format & DIFF_FORMAT_PATCH)
0d1e0e78 4644 options->flags.dirty_submodules = 1;
5e363541 4645
6973dcae
JH
4646 if (options->detect_rename && options->rename_limit < 0)
4647 options->rename_limit = diff_rename_limit_default;
de1d81d5 4648 if (hexsz < options->abbrev)
4649 options->abbrev = hexsz; /* full */
6973dcae 4650
68aacb2f
JH
4651 /*
4652 * It does not make sense to show the first hit we happened
4653 * to have found. It does not make sense not to return with
4654 * exit code in such a case either.
4655 */
0d1e0e78 4656 if (options->flags.quick) {
68aacb2f 4657 options->output_format = DIFF_FORMAT_NO_OUTPUT;
0d1e0e78 4658 options->flags.exit_with_status = 1;
68aacb2f 4659 }
ee7fb0b1 4660
0ea7d5b6 4661 options->diff_path_counter = 0;
b0e2c999 4662
0d1e0e78 4663 if (options->flags.follow_renames && options->pathspec.nr != 1)
dd63f169 4664 die(_("--follow requires exactly one pathspec"));
2e2d5ac1
SB
4665
4666 if (!options->use_color || external_diff())
4667 options->color_moved = 0;
4a288478
NTND
4668
4669 FREE_AND_NULL(options->parseopts);
6973dcae
JH
4670}
4671
dea007fb
MM
4672int parse_long_opt(const char *opt, const char **argv,
4673 const char **optarg)
4674{
4675 const char *arg = argv[0];
95b567c7 4676 if (!skip_prefix(arg, "--", &arg))
dea007fb 4677 return 0;
95b567c7 4678 if (!skip_prefix(arg, opt, &arg))
dea007fb 4679 return 0;
b0d12fc9 4680 if (*arg == '=') { /* stuck form: --option=value */
dea007fb
MM
4681 *optarg = arg + 1;
4682 return 1;
4683 }
4684 if (*arg != '\0')
4685 return 0;
4686 /* separate form: --option value */
4687 if (!argv[1])
4688 die("Option '--%s' requires a value", opt);
4689 *optarg = argv[1];
4690 return 2;
4691}
4692
84b5089e 4693static int diff_opt_stat(const struct option *opt, const char *value, int unset)
4d7f7a4a 4694{
84b5089e 4695 struct diff_options *options = opt->value;
4d7f7a4a
JN
4696 int width = options->stat_width;
4697 int name_width = options->stat_name_width;
969fe57b 4698 int graph_width = options->stat_graph_width;
808e1db2 4699 int count = options->stat_count;
84b5089e 4700 char *end;
4d7f7a4a 4701
84b5089e 4702 BUG_ON_OPT_NEG(unset);
4d7f7a4a 4703
84b5089e
NTND
4704 if (!strcmp(opt->long_name, "stat")) {
4705 if (value) {
4706 width = strtoul(value, &end, 10);
4707 if (*end == ',')
4708 name_width = strtoul(end+1, &end, 10);
4709 if (*end == ',')
4710 count = strtoul(end+1, &end, 10);
4711 if (*end)
4712 return error(_("invalid --stat value: %s"), value);
1e57208e 4713 }
84b5089e
NTND
4714 } else if (!strcmp(opt->long_name, "stat-width")) {
4715 width = strtoul(value, &end, 10);
4716 if (*end)
4717 return error(_("%s expects a numerical value"),
4718 opt->long_name);
4719 } else if (!strcmp(opt->long_name, "stat-name-width")) {
4720 name_width = strtoul(value, &end, 10);
4721 if (*end)
4722 return error(_("%s expects a numerical value"),
4723 opt->long_name);
4724 } else if (!strcmp(opt->long_name, "stat-graph-width")) {
4725 graph_width = strtoul(value, &end, 10);
4726 if (*end)
4727 return error(_("%s expects a numerical value"),
4728 opt->long_name);
4729 } else if (!strcmp(opt->long_name, "stat-count")) {
4730 count = strtoul(value, &end, 10);
4731 if (*end)
4732 return error(_("%s expects a numerical value"),
4733 opt->long_name);
4734 } else
4735 BUG("%s should not get here", opt->long_name);
4d7f7a4a 4736
4d7f7a4a
JN
4737 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4738 options->stat_name_width = name_width;
969fe57b 4739 options->stat_graph_width = graph_width;
4d7f7a4a 4740 options->stat_width = width;
808e1db2 4741 options->stat_count = count;
84b5089e 4742 return 0;
4d7f7a4a
JN
4743}
4744
333f3fb0
JH
4745static int parse_dirstat_opt(struct diff_options *options, const char *params)
4746{
51670fc8
JH
4747 struct strbuf errmsg = STRBUF_INIT;
4748 if (parse_dirstat_params(options, params, &errmsg))
7478ac57 4749 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
51670fc8
JH
4750 errmsg.buf);
4751 strbuf_release(&errmsg);
333f3fb0
JH
4752 /*
4753 * The caller knows a dirstat-related option is given from the command
4754 * line; allow it to say "return this_function();"
4755 */
4756 options->output_format |= DIFF_FORMAT_DIRSTAT;
4757 return 1;
4758}
4759
1ecc1cbd
JH
4760static const char diff_status_letters[] = {
4761 DIFF_STATUS_ADDED,
4762 DIFF_STATUS_COPIED,
4763 DIFF_STATUS_DELETED,
4764 DIFF_STATUS_MODIFIED,
4765 DIFF_STATUS_RENAMED,
4766 DIFF_STATUS_TYPE_CHANGED,
4767 DIFF_STATUS_UNKNOWN,
4768 DIFF_STATUS_UNMERGED,
4769 DIFF_STATUS_FILTER_AON,
4770 DIFF_STATUS_FILTER_BROKEN,
4771 '\0',
4772};
4773
4774static unsigned int filter_bit['Z' + 1];
4775
4776static void prepare_filter_bits(void)
4777{
4778 int i;
4779
4780 if (!filter_bit[DIFF_STATUS_ADDED]) {
4781 for (i = 0; diff_status_letters[i]; i++)
4782 filter_bit[(int) diff_status_letters[i]] = (1 << i);
4783 }
4784}
4785
4786static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4787{
4788 return opt->filter & filter_bit[(int) status];
4789}
4790
cdb5330a 4791unsigned diff_filter_bit(char status)
1ecc1cbd 4792{
cdb5330a
NTND
4793 prepare_filter_bits();
4794 return filter_bit[(int) status];
4795}
4796
d2d3f273
NTND
4797static int diff_opt_diff_filter(const struct option *option,
4798 const char *optarg, int unset)
1ecc1cbd 4799{
d2d3f273 4800 struct diff_options *opt = option->value;
1ecc1cbd
JH
4801 int i, optch;
4802
d2d3f273 4803 BUG_ON_OPT_NEG(unset);
1ecc1cbd 4804 prepare_filter_bits();
7f2ea5f0
JH
4805
4806 /*
4807 * If there is a negation e.g. 'd' in the input, and we haven't
4808 * initialized the filter field with another --diff-filter, start
4809 * from full set of bits, except for AON.
4810 */
4811 if (!opt->filter) {
4812 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4813 if (optch < 'a' || 'z' < optch)
4814 continue;
4815 opt->filter = (1 << (ARRAY_SIZE(diff_status_letters) - 1)) - 1;
4816 opt->filter &= ~filter_bit[DIFF_STATUS_FILTER_AON];
4817 break;
4818 }
4819 }
4820
1ecc1cbd
JH
4821 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4822 unsigned int bit;
7f2ea5f0
JH
4823 int negate;
4824
4825 if ('a' <= optch && optch <= 'z') {
4826 negate = 1;
4827 optch = toupper(optch);
4828 } else {
4829 negate = 0;
4830 }
1ecc1cbd
JH
4831
4832 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
4833 if (!bit)
d2d3f273
NTND
4834 return error(_("unknown change class '%c' in --diff-filter=%s"),
4835 optarg[i], optarg);
7f2ea5f0
JH
4836 if (negate)
4837 opt->filter &= ~bit;
4838 else
4839 opt->filter |= bit;
1ecc1cbd
JH
4840 }
4841 return 0;
4842}
4843
3b335762
NTND
4844static void enable_patch_output(int *fmt)
4845{
71482d38
MM
4846 *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
4847 *fmt |= DIFF_FORMAT_PATCH;
4848}
4849
5a749d9f
NTND
4850static int diff_opt_ws_error_highlight(const struct option *option,
4851 const char *arg, int unset)
b8767f79 4852{
5a749d9f 4853 struct diff_options *opt = option->value;
077965f8 4854 int val = parse_ws_error_highlight(arg);
b8767f79 4855
5a749d9f
NTND
4856 BUG_ON_OPT_NEG(unset);
4857 if (val < 0)
4858 return error(_("unknown value after ws-error-highlight=%.*s"),
4859 -1 - val, arg);
b8767f79 4860 opt->ws_error_highlight = val;
5a749d9f 4861 return 0;
b8767f79
JH
4862}
4863
a75f28cb
NTND
4864static int diff_opt_find_object(const struct option *option,
4865 const char *arg, int unset)
15af58c1 4866{
a75f28cb 4867 struct diff_options *opt = option->value;
15af58c1
SB
4868 struct object_id oid;
4869
a75f28cb 4870 BUG_ON_OPT_NEG(unset);
15af58c1 4871 if (get_oid(arg, &oid))
a75f28cb 4872 return error(_("unable to resolve '%s'"), arg);
15af58c1
SB
4873
4874 if (!opt->objfind)
4875 opt->objfind = xcalloc(1, sizeof(*opt->objfind));
4876
4877 opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
4878 opt->flags.recursive = 1;
4879 opt->flags.tree_in_recursive = 1;
4880 oidset_insert(opt->objfind, &oid);
a75f28cb 4881 return 0;
15af58c1
SB
4882}
4883
df84a436
NTND
4884static int diff_opt_anchored(const struct option *opt,
4885 const char *arg, int unset)
4886{
4887 struct diff_options *options = opt->value;
4888
4889 BUG_ON_OPT_NEG(unset);
4890 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
4891 ALLOC_GROW(options->anchors, options->anchors_nr + 1,
4892 options->anchors_alloc);
4893 options->anchors[options->anchors_nr++] = xstrdup(arg);
4894 return 0;
4895}
4896
6d9af6f4
NTND
4897static int diff_opt_binary(const struct option *opt,
4898 const char *arg, int unset)
4899{
4900 struct diff_options *options = opt->value;
4901
4902 BUG_ON_OPT_NEG(unset);
4903 BUG_ON_OPT_ARG(arg);
4904 enable_patch_output(&options->output_format);
4905 options->flags.binary = 1;
4906 return 0;
4907}
4908
ced4e179
NTND
4909static int diff_opt_break_rewrites(const struct option *opt,
4910 const char *arg, int unset)
4911{
4912 int *break_opt = opt->value;
4913 int opt1, opt2;
4914
4915 BUG_ON_OPT_NEG(unset);
4916 if (!arg)
4917 arg = "";
4918 opt1 = parse_rename_score(&arg);
4919 if (*arg == 0)
4920 opt2 = 0;
4921 else if (*arg != '/')
4922 return error(_("%s expects <n>/<m> form"), opt->long_name);
4923 else {
4924 arg++;
4925 opt2 = parse_rename_score(&arg);
4926 }
4927 if (*arg != 0)
4928 return error(_("%s expects <n>/<m> form"), opt->long_name);
4929 *break_opt = opt1 | (opt2 << 16);
4930 return 0;
4931}
4932
af2f3680
NTND
4933static int diff_opt_char(const struct option *opt,
4934 const char *arg, int unset)
4935{
4936 char *value = opt->value;
4937
4938 BUG_ON_OPT_NEG(unset);
4939 if (arg[1])
4940 return error(_("%s expects a character, got '%s'"),
4941 opt->long_name, arg);
4942 *value = arg[0];
4943 return 0;
4944}
4945
59311a98
NTND
4946static int diff_opt_color_moved(const struct option *opt,
4947 const char *arg, int unset)
4948{
4949 struct diff_options *options = opt->value;
4950
4951 if (unset) {
4952 options->color_moved = COLOR_MOVED_NO;
4953 } else if (!arg) {
4954 if (diff_color_moved_default)
4955 options->color_moved = diff_color_moved_default;
4956 if (options->color_moved == COLOR_MOVED_NO)
4957 options->color_moved = COLOR_MOVED_DEFAULT;
4958 } else {
4959 int cm = parse_color_moved(arg);
4960 if (cm < 0)
4961 return error(_("bad --color-moved argument: %s"), arg);
4962 options->color_moved = cm;
4963 }
4964 return 0;
4965}
4966
8ce2020f
NTND
4967static int diff_opt_color_moved_ws(const struct option *opt,
4968 const char *arg, int unset)
4969{
4970 struct diff_options *options = opt->value;
4971 unsigned cm;
4972
bb987290
NTND
4973 if (unset) {
4974 options->color_moved_ws_handling = 0;
4975 return 0;
4976 }
4977
8ce2020f
NTND
4978 cm = parse_color_moved_ws(arg);
4979 if (cm & COLOR_MOVED_WS_ERROR)
4980 return error(_("invalid mode '%s' in --color-moved-ws"), arg);
4981 options->color_moved_ws_handling = cm;
4982 return 0;
4983}
4984
212db69d
NTND
4985static int diff_opt_color_words(const struct option *opt,
4986 const char *arg, int unset)
4987{
4988 struct diff_options *options = opt->value;
4989
4990 BUG_ON_OPT_NEG(unset);
4991 options->use_color = 1;
4992 options->word_diff = DIFF_WORDS_COLOR;
4993 options->word_regex = arg;
4994 return 0;
4995}
4996
7d7942b7
NTND
4997static int diff_opt_compact_summary(const struct option *opt,
4998 const char *arg, int unset)
4999{
5000 struct diff_options *options = opt->value;
5001
5002 BUG_ON_OPT_ARG(arg);
5003 if (unset) {
5004 options->flags.stat_with_summary = 0;
5005 } else {
5006 options->flags.stat_with_summary = 1;
5007 options->output_format |= DIFF_FORMAT_DIFFSTAT;
5008 }
5009 return 0;
5010}
5011
10f35b1c
NTND
5012static int diff_opt_diff_algorithm(const struct option *opt,
5013 const char *arg, int unset)
5014{
5015 struct diff_options *options = opt->value;
5016 long value = parse_algorithm_value(arg);
5017
5018 BUG_ON_OPT_NEG(unset);
5019 if (value < 0)
5020 return error(_("option diff-algorithm accepts \"myers\", "
5021 "\"minimal\", \"patience\" and \"histogram\""));
5022
5023 /* clear out previous settings */
5024 DIFF_XDL_CLR(options, NEED_MINIMAL);
5025 options->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
5026 options->xdl_opts |= value;
5027 return 0;
5028}
5029
4ce7aab5
NTND
5030static int diff_opt_dirstat(const struct option *opt,
5031 const char *arg, int unset)
5032{
5033 struct diff_options *options = opt->value;
5034
5035 BUG_ON_OPT_NEG(unset);
5036 if (!strcmp(opt->long_name, "cumulative")) {
5037 if (arg)
5038 BUG("how come --cumulative take a value?");
5039 arg = "cumulative";
5040 } else if (!strcmp(opt->long_name, "dirstat-by-file"))
5041 parse_dirstat_opt(options, "files");
5042 parse_dirstat_opt(options, arg ? arg : "");
5043 return 0;
5044}
5045
7f64850d
NTND
5046static int diff_opt_find_copies(const struct option *opt,
5047 const char *arg, int unset)
5048{
5049 struct diff_options *options = opt->value;
5050
5051 BUG_ON_OPT_NEG(unset);
5052 if (!arg)
5053 arg = "";
5054 options->rename_score = parse_rename_score(&arg);
5055 if (*arg != 0)
5056 return error(_("invalid argument to %s"), opt->long_name);
5057
5058 if (options->detect_rename == DIFF_DETECT_COPY)
5059 options->flags.find_copies_harder = 1;
5060 else
5061 options->detect_rename = DIFF_DETECT_COPY;
5062
5063 return 0;
5064}
5065
f476308b
NTND
5066static int diff_opt_find_renames(const struct option *opt,
5067 const char *arg, int unset)
5068{
5069 struct diff_options *options = opt->value;
5070
5071 BUG_ON_OPT_NEG(unset);
5072 if (!arg)
5073 arg = "";
5074 options->rename_score = parse_rename_score(&arg);
5075 if (*arg != 0)
5076 return error(_("invalid argument to %s"), opt->long_name);
5077
5078 options->detect_rename = DIFF_DETECT_RENAME;
5079 return 0;
5080}
5081
1e9250b5
NTND
5082static int diff_opt_follow(const struct option *opt,
5083 const char *arg, int unset)
5084{
5085 struct diff_options *options = opt->value;
5086
5087 BUG_ON_OPT_ARG(arg);
5088 if (unset) {
5089 options->flags.follow_renames = 0;
5090 options->flags.default_follow_renames = 0;
5091 } else {
5092 options->flags.follow_renames = 1;
5093 }
5094 return 0;
5095}
5096
b680ee14
NTND
5097static int diff_opt_ignore_submodules(const struct option *opt,
5098 const char *arg, int unset)
5099{
5100 struct diff_options *options = opt->value;
5101
5102 BUG_ON_OPT_NEG(unset);
5103 if (!arg)
5104 arg = "all";
5105 options->flags.override_submodule_config = 1;
5106 handle_ignore_submodules_arg(options, arg);
5107 return 0;
5108}
5109
2f81cf98
NTND
5110static int diff_opt_line_prefix(const struct option *opt,
5111 const char *optarg, int unset)
5112{
5113 struct diff_options *options = opt->value;
5114
5115 BUG_ON_OPT_NEG(unset);
5116 options->line_prefix = optarg;
5117 options->line_prefix_length = strlen(options->line_prefix);
5118 graph_setup_line_prefix(options);
5119 return 0;
5120}
5121
11c659d8
NTND
5122static int diff_opt_no_prefix(const struct option *opt,
5123 const char *optarg, int unset)
5124{
5125 struct diff_options *options = opt->value;
5126
5127 BUG_ON_OPT_NEG(unset);
5128 BUG_ON_OPT_ARG(optarg);
5129 options->a_prefix = "";
5130 options->b_prefix = "";
5131 return 0;
5132}
5133
af2f3680
NTND
5134static enum parse_opt_result diff_opt_output(struct parse_opt_ctx_t *ctx,
5135 const struct option *opt,
5136 const char *arg, int unset)
5137{
5138 struct diff_options *options = opt->value;
5139 char *path;
5140
5141 BUG_ON_OPT_NEG(unset);
5142 path = prefix_filename(ctx->prefix, arg);
5143 options->file = xfopen(path, "w");
5144 options->close_file = 1;
5145 if (options->use_color != GIT_COLOR_ALWAYS)
5146 options->use_color = GIT_COLOR_NEVER;
5147 free(path);
5148 return 0;
5149}
5150
31fd640e
NTND
5151static int diff_opt_patience(const struct option *opt,
5152 const char *arg, int unset)
5153{
5154 struct diff_options *options = opt->value;
5155 int i;
5156
5157 BUG_ON_OPT_NEG(unset);
5158 BUG_ON_OPT_ARG(arg);
5159 options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
5160 /*
5161 * Both --patience and --anchored use PATIENCE_DIFF
5162 * internally, so remove any anchors previously
5163 * specified.
5164 */
5165 for (i = 0; i < options->anchors_nr; i++)
5166 free(options->anchors[i]);
5167 options->anchors_nr = 0;
5168 return 0;
5169}
5170
a41cfb32
NTND
5171static int diff_opt_pickaxe_regex(const struct option *opt,
5172 const char *arg, int unset)
5173{
5174 struct diff_options *options = opt->value;
5175
5176 BUG_ON_OPT_NEG(unset);
5177 options->pickaxe = arg;
5178 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
5179 return 0;
5180}
5181
5182static int diff_opt_pickaxe_string(const struct option *opt,
5183 const char *arg, int unset)
5184{
5185 struct diff_options *options = opt->value;
5186
5187 BUG_ON_OPT_NEG(unset);
5188 options->pickaxe = arg;
5189 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
5190 return 0;
5191}
5192
0b1c5b59
NTND
5193static int diff_opt_relative(const struct option *opt,
5194 const char *arg, int unset)
5195{
5196 struct diff_options *options = opt->value;
5197
5198 BUG_ON_OPT_NEG(unset);
5199 options->flags.relative_name = 1;
5200 if (arg)
5201 options->prefix = arg;
5202 return 0;
5203}
5204
125dcea9
NTND
5205static int diff_opt_submodule(const struct option *opt,
5206 const char *arg, int unset)
5207{
5208 struct diff_options *options = opt->value;
5209
5210 BUG_ON_OPT_NEG(unset);
5211 if (!arg)
5212 arg = "log";
5213 if (parse_submodule_params(options, arg))
5214 return error(_("failed to parse --submodule option parameter: '%s'"),
5215 arg);
5216 return 0;
5217}
5218
8ab76977
NTND
5219static int diff_opt_textconv(const struct option *opt,
5220 const char *arg, int unset)
5221{
5222 struct diff_options *options = opt->value;
5223
5224 BUG_ON_OPT_ARG(arg);
5225 if (unset) {
5226 options->flags.allow_textconv = 0;
5227 } else {
5228 options->flags.allow_textconv = 1;
5229 options->flags.textconv_set_via_cmdline = 1;
5230 }
5231 return 0;
5232}
5233
d473e2e0
NTND
5234static int diff_opt_unified(const struct option *opt,
5235 const char *arg, int unset)
5236{
5237 struct diff_options *options = opt->value;
5238 char *s;
5239
5240 BUG_ON_OPT_NEG(unset);
5241
8ef05193
NTND
5242 if (arg) {
5243 options->context = strtol(arg, &s, 10);
5244 if (*s)
5245 return error(_("%s expects a numerical value"), "--unified");
5246 }
d473e2e0
NTND
5247 enable_patch_output(&options->output_format);
5248
5249 return 0;
5250}
5251
e9fb39b6
NTND
5252static int diff_opt_word_diff(const struct option *opt,
5253 const char *arg, int unset)
5254{
5255 struct diff_options *options = opt->value;
5256
5257 BUG_ON_OPT_NEG(unset);
5258 if (arg) {
5259 if (!strcmp(arg, "plain"))
5260 options->word_diff = DIFF_WORDS_PLAIN;
5261 else if (!strcmp(arg, "color")) {
5262 options->use_color = 1;
5263 options->word_diff = DIFF_WORDS_COLOR;
5264 }
5265 else if (!strcmp(arg, "porcelain"))
5266 options->word_diff = DIFF_WORDS_PORCELAIN;
5267 else if (!strcmp(arg, "none"))
5268 options->word_diff = DIFF_WORDS_NONE;
5269 else
5270 return error(_("bad --word-diff argument: %s"), arg);
5271 } else {
5272 if (options->word_diff == DIFF_WORDS_NONE)
5273 options->word_diff = DIFF_WORDS_PLAIN;
5274 }
5275 return 0;
5276}
5277
797df119
NTND
5278static int diff_opt_word_diff_regex(const struct option *opt,
5279 const char *arg, int unset)
5280{
5281 struct diff_options *options = opt->value;
5282
5283 BUG_ON_OPT_NEG(unset);
5284 if (options->word_diff == DIFF_WORDS_NONE)
5285 options->word_diff = DIFF_WORDS_PLAIN;
5286 options->word_regex = arg;
5287 return 0;
5288}
5289
4a288478
NTND
5290static void prep_parse_options(struct diff_options *options)
5291{
5292 struct option parseopts[] = {
cc013c22
NTND
5293 OPT_GROUP(N_("Diff output format options")),
5294 OPT_BITOP('p', "patch", &options->output_format,
5295 N_("generate patch"),
5296 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
e01df7a3
NTND
5297 OPT_BIT_F('s', "no-patch", &options->output_format,
5298 N_("suppress diff output"),
5299 DIFF_FORMAT_NO_OUTPUT, PARSE_OPT_NONEG),
cc013c22
NTND
5300 OPT_BITOP('u', NULL, &options->output_format,
5301 N_("generate patch"),
5302 DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
d473e2e0
NTND
5303 OPT_CALLBACK_F('U', "unified", options, N_("<n>"),
5304 N_("generate diffs with <n> lines context"),
8ef05193 5305 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_unified),
7fd9a1ba
NTND
5306 OPT_BOOL('W', "function-context", &options->flags.funccontext,
5307 N_("generate diffs with <n> lines context")),
ed881486
NTND
5308 OPT_BIT_F(0, "raw", &options->output_format,
5309 N_("generate the diff in raw format"),
5310 DIFF_FORMAT_RAW, PARSE_OPT_NONEG),
c659f303
NTND
5311 OPT_BITOP(0, "patch-with-raw", &options->output_format,
5312 N_("synonym for '-p --raw'"),
5313 DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW,
5314 DIFF_FORMAT_NO_OUTPUT),
e550f585
NTND
5315 OPT_BITOP(0, "patch-with-stat", &options->output_format,
5316 N_("synonym for '-p --stat'"),
5317 DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT,
5318 DIFF_FORMAT_NO_OUTPUT),
e5673620
NTND
5319 OPT_BIT_F(0, "numstat", &options->output_format,
5320 N_("machine friendly --stat"),
5321 DIFF_FORMAT_NUMSTAT, PARSE_OPT_NONEG),
5322 OPT_BIT_F(0, "shortstat", &options->output_format,
5323 N_("output only the last line of --stat"),
5324 DIFF_FORMAT_SHORTSTAT, PARSE_OPT_NONEG),
4ce7aab5
NTND
5325 OPT_CALLBACK_F('X', "dirstat", options, N_("<param1,param2>..."),
5326 N_("output the distribution of relative amount of changes for each sub-directory"),
5327 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5328 diff_opt_dirstat),
5329 OPT_CALLBACK_F(0, "cumulative", options, NULL,
5330 N_("synonym for --dirstat=cumulative"),
5331 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5332 diff_opt_dirstat),
5333 OPT_CALLBACK_F(0, "dirstat-by-file", options, N_("<param1,param2>..."),
5334 N_("synonym for --dirstat=files,param1,param2..."),
5335 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5336 diff_opt_dirstat),
fc6af3e9
NTND
5337 OPT_BIT_F(0, "check", &options->output_format,
5338 N_("warn if changes introduce conflict markers or whitespace errors"),
5339 DIFF_FORMAT_CHECKDIFF, PARSE_OPT_NONEG),
70a30417
NTND
5340 OPT_BIT_F(0, "summary", &options->output_format,
5341 N_("condensed summary such as creations, renames and mode changes"),
5342 DIFF_FORMAT_SUMMARY, PARSE_OPT_NONEG),
0e840e2a
NTND
5343 OPT_BIT_F(0, "name-only", &options->output_format,
5344 N_("show only names of changed files"),
5345 DIFF_FORMAT_NAME, PARSE_OPT_NONEG),
a2387472
NTND
5346 OPT_BIT_F(0, "name-status", &options->output_format,
5347 N_("show only names and status of changed files"),
5348 DIFF_FORMAT_NAME_STATUS, PARSE_OPT_NONEG),
84b5089e
NTND
5349 OPT_CALLBACK_F(0, "stat", options, N_("<width>[,<name-width>[,<count>]]"),
5350 N_("generate diffstat"),
5351 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_stat),
5352 OPT_CALLBACK_F(0, "stat-width", options, N_("<width>"),
5353 N_("generate diffstat with a given width"),
5354 PARSE_OPT_NONEG, diff_opt_stat),
5355 OPT_CALLBACK_F(0, "stat-name-width", options, N_("<width>"),
5356 N_("generate diffstat with a given name width"),
5357 PARSE_OPT_NONEG, diff_opt_stat),
5358 OPT_CALLBACK_F(0, "stat-graph-width", options, N_("<width>"),
5359 N_("generate diffstat with a given graph width"),
5360 PARSE_OPT_NONEG, diff_opt_stat),
5361 OPT_CALLBACK_F(0, "stat-count", options, N_("<count>"),
5362 N_("generate diffstat with limited lines"),
5363 PARSE_OPT_NONEG, diff_opt_stat),
7d7942b7
NTND
5364 OPT_CALLBACK_F(0, "compact-summary", options, NULL,
5365 N_("generate compact summary in diffstat"),
5366 PARSE_OPT_NOARG, diff_opt_compact_summary),
6d9af6f4
NTND
5367 OPT_CALLBACK_F(0, "binary", options, NULL,
5368 N_("output a binary diff that can be applied"),
5369 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_binary),
4fe01672
NTND
5370 OPT_BOOL(0, "full-index", &options->flags.full_index,
5371 N_("show full pre- and post-image object names on the \"index\" lines")),
8b81c26e
NTND
5372 OPT_COLOR_FLAG(0, "color", &options->use_color,
5373 N_("show colored diff")),
5a749d9f
NTND
5374 OPT_CALLBACK_F(0, "ws-error-highlight", options, N_("<kind>"),
5375 N_("highlight whitespace errors in the 'context', 'old' or 'new' lines in the diff"),
5376 PARSE_OPT_NONEG, diff_opt_ws_error_highlight),
1a1eb164
NTND
5377 OPT_SET_INT('z', NULL, &options->line_termination,
5378 N_("do not munge pathnames and use NULs as output field terminators in --raw or --numstat"),
5379 0),
d8774183 5380 OPT__ABBREV(&options->abbrev),
31fba9d3
NTND
5381 OPT_STRING_F(0, "src-prefix", &options->a_prefix, N_("<prefix>"),
5382 N_("show the given source prefix instead of \"a/\""),
5383 PARSE_OPT_NONEG),
5384 OPT_STRING_F(0, "dst-prefix", &options->b_prefix, N_("<prefix>"),
8a1569d6 5385 N_("show the given destination prefix instead of \"b/\""),
31fba9d3 5386 PARSE_OPT_NONEG),
2f81cf98
NTND
5387 OPT_CALLBACK_F(0, "line-prefix", options, N_("<prefix>"),
5388 N_("prepend an additional prefix to every line of output"),
5389 PARSE_OPT_NONEG, diff_opt_line_prefix),
11c659d8
NTND
5390 OPT_CALLBACK_F(0, "no-prefix", options, NULL,
5391 N_("do not show any source or destination prefix"),
5392 PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_no_prefix),
16ed6c97
NTND
5393 OPT_INTEGER_F(0, "inter-hunk-context", &options->interhunkcontext,
5394 N_("show context between diff hunks up to the specified number of lines"),
5395 PARSE_OPT_NONEG),
af2f3680
NTND
5396 OPT_CALLBACK_F(0, "output-indicator-new",
5397 &options->output_indicators[OUTPUT_INDICATOR_NEW],
5398 N_("<char>"),
5399 N_("specify the character to indicate a new line instead of '+'"),
5400 PARSE_OPT_NONEG, diff_opt_char),
5401 OPT_CALLBACK_F(0, "output-indicator-old",
5402 &options->output_indicators[OUTPUT_INDICATOR_OLD],
5403 N_("<char>"),
5404 N_("specify the character to indicate an old line instead of '-'"),
5405 PARSE_OPT_NONEG, diff_opt_char),
5406 OPT_CALLBACK_F(0, "output-indicator-context",
5407 &options->output_indicators[OUTPUT_INDICATOR_CONTEXT],
5408 N_("<char>"),
5409 N_("specify the character to indicate a context instead of ' '"),
5410 PARSE_OPT_NONEG, diff_opt_char),
5411
ced4e179
NTND
5412 OPT_GROUP(N_("Diff rename options")),
5413 OPT_CALLBACK_F('B', "break-rewrites", &options->break_opt, N_("<n>[/<m>]"),
5414 N_("break complete rewrite changes into pairs of delete and create"),
5415 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5416 diff_opt_break_rewrites),
f476308b
NTND
5417 OPT_CALLBACK_F('M', "find-renames", options, N_("<n>"),
5418 N_("detect renames"),
5419 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5420 diff_opt_find_renames),
1e533296
NTND
5421 OPT_SET_INT_F('D', "irreversible-delete", &options->irreversible_delete,
5422 N_("omit the preimage for deletes"),
5423 1, PARSE_OPT_NONEG),
7f64850d
NTND
5424 OPT_CALLBACK_F('C', "find-copies", options, N_("<n>"),
5425 N_("detect copies"),
5426 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5427 diff_opt_find_copies),
bdd4741b
NTND
5428 OPT_BOOL(0, "find-copies-harder", &options->flags.find_copies_harder,
5429 N_("use unmodified files as source to find copies")),
cdc43eb0
NTND
5430 OPT_SET_INT_F(0, "no-renames", &options->detect_rename,
5431 N_("disable rename detection"),
5432 0, PARSE_OPT_NONEG),
5433 OPT_BOOL(0, "rename-empty", &options->flags.rename_empty,
5434 N_("use empty blobs as rename source")),
1e9250b5
NTND
5435 OPT_CALLBACK_F(0, "follow", options, NULL,
5436 N_("continue listing the history of a file beyond renames"),
5437 PARSE_OPT_NOARG, diff_opt_follow),
bffee749
NTND
5438 OPT_INTEGER('l', NULL, &options->rename_limit,
5439 N_("prevent rename/copy detection if the number of rename/copy targets exceeds given limit")),
ced4e179 5440
2e75f922
NTND
5441 OPT_GROUP(N_("Diff algorithm options")),
5442 OPT_BIT(0, "minimal", &options->xdl_opts,
5443 N_("produce the smallest possible diff"),
5444 XDF_NEED_MINIMAL),
87649a16
NTND
5445 OPT_BIT_F('w', "ignore-all-space", &options->xdl_opts,
5446 N_("ignore whitespace when comparing lines"),
5447 XDF_IGNORE_WHITESPACE, PARSE_OPT_NONEG),
5448 OPT_BIT_F('b', "ignore-space-change", &options->xdl_opts,
5449 N_("ignore changes in amount of whitespace"),
5450 XDF_IGNORE_WHITESPACE_CHANGE, PARSE_OPT_NONEG),
5451 OPT_BIT_F(0, "ignore-space-at-eol", &options->xdl_opts,
5452 N_("ignore changes in whitespace at EOL"),
5453 XDF_IGNORE_WHITESPACE_AT_EOL, PARSE_OPT_NONEG),
5454 OPT_BIT_F(0, "ignore-cr-at-eol", &options->xdl_opts,
5455 N_("ignore carrier-return at the end of line"),
5456 XDF_IGNORE_CR_AT_EOL, PARSE_OPT_NONEG),
5457 OPT_BIT_F(0, "ignore-blank-lines", &options->xdl_opts,
5458 N_("ignore changes whose lines are all blank"),
5459 XDF_IGNORE_BLANK_LINES, PARSE_OPT_NONEG),
06f77518
NTND
5460 OPT_BIT(0, "indent-heuristic", &options->xdl_opts,
5461 N_("heuristic to shift diff hunk boundaries for easy reading"),
5462 XDF_INDENT_HEURISTIC),
31fd640e
NTND
5463 OPT_CALLBACK_F(0, "patience", options, NULL,
5464 N_("generate diff using the \"patience diff\" algorithm"),
5465 PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5466 diff_opt_patience),
f1e68ef5
NTND
5467 OPT_BITOP(0, "histogram", &options->xdl_opts,
5468 N_("generate diff using the \"histogram diff\" algorithm"),
5469 XDF_HISTOGRAM_DIFF, XDF_DIFF_ALGORITHM_MASK),
10f35b1c
NTND
5470 OPT_CALLBACK_F(0, "diff-algorithm", options, N_("<algorithm>"),
5471 N_("choose a diff algorithm"),
5472 PARSE_OPT_NONEG, diff_opt_diff_algorithm),
df84a436
NTND
5473 OPT_CALLBACK_F(0, "anchored", options, N_("<text>"),
5474 N_("generate diff using the \"anchored diff\" algorithm"),
5475 PARSE_OPT_NONEG, diff_opt_anchored),
e9fb39b6
NTND
5476 OPT_CALLBACK_F(0, "word-diff", options, N_("<mode>"),
5477 N_("show word diff, using <mode> to delimit changed words"),
5478 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_word_diff),
797df119
NTND
5479 OPT_CALLBACK_F(0, "word-diff-regex", options, N_("<regex>"),
5480 N_("use <regex> to decide what a word is"),
5481 PARSE_OPT_NONEG, diff_opt_word_diff_regex),
212db69d
NTND
5482 OPT_CALLBACK_F(0, "color-words", options, N_("<regex>"),
5483 N_("equivalent to --word-diff=color --word-diff-regex=<regex>"),
5484 PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_color_words),
59311a98 5485 OPT_CALLBACK_F(0, "color-moved", options, N_("<mode>"),
8bcd8f4c 5486 N_("moved lines of code are colored differently"),
59311a98 5487 PARSE_OPT_OPTARG, diff_opt_color_moved),
8ce2020f
NTND
5488 OPT_CALLBACK_F(0, "color-moved-ws", options, N_("<mode>"),
5489 N_("how white spaces are ignored in --color-moved"),
bb987290 5490 0, diff_opt_color_moved_ws),
2e75f922 5491
8bcd8f4c 5492 OPT_GROUP(N_("Other diff options")),
0b1c5b59
NTND
5493 OPT_CALLBACK_F(0, "relative", options, N_("<prefix>"),
5494 N_("when run from subdir, exclude changes outside and show relative paths"),
5495 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5496 diff_opt_relative),
c37d4c0a
NTND
5497 OPT_BOOL('a', "text", &options->flags.text,
5498 N_("treat all files as text")),
4f99f299
NTND
5499 OPT_BOOL('R', NULL, &options->flags.reverse_diff,
5500 N_("swap two inputs, reverse the diff")),
1086ea0c
NTND
5501 OPT_BOOL(0, "exit-code", &options->flags.exit_with_status,
5502 N_("exit with 1 if there were differences, 0 otherwise")),
9bbaf1ce
NTND
5503 OPT_BOOL(0, "quiet", &options->flags.quick,
5504 N_("disable all output of the program")),
0cda1003
NTND
5505 OPT_BOOL(0, "ext-diff", &options->flags.allow_external,
5506 N_("allow an external diff helper to be executed")),
8ab76977
NTND
5507 OPT_CALLBACK_F(0, "textconv", options, NULL,
5508 N_("run external text conversion filters when comparing binary files"),
5509 PARSE_OPT_NOARG, diff_opt_textconv),
b680ee14
NTND
5510 OPT_CALLBACK_F(0, "ignore-submodules", options, N_("<when>"),
5511 N_("ignore changes to submodules in the diff generation"),
5512 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5513 diff_opt_ignore_submodules),
125dcea9
NTND
5514 OPT_CALLBACK_F(0, "submodule", options, N_("<format>"),
5515 N_("specify how differences in submodules are shown"),
5516 PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5517 diff_opt_submodule),
96860e48
NTND
5518 OPT_SET_INT_F(0, "ita-invisible-in-index", &options->ita_invisible_in_index,
5519 N_("hide 'git add -N' entries from the index"),
5520 1, PARSE_OPT_NONEG),
5521 OPT_SET_INT_F(0, "ita-visible-in-index", &options->ita_invisible_in_index,
5522 N_("treat 'git add -N' entries as real in the index"),
5523 0, PARSE_OPT_NONEG),
a41cfb32
NTND
5524 OPT_CALLBACK_F('S', NULL, options, N_("<string>"),
5525 N_("look for differences that change the number of occurrences of the specified string"),
5526 0, diff_opt_pickaxe_string),
5527 OPT_CALLBACK_F('G', NULL, options, N_("<regex>"),
5528 N_("look for differences that change the number of occurrences of the specified regex"),
5529 0, diff_opt_pickaxe_regex),
85f8e889
NTND
5530 OPT_BIT_F(0, "pickaxe-all", &options->pickaxe_opts,
5531 N_("show all changes in the changeset with -S or -G"),
5532 DIFF_PICKAXE_ALL, PARSE_OPT_NONEG),
5533 OPT_BIT_F(0, "pickaxe-regex", &options->pickaxe_opts,
5534 N_("treat <string> in -S as extended POSIX regular expression"),
5535 DIFF_PICKAXE_REGEX, PARSE_OPT_NONEG),
f731814b
NTND
5536 OPT_FILENAME('O', NULL, &options->orderfile,
5537 N_("control the order in which files appear in the output")),
a75f28cb
NTND
5538 OPT_CALLBACK_F(0, "find-object", options, N_("<object-id>"),
5539 N_("look for differences that change the number of occurrences of the specified object"),
5540 PARSE_OPT_NONEG, diff_opt_find_object),
d2d3f273
NTND
5541 OPT_CALLBACK_F(0, "diff-filter", options, N_("[(A|C|D|M|R|T|U|X|B)...[*]]"),
5542 N_("select files by diff type"),
5543 PARSE_OPT_NONEG, diff_opt_diff_filter),
af2f3680
NTND
5544 { OPTION_CALLBACK, 0, "output", options, N_("<file>"),
5545 N_("Output to a specific file"),
5546 PARSE_OPT_NONEG, NULL, 0, diff_opt_output },
5547
4a288478
NTND
5548 OPT_END()
5549 };
5550
5551 ALLOC_ARRAY(options->parseopts, ARRAY_SIZE(parseopts));
5552 memcpy(options->parseopts, parseopts, sizeof(parseopts));
5553}
5554
a97262c6
NTND
5555int diff_opt_parse(struct diff_options *options,
5556 const char **av, int ac, const char *prefix)
6973dcae 5557{
a97262c6
NTND
5558 if (!prefix)
5559 prefix = "";
5560
4a288478
NTND
5561 ac = parse_options(ac, av, prefix, options->parseopts, NULL,
5562 PARSE_OPT_KEEP_DASHDASH |
5563 PARSE_OPT_KEEP_UNKNOWN |
5564 PARSE_OPT_NO_INTERNAL_HELP |
5565 PARSE_OPT_ONE_SHOT |
5566 PARSE_OPT_STOP_AT_NON_OPTION);
5567
8ce2020f 5568 return ac;
6973dcae
JH
5569}
5570
10ae7526 5571int parse_rename_score(const char **cp_p)
6973dcae
JH
5572{
5573 unsigned long num, scale;
5574 int ch, dot;
5575 const char *cp = *cp_p;
5576
5577 num = 0;
5578 scale = 1;
5579 dot = 0;
eeefa7c9 5580 for (;;) {
6973dcae
JH
5581 ch = *cp;
5582 if ( !dot && ch == '.' ) {
5583 scale = 1;
5584 dot = 1;
5585 } else if ( ch == '%' ) {
5586 scale = dot ? scale*100 : 100;
5587 cp++; /* % is always at the end */
5588 break;
5589 } else if ( ch >= '0' && ch <= '9' ) {
5590 if ( scale < 100000 ) {
5591 scale *= 10;
5592 num = (num*10) + (ch-'0');
5593 }
5594 } else {
5595 break;
5596 }
5597 cp++;
5598 }
5599 *cp_p = cp;
5600
5601 /* user says num divided by scale and we say internally that
5602 * is MAX_SCORE * num / scale.
5603 */
dc49cd76 5604 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
6973dcae
JH
5605}
5606
6973dcae
JH
5607struct diff_queue_struct diff_queued_diff;
5608
5609void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
5610{
4c960a43 5611 ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
6973dcae
JH
5612 queue->queue[queue->nr++] = dp;
5613}
5614
5615struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
5616 struct diff_filespec *one,
5617 struct diff_filespec *two)
5618{
ef677686 5619 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
6973dcae
JH
5620 dp->one = one;
5621 dp->two = two;
6973dcae
JH
5622 if (queue)
5623 diff_q(queue, dp);
5624 return dp;
5625}
5626
5627void diff_free_filepair(struct diff_filepair *p)
5628{
9fb88419
LT
5629 free_filespec(p->one);
5630 free_filespec(p->two);
6973dcae
JH
5631 free(p);
5632}
5633
d6cece51 5634const char *diff_aligned_abbrev(const struct object_id *oid, int len)
6973dcae
JH
5635{
5636 int abblen;
5637 const char *abbrev;
6973dcae 5638
7cb6ac1e 5639 /* Do we want all 40 hex characters? */
02afca1e 5640 if (len == the_hash_algo->hexsz)
d6cece51
JK
5641 return oid_to_hex(oid);
5642
7cb6ac1e 5643 /* An abbreviated value is fine, possibly followed by an ellipsis. */
4f03666a 5644 abbrev = diff_abbrev_oid(oid, len);
7cb6ac1e
AR
5645
5646 if (!print_sha1_ellipsis())
5647 return abbrev;
5648
6973dcae 5649 abblen = strlen(abbrev);
d709f1fb
JH
5650
5651 /*
7cb6ac1e 5652 * In well-behaved cases, where the abbreviated result is the
d709f1fb
JH
5653 * same as the requested length, append three dots after the
5654 * abbreviation (hence the whole logic is limited to the case
5655 * where abblen < 37); when the actual abbreviated result is a
5656 * bit longer than the requested length, we reduce the number
5657 * of dots so that they match the well-behaved ones. However,
5658 * if the actual abbreviation is longer than the requested
5659 * length by more than three, we give up on aligning, and add
5660 * three dots anyway, to indicate that the output is not the
5661 * full object name. Yes, this may be suboptimal, but this
5662 * appears only in "diff --raw --abbrev" output and it is not
5663 * worth the effort to change it now. Note that this would
5664 * likely to work fine when the automatic sizing of default
5665 * abbreviation length is used--we would be fed -1 in "len" in
5666 * that case, and will end up always appending three-dots, but
5667 * the automatic sizing is supposed to give abblen that ensures
5668 * uniqueness across all objects (statistically speaking).
5669 */
02afca1e 5670 if (abblen < the_hash_algo->hexsz - 3) {
dc01505f 5671 static char hex[GIT_MAX_HEXSZ + 1];
6973dcae 5672 if (len < abblen && abblen <= len + 2)
5096d490 5673 xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
6973dcae 5674 else
5096d490 5675 xsnprintf(hex, sizeof(hex), "%s...", abbrev);
6973dcae
JH
5676 return hex;
5677 }
d6cece51
JK
5678
5679 return oid_to_hex(oid);
6973dcae
JH
5680}
5681
663af342 5682static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
6973dcae 5683{
663af342
PH
5684 int line_termination = opt->line_termination;
5685 int inter_name_termination = line_termination ? '\t' : '\0';
6973dcae 5686
30997bb8 5687 fprintf(opt->file, "%s", diff_line_prefix(opt));
663af342 5688 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
c0c77734 5689 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
d6cece51 5690 diff_aligned_abbrev(&p->one->oid, opt->abbrev));
a0d12c44 5691 fprintf(opt->file, "%s ",
d6cece51 5692 diff_aligned_abbrev(&p->two->oid, opt->abbrev));
6973dcae 5693 }
663af342 5694 if (p->score) {
c0c77734
DB
5695 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
5696 inter_name_termination);
663af342 5697 } else {
c0c77734 5698 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
6973dcae 5699 }
6973dcae 5700
cd676a51
JH
5701 if (p->status == DIFF_STATUS_COPIED ||
5702 p->status == DIFF_STATUS_RENAMED) {
5703 const char *name_a, *name_b;
5704 name_a = p->one->path;
5705 name_b = p->two->path;
5706 strip_prefix(opt->prefix_length, &name_a, &name_b);
c0c77734
DB
5707 write_name_quoted(name_a, opt->file, inter_name_termination);
5708 write_name_quoted(name_b, opt->file, line_termination);
663af342 5709 } else {
cd676a51
JH
5710 const char *name_a, *name_b;
5711 name_a = p->one->mode ? p->one->path : p->two->path;
5712 name_b = NULL;
5713 strip_prefix(opt->prefix_length, &name_a, &name_b);
c0c77734 5714 write_name_quoted(name_a, opt->file, line_termination);
663af342 5715 }
6973dcae
JH
5716}
5717
5718int diff_unmodified_pair(struct diff_filepair *p)
5719{
5720 /* This function is written stricter than necessary to support
5721 * the currently implemented transformers, but the idea is to
5722 * let transformers to produce diff_filepairs any way they want,
5723 * and filter and clean them up here before producing the output.
5724 */
663af342 5725 struct diff_filespec *one = p->one, *two = p->two;
6973dcae
JH
5726
5727 if (DIFF_PAIR_UNMERGED(p))
5728 return 0; /* unmerged is interesting */
5729
6973dcae
JH
5730 /* deletion, addition, mode or type change
5731 * and rename are all interesting.
5732 */
5733 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
5734 DIFF_PAIR_MODE_CHANGED(p) ||
5735 strcmp(one->path, two->path))
5736 return 0;
5737
5738 /* both are valid and point at the same path. that is, we are
5739 * dealing with a change.
5740 */
41c9560e 5741 if (one->oid_valid && two->oid_valid &&
4a7e27e9 5742 oideq(&one->oid, &two->oid) &&
85adbf2f 5743 !one->dirty_submodule && !two->dirty_submodule)
6973dcae 5744 return 1; /* no change */
41c9560e 5745 if (!one->oid_valid && !two->oid_valid)
6973dcae
JH
5746 return 1; /* both look at the same file on the filesystem. */
5747 return 0;
5748}
5749
5750static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
5751{
5752 if (diff_unmodified_pair(p))
5753 return;
5754
5755 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5756 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5757 return; /* no tree diffs in patch format */
5758
5759 run_diff(p, o);
5760}
5761
5762static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
5763 struct diffstat_t *diffstat)
5764{
5765 if (diff_unmodified_pair(p))
5766 return;
5767
5768 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5769 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
c3fced64 5770 return; /* no useful stat for tree diffs */
6973dcae
JH
5771
5772 run_diffstat(p, o, diffstat);
5773}
5774
88246898
JS
5775static void diff_flush_checkdiff(struct diff_filepair *p,
5776 struct diff_options *o)
5777{
5778 if (diff_unmodified_pair(p))
5779 return;
5780
5781 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5782 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
c3fced64 5783 return; /* nothing to check in tree diffs */
88246898
JS
5784
5785 run_checkdiff(p, o);
5786}
5787
6973dcae
JH
5788int diff_queue_is_empty(void)
5789{
5790 struct diff_queue_struct *q = &diff_queued_diff;
5791 int i;
5792 for (i = 0; i < q->nr; i++)
5793 if (!diff_unmodified_pair(q->queue[i]))
5794 return 0;
5795 return 1;
5796}
5797
5798#if DIFF_DEBUG
5799void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
5800{
5801 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
5802 x, one ? one : "",
5803 s->path,
5804 DIFF_FILE_VALID(s) ? "valid" : "invalid",
5805 s->mode,
41c9560e 5806 s->oid_valid ? oid_to_hex(&s->oid) : "");
428d52a5 5807 fprintf(stderr, "queue[%d] %s size %lu\n",
6973dcae 5808 x, one ? one : "",
428d52a5 5809 s->size);
6973dcae
JH
5810}
5811
5812void diff_debug_filepair(const struct diff_filepair *p, int i)
5813{
5814 diff_debug_filespec(p->one, i, "one");
5815 diff_debug_filespec(p->two, i, "two");
64479711 5816 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
6973dcae 5817 p->score, p->status ? p->status : '?',
64479711 5818 p->one->rename_used, p->broken_pair);
6973dcae
JH
5819}
5820
5821void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
5822{
5823 int i;
5824 if (msg)
5825 fprintf(stderr, "%s\n", msg);
5826 fprintf(stderr, "q->nr = %d\n", q->nr);
5827 for (i = 0; i < q->nr; i++) {
5828 struct diff_filepair *p = q->queue[i];
5829 diff_debug_filepair(p, i);
5830 }
5831}
5832#endif
5833
5834static void diff_resolve_rename_copy(void)
5835{
64479711
LT
5836 int i;
5837 struct diff_filepair *p;
6973dcae
JH
5838 struct diff_queue_struct *q = &diff_queued_diff;
5839
5840 diff_debug_queue("resolve-rename-copy", q);
5841
5842 for (i = 0; i < q->nr; i++) {
5843 p = q->queue[i];
5844 p->status = 0; /* undecided */
5845 if (DIFF_PAIR_UNMERGED(p))
5846 p->status = DIFF_STATUS_UNMERGED;
5847 else if (!DIFF_FILE_VALID(p->one))
5848 p->status = DIFF_STATUS_ADDED;
5849 else if (!DIFF_FILE_VALID(p->two))
5850 p->status = DIFF_STATUS_DELETED;
5851 else if (DIFF_PAIR_TYPE_CHANGED(p))
5852 p->status = DIFF_STATUS_TYPE_CHANGED;
5853
5854 /* from this point on, we are dealing with a pair
5855 * whose both sides are valid and of the same type, i.e.
5856 * either in-place edit or rename/copy edit.
5857 */
5858 else if (DIFF_PAIR_RENAME(p)) {
64479711
LT
5859 /*
5860 * A rename might have re-connected a broken
5861 * pair up, causing the pathnames to be the
5862 * same again. If so, that's not a rename at
5863 * all, just a modification..
5864 *
5865 * Otherwise, see if this source was used for
5866 * multiple renames, in which case we decrement
5867 * the count, and call it a copy.
6973dcae 5868 */
64479711
LT
5869 if (!strcmp(p->one->path, p->two->path))
5870 p->status = DIFF_STATUS_MODIFIED;
5871 else if (--p->one->rename_used > 0)
6973dcae 5872 p->status = DIFF_STATUS_COPIED;
64479711 5873 else
6973dcae
JH
5874 p->status = DIFF_STATUS_RENAMED;
5875 }
9001dc2a 5876 else if (!oideq(&p->one->oid, &p->two->oid) ||
d516c2d1 5877 p->one->mode != p->two->mode ||
85adbf2f
JL
5878 p->one->dirty_submodule ||
5879 p->two->dirty_submodule ||
a0d12c44 5880 is_null_oid(&p->one->oid))
6973dcae
JH
5881 p->status = DIFF_STATUS_MODIFIED;
5882 else {
5883 /* This is a "no-change" entry and should not
5884 * happen anymore, but prepare for broken callers.
5885 */
5886 error("feeding unmodified %s to diffcore",
5887 p->one->path);
5888 p->status = DIFF_STATUS_UNKNOWN;
5889 }
5890 }
5891 diff_debug_queue("resolve-rename-copy done", q);
5892}
5893
c6744349 5894static int check_pair_status(struct diff_filepair *p)
6973dcae 5895{
6973dcae
JH
5896 switch (p->status) {
5897 case DIFF_STATUS_UNKNOWN:
c6744349 5898 return 0;
6973dcae
JH
5899 case 0:
5900 die("internal error in diff-resolve-rename-copy");
6973dcae 5901 default:
c6744349 5902 return 1;
6973dcae
JH
5903 }
5904}
5905
c6744349
TH
5906static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
5907{
5908 int fmt = opt->output_format;
5909
5910 if (fmt & DIFF_FORMAT_CHECKDIFF)
5911 diff_flush_checkdiff(p, opt);
5912 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
5913 diff_flush_raw(p, opt);
cd676a51
JH
5914 else if (fmt & DIFF_FORMAT_NAME) {
5915 const char *name_a, *name_b;
5916 name_a = p->two->path;
5917 name_b = NULL;
5918 strip_prefix(opt->prefix_length, &name_a, &name_b);
f5022b5f 5919 fprintf(opt->file, "%s", diff_line_prefix(opt));
c0c77734 5920 write_name_quoted(name_a, opt->file, opt->line_termination);
cd676a51 5921 }
c6744349
TH
5922}
5923
146fdb0d 5924static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
4bbd261b 5925{
146fdb0d 5926 struct strbuf sb = STRBUF_INIT;
4bbd261b 5927 if (fs->mode)
146fdb0d 5928 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
4bbd261b 5929 else
146fdb0d 5930 strbuf_addf(&sb, " %s ", newdelete);
4bbd261b 5931
146fdb0d
SB
5932 quote_c_style(fs->path, &sb, NULL, 0);
5933 strbuf_addch(&sb, '\n');
5934 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5935 sb.buf, sb.len, 0);
5936 strbuf_release(&sb);
5937}
4bbd261b 5938
146fdb0d
SB
5939static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
5940 int show_name)
4bbd261b
SE
5941{
5942 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
146fdb0d
SB
5943 struct strbuf sb = STRBUF_INIT;
5944 strbuf_addf(&sb, " mode change %06o => %06o",
5945 p->one->mode, p->two->mode);
0d26a64e 5946 if (show_name) {
146fdb0d
SB
5947 strbuf_addch(&sb, ' ');
5948 quote_c_style(p->two->path, &sb, NULL, 0);
0d26a64e 5949 }
58aaced4 5950 strbuf_addch(&sb, '\n');
146fdb0d
SB
5951 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5952 sb.buf, sb.len, 0);
5953 strbuf_release(&sb);
4bbd261b
SE
5954 }
5955}
5956
146fdb0d
SB
5957static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
5958 struct diff_filepair *p)
4bbd261b 5959{
146fdb0d 5960 struct strbuf sb = STRBUF_INIT;
c905cbc4
NTND
5961 struct strbuf names = STRBUF_INIT;
5962
5963 pprint_rename(&names, p->one->path, p->two->path);
146fdb0d 5964 strbuf_addf(&sb, " %s %s (%d%%)\n",
c905cbc4
NTND
5965 renamecopy, names.buf, similarity_index(p));
5966 strbuf_release(&names);
146fdb0d
SB
5967 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5968 sb.buf, sb.len, 0);
5969 show_mode_change(opt, p, 0);
348eda24 5970 strbuf_release(&sb);
4bbd261b
SE
5971}
5972
7be57610 5973static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
4bbd261b
SE
5974{
5975 switch(p->status) {
5976 case DIFF_STATUS_DELETED:
146fdb0d 5977 show_file_mode_name(opt, "delete", p->one);
4bbd261b
SE
5978 break;
5979 case DIFF_STATUS_ADDED:
146fdb0d 5980 show_file_mode_name(opt, "create", p->two);
4bbd261b
SE
5981 break;
5982 case DIFF_STATUS_COPIED:
146fdb0d 5983 show_rename_copy(opt, "copy", p);
4bbd261b
SE
5984 break;
5985 case DIFF_STATUS_RENAMED:
146fdb0d 5986 show_rename_copy(opt, "rename", p);
4bbd261b
SE
5987 break;
5988 default:
5989 if (p->score) {
146fdb0d
SB
5990 struct strbuf sb = STRBUF_INIT;
5991 strbuf_addstr(&sb, " rewrite ");
5992 quote_c_style(p->two->path, &sb, NULL, 0);
5993 strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
5994 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5995 sb.buf, sb.len, 0);
fa842d84 5996 strbuf_release(&sb);
663af342 5997 }
146fdb0d 5998 show_mode_change(opt, p, !p->score);
4bbd261b
SE
5999 break;
6000 }
6001}
6002
fcb3d0ad 6003struct patch_id_t {
36261e42 6004 git_hash_ctx *ctx;
fcb3d0ad
JS
6005 int patchlen;
6006};
6007
6008static int remove_space(char *line, int len)
6009{
6010 int i;
663af342
PH
6011 char *dst = line;
6012 unsigned char c;
fcb3d0ad 6013
663af342
PH
6014 for (i = 0; i < len; i++)
6015 if (!isspace((c = line[i])))
6016 *dst++ = c;
fcb3d0ad 6017
663af342 6018 return dst - line;
fcb3d0ad
JS
6019}
6020
36261e42 6021void flush_one_hunk(struct object_id *result, git_hash_ctx *ctx)
a8f6855f
SB
6022{
6023 unsigned char hash[GIT_MAX_RAWSZ];
6024 unsigned short carry = 0;
6025 int i;
6026
36261e42 6027 the_hash_algo->final_fn(hash, ctx);
6028 the_hash_algo->init_fn(ctx);
a8f6855f 6029 /* 20-byte sum, with carry */
36261e42 6030 for (i = 0; i < the_hash_algo->rawsz; ++i) {
a8f6855f
SB
6031 carry += result->hash[i] + hash[i];
6032 result->hash[i] = carry;
6033 carry >>= 8;
6034 }
6035}
6036
fcb3d0ad
JS
6037static void patch_id_consume(void *priv, char *line, unsigned long len)
6038{
6039 struct patch_id_t *data = priv;
6040 int new_len;
6041
fcb3d0ad
JS
6042 new_len = remove_space(line, len);
6043
36261e42 6044 the_hash_algo->update_fn(data->ctx, line, new_len);
fcb3d0ad
JS
6045 data->patchlen += new_len;
6046}
6047
36261e42 6048static void patch_id_add_string(git_hash_ctx *ctx, const char *str)
977db6b4 6049{
36261e42 6050 the_hash_algo->update_fn(ctx, str, strlen(str));
977db6b4
JK
6051}
6052
36261e42 6053static void patch_id_add_mode(git_hash_ctx *ctx, unsigned mode)
977db6b4
JK
6054{
6055 /* large enough for 2^32 in octal */
6056 char buf[12];
6057 int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
36261e42 6058 the_hash_algo->update_fn(ctx, buf, len);
977db6b4
JK
6059}
6060
a8f6855f
SB
6061/* returns 0 upon success, and writes result into oid */
6062static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only, int stable)
fcb3d0ad
JS
6063{
6064 struct diff_queue_struct *q = &diff_queued_diff;
6065 int i;
36261e42 6066 git_hash_ctx ctx;
fcb3d0ad 6067 struct patch_id_t data;
fcb3d0ad 6068
36261e42 6069 the_hash_algo->init_fn(&ctx);
fcb3d0ad
JS
6070 memset(&data, 0, sizeof(struct patch_id_t));
6071 data.ctx = &ctx;
a8f6855f 6072 oidclr(oid);
fcb3d0ad
JS
6073
6074 for (i = 0; i < q->nr; i++) {
6075 xpparam_t xpp;
6076 xdemitconf_t xecfg;
fcb3d0ad
JS
6077 mmfile_t mf1, mf2;
6078 struct diff_filepair *p = q->queue[i];
6079 int len1, len2;
6080
9ccd0a88 6081 memset(&xpp, 0, sizeof(xpp));
30b25010 6082 memset(&xecfg, 0, sizeof(xecfg));
fcb3d0ad
JS
6083 if (p->status == 0)
6084 return error("internal diff status error");
6085 if (p->status == DIFF_STATUS_UNKNOWN)
6086 continue;
6087 if (diff_unmodified_pair(p))
6088 continue;
6089 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6090 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6091 continue;
6092 if (DIFF_PAIR_UNMERGED(p))
6093 continue;
6094
58bf2a4c
NTND
6095 diff_fill_oid_info(p->one, options->repo->index);
6096 diff_fill_oid_info(p->two, options->repo->index);
fcb3d0ad 6097
fcb3d0ad
JS
6098 len1 = remove_space(p->one->path, strlen(p->one->path));
6099 len2 = remove_space(p->two->path, strlen(p->two->path));
977db6b4
JK
6100 patch_id_add_string(&ctx, "diff--git");
6101 patch_id_add_string(&ctx, "a/");
36261e42 6102 the_hash_algo->update_fn(&ctx, p->one->path, len1);
977db6b4 6103 patch_id_add_string(&ctx, "b/");
36261e42 6104 the_hash_algo->update_fn(&ctx, p->two->path, len2);
977db6b4
JK
6105
6106 if (p->one->mode == 0) {
6107 patch_id_add_string(&ctx, "newfilemode");
6108 patch_id_add_mode(&ctx, p->two->mode);
6109 patch_id_add_string(&ctx, "---/dev/null");
6110 patch_id_add_string(&ctx, "+++b/");
36261e42 6111 the_hash_algo->update_fn(&ctx, p->two->path, len2);
977db6b4
JK
6112 } else if (p->two->mode == 0) {
6113 patch_id_add_string(&ctx, "deletedfilemode");
6114 patch_id_add_mode(&ctx, p->one->mode);
6115 patch_id_add_string(&ctx, "---a/");
36261e42 6116 the_hash_algo->update_fn(&ctx, p->one->path, len1);
977db6b4
JK
6117 patch_id_add_string(&ctx, "+++/dev/null");
6118 } else {
6119 patch_id_add_string(&ctx, "---a/");
36261e42 6120 the_hash_algo->update_fn(&ctx, p->one->path, len1);
977db6b4 6121 patch_id_add_string(&ctx, "+++b/");
36261e42 6122 the_hash_algo->update_fn(&ctx, p->two->path, len2);
977db6b4 6123 }
fcb3d0ad 6124
3e8e32c3
KW
6125 if (diff_header_only)
6126 continue;
6127
b78ea5fc
NTND
6128 if (fill_mmfile(options->repo, &mf1, p->one) < 0 ||
6129 fill_mmfile(options->repo, &mf2, p->two) < 0)
3e8e32c3
KW
6130 return error("unable to read files to diff");
6131
b78ea5fc
NTND
6132 if (diff_filespec_is_binary(options->repo, p->one) ||
6133 diff_filespec_is_binary(options->repo, p->two)) {
36261e42 6134 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->one->oid),
6135 the_hash_algo->hexsz);
6136 the_hash_algo->update_fn(&ctx, oid_to_hex(&p->two->oid),
6137 the_hash_algo->hexsz);
34597c1f
CB
6138 continue;
6139 }
6140
582aa00b 6141 xpp.flags = 0;
fcb3d0ad 6142 xecfg.ctxlen = 3;
ad14b450 6143 xecfg.flags = 0;
b1357391
JK
6144 if (xdi_diff_outf(&mf1, &mf2, discard_hunk_line,
6145 patch_id_consume, &data, &xpp, &xecfg))
3efb9880
JK
6146 return error("unable to generate patch-id diff for %s",
6147 p->one->path);
a8f6855f
SB
6148
6149 if (stable)
6150 flush_one_hunk(oid, &ctx);
fcb3d0ad
JS
6151 }
6152
a8f6855f 6153 if (!stable)
36261e42 6154 the_hash_algo->final_fn(oid->hash, &ctx);
a8f6855f 6155
fcb3d0ad
JS
6156 return 0;
6157}
6158
a8f6855f 6159int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only, int stable)
fcb3d0ad
JS
6160{
6161 struct diff_queue_struct *q = &diff_queued_diff;
6162 int i;
a8f6855f 6163 int result = diff_get_patch_id(options, oid, diff_header_only, stable);
fcb3d0ad
JS
6164
6165 for (i = 0; i < q->nr; i++)
6166 diff_free_filepair(q->queue[i]);
6167
6168 free(q->queue);
9ca5df90 6169 DIFF_QUEUE_CLEAR(q);
fcb3d0ad
JS
6170
6171 return result;
6172}
6173
946c3784 6174static int is_summary_empty(const struct diff_queue_struct *q)
6973dcae 6175{
6973dcae 6176 int i;
6973dcae 6177
946c3784
TH
6178 for (i = 0; i < q->nr; i++) {
6179 const struct diff_filepair *p = q->queue[i];
6180
6181 switch (p->status) {
6182 case DIFF_STATUS_DELETED:
6183 case DIFF_STATUS_ADDED:
6184 case DIFF_STATUS_COPIED:
6185 case DIFF_STATUS_RENAMED:
6186 return 0;
6187 default:
6188 if (p->score)
6189 return 0;
6190 if (p->one->mode && p->two->mode &&
6191 p->one->mode != p->two->mode)
6192 return 0;
6193 break;
6194 }
6973dcae 6195 }
946c3784
TH
6196 return 1;
6197}
6198
f31027c9 6199static const char rename_limit_warning[] =
db424979 6200N_("inexact rename detection was skipped due to too many files.");
f31027c9
JH
6201
6202static const char degrade_cc_to_c_warning[] =
db424979 6203N_("only found copies from modified paths due to too many files.");
f31027c9
JH
6204
6205static const char rename_limit_advice[] =
db424979
VA
6206N_("you may want to set your %s variable to at least "
6207 "%d and retry the command.");
f31027c9
JH
6208
6209void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
6210{
4e056c98 6211 fflush(stdout);
f31027c9 6212 if (degraded_cc)
db424979 6213 warning(_(degrade_cc_to_c_warning));
f31027c9 6214 else if (needed)
db424979 6215 warning(_(rename_limit_warning));
f31027c9
JH
6216 else
6217 return;
9f7e4bfa 6218 if (0 < needed)
db424979 6219 warning(_(rename_limit_advice), varname, needed);
f31027c9
JH
6220}
6221
ec331506
SB
6222static void diff_flush_patch_all_file_pairs(struct diff_options *o)
6223{
6224 int i;
e6e045f8 6225 static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
ec331506 6226 struct diff_queue_struct *q = &diff_queued_diff;
091f8e28
SB
6227
6228 if (WSEH_NEW & WS_RULE_MASK)
033abf97 6229 BUG("WS rules bit mask overlaps with diff symbol flags");
091f8e28 6230
2e2d5ac1
SB
6231 if (o->color_moved)
6232 o->emitted_symbols = &esm;
e6e045f8 6233
ec331506
SB
6234 for (i = 0; i < q->nr; i++) {
6235 struct diff_filepair *p = q->queue[i];
6236 if (check_pair_status(p))
6237 diff_flush_patch(p, o);
6238 }
e6e045f8
SB
6239
6240 if (o->emitted_symbols) {
2e2d5ac1
SB
6241 if (o->color_moved) {
6242 struct hashmap add_lines, del_lines;
6243
ca1f4ae4
SB
6244 if (o->color_moved_ws_handling &
6245 COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
6246 o->color_moved_ws_handling |= XDF_IGNORE_WHITESPACE;
6247
ee1df66f
SB
6248 hashmap_init(&del_lines, moved_entry_cmp, o, 0);
6249 hashmap_init(&add_lines, moved_entry_cmp, o, 0);
2e2d5ac1
SB
6250
6251 add_lines_to_move_detection(o, &add_lines, &del_lines);
6252 mark_color_as_moved(o, &add_lines, &del_lines);
86b452e2
SB
6253 if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
6254 dim_moved_lines(o);
2e2d5ac1 6255
c8e424c9
EW
6256 hashmap_free_entries(&add_lines, struct moved_entry,
6257 ent);
6258 hashmap_free_entries(&del_lines, struct moved_entry,
6259 ent);
2e2d5ac1
SB
6260 }
6261
e6e045f8
SB
6262 for (i = 0; i < esm.nr; i++)
6263 emit_diff_symbol_from_struct(o, &esm.buf[i]);
6264
6265 for (i = 0; i < esm.nr; i++)
6266 free((void *)esm.buf[i].line);
48edf3a0
JK
6267 esm.nr = 0;
6268
6269 o->emitted_symbols = NULL;
e6e045f8 6270 }
ec331506
SB
6271}
6272
6973dcae
JH
6273void diff_flush(struct diff_options *options)
6274{
6275 struct diff_queue_struct *q = &diff_queued_diff;
c6744349 6276 int i, output_format = options->output_format;
946c3784 6277 int separator = 0;
1c57a627 6278 int dirstat_by_line = 0;
6973dcae 6279
c6744349
TH
6280 /*
6281 * Order: raw, stat, summary, patch
6282 * or: name/name-status/checkdiff (other bits clear)
6283 */
946c3784
TH
6284 if (!q->nr)
6285 goto free_queue;
6973dcae 6286
c6744349
TH
6287 if (output_format & (DIFF_FORMAT_RAW |
6288 DIFF_FORMAT_NAME |
6289 DIFF_FORMAT_NAME_STATUS |
6290 DIFF_FORMAT_CHECKDIFF)) {
6973dcae
JH
6291 for (i = 0; i < q->nr; i++) {
6292 struct diff_filepair *p = q->queue[i];
c6744349
TH
6293 if (check_pair_status(p))
6294 flush_one_pair(p, options);
6973dcae 6295 }
946c3784 6296 separator++;
6973dcae 6297 }
c6744349 6298
0d1e0e78 6299 if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
1c57a627
JH
6300 dirstat_by_line = 1;
6301
6302 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
6303 dirstat_by_line) {
5e2b0636 6304 struct diffstat_t diffstat;
c6744349 6305
e4cb659e 6306 compute_diffstat(options, &diffstat, q);
74e2abe5
JH
6307 if (output_format & DIFF_FORMAT_NUMSTAT)
6308 show_numstat(&diffstat, options);
6309 if (output_format & DIFF_FORMAT_DIFFSTAT)
6310 show_stats(&diffstat, options);
f604652e 6311 if (output_format & DIFF_FORMAT_SHORTSTAT)
c0c77734 6312 show_shortstats(&diffstat, options);
ab27389a 6313 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
1c57a627 6314 show_dirstat_by_line(&diffstat, options);
f604652e 6315 free_diffstat_info(&diffstat);
3969cf7d 6316 separator++;
6973dcae 6317 }
1c57a627 6318 if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
c04a7155 6319 show_dirstat(options);
6973dcae 6320
946c3784 6321 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
7be57610
BY
6322 for (i = 0; i < q->nr; i++) {
6323 diff_summary(options, q->queue[i]);
6324 }
3969cf7d 6325 separator++;
6973dcae
JH
6326 }
6327
6977c250 6328 if (output_format & DIFF_FORMAT_NO_OUTPUT &&
0d1e0e78
BW
6329 options->flags.exit_with_status &&
6330 options->flags.diff_from_contents) {
6977c250
LA
6331 /*
6332 * run diff_flush_patch for the exit status. setting
749f763d 6333 * options->file to /dev/null should be safe, because we
6977c250
LA
6334 * aren't supposed to produce any output anyway.
6335 */
6336 if (options->close_file)
6337 fclose(options->file);
23a9e071 6338 options->file = xfopen("/dev/null", "w");
6977c250 6339 options->close_file = 1;
2e2d5ac1 6340 options->color_moved = 0;
6977c250
LA
6341 for (i = 0; i < q->nr; i++) {
6342 struct diff_filepair *p = q->queue[i];
6343 if (check_pair_status(p))
6344 diff_flush_patch(p, options);
6345 if (options->found_changes)
6346 break;
6347 }
6348 }
6349
c6744349 6350 if (output_format & DIFF_FORMAT_PATCH) {
946c3784 6351 if (separator) {
091f8e28 6352 emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
30b7e1e7 6353 if (options->stat_sep)
946c3784 6354 /* attach patch instead of inline */
30b7e1e7
SB
6355 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
6356 NULL, 0, 0);
c6744349
TH
6357 }
6358
ec331506 6359 diff_flush_patch_all_file_pairs(options);
4bbd261b
SE
6360 }
6361
04245581
JK
6362 if (output_format & DIFF_FORMAT_CALLBACK)
6363 options->format_callback(q, options, options->format_callback_data);
6364
c6744349
TH
6365 for (i = 0; i < q->nr; i++)
6366 diff_free_filepair(q->queue[i]);
946c3784 6367free_queue:
6973dcae 6368 free(q->queue);
9ca5df90 6369 DIFF_QUEUE_CLEAR(q);
c0c77734
DB
6370 if (options->close_file)
6371 fclose(options->file);
f245194f
JH
6372
6373 /*
97bf2a08 6374 * Report the content-level differences with HAS_CHANGES;
f245194f
JH
6375 * diff_addremove/diff_change does not set the bit when
6376 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
6377 */
0d1e0e78 6378 if (options->flags.diff_from_contents) {
f245194f 6379 if (options->found_changes)
0d1e0e78 6380 options->flags.has_changes = 1;
f245194f 6381 else
0d1e0e78 6382 options->flags.has_changes = 0;
f245194f 6383 }
6973dcae
JH
6384}
6385
08578fa1
JH
6386static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
6387{
6388 return (((p->status == DIFF_STATUS_MODIFIED) &&
6389 ((p->score &&
1ecc1cbd 6390 filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
08578fa1 6391 (!p->score &&
1ecc1cbd 6392 filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
08578fa1 6393 ((p->status != DIFF_STATUS_MODIFIED) &&
1ecc1cbd 6394 filter_bit_tst(p->status, options)));
08578fa1
JH
6395}
6396
949226fe 6397static void diffcore_apply_filter(struct diff_options *options)
6973dcae
JH
6398{
6399 int i;
6400 struct diff_queue_struct *q = &diff_queued_diff;
6401 struct diff_queue_struct outq;
949226fe 6402
9ca5df90 6403 DIFF_QUEUE_CLEAR(&outq);
6973dcae 6404
1ecc1cbd 6405 if (!options->filter)
6973dcae
JH
6406 return;
6407
1ecc1cbd 6408 if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
6973dcae
JH
6409 int found;
6410 for (i = found = 0; !found && i < q->nr; i++) {
08578fa1 6411 if (match_filter(options, q->queue[i]))
6973dcae
JH
6412 found++;
6413 }
6414 if (found)
6415 return;
6416
6417 /* otherwise we will clear the whole queue
6418 * by copying the empty outq at the end of this
6419 * function, but first clear the current entries
6420 * in the queue.
6421 */
6422 for (i = 0; i < q->nr; i++)
6423 diff_free_filepair(q->queue[i]);
6424 }
6425 else {
6426 /* Only the matching ones */
6427 for (i = 0; i < q->nr; i++) {
6428 struct diff_filepair *p = q->queue[i];
08578fa1 6429 if (match_filter(options, p))
6973dcae
JH
6430 diff_q(&outq, p);
6431 else
6432 diff_free_filepair(p);
6433 }
6434 }
6435 free(q->queue);
6436 *q = outq;
6437}
6438
5701115a 6439/* Check whether two filespecs with the same mode and size are identical */
b78ea5fc
NTND
6440static int diff_filespec_is_identical(struct repository *r,
6441 struct diff_filespec *one,
5701115a
SV
6442 struct diff_filespec *two)
6443{
2b459b48
JH
6444 if (S_ISGITLINK(one->mode))
6445 return 0;
1c37e86a 6446 if (diff_populate_filespec(r, one, NULL))
5701115a 6447 return 0;
1c37e86a 6448 if (diff_populate_filespec(r, two, NULL))
5701115a
SV
6449 return 0;
6450 return !memcmp(one->data, two->data, one->size);
6451}
6452
b78ea5fc
NTND
6453static int diff_filespec_check_stat_unmatch(struct repository *r,
6454 struct diff_filepair *p)
fceb9072 6455{
1c37e86a
JT
6456 struct diff_populate_filespec_options dpf_options = {
6457 .check_size_only = 1,
95acf11a
JT
6458 .missing_object_cb = diff_queued_diff_prefetch,
6459 .missing_object_data = r,
1c37e86a
JT
6460 };
6461
f34b205f
NTND
6462 if (p->done_skip_stat_unmatch)
6463 return p->skip_stat_unmatch_result;
6464
6465 p->done_skip_stat_unmatch = 1;
6466 p->skip_stat_unmatch_result = 0;
fceb9072
NTND
6467 /*
6468 * 1. Entries that come from stat info dirtiness
6469 * always have both sides (iow, not create/delete),
6470 * one side of the object name is unknown, with
6471 * the same mode and size. Keep the ones that
6472 * do not match these criteria. They have real
6473 * differences.
6474 *
6475 * 2. At this point, the file is known to be modified,
6476 * with the same mode and size, and the object
6477 * name of one side is unknown. Need to inspect
6478 * the identical contents.
6479 */
6480 if (!DIFF_FILE_VALID(p->one) || /* (1) */
6481 !DIFF_FILE_VALID(p->two) ||
41c9560e 6482 (p->one->oid_valid && p->two->oid_valid) ||
fceb9072 6483 (p->one->mode != p->two->mode) ||
1c37e86a
JT
6484 diff_populate_filespec(r, p->one, &dpf_options) ||
6485 diff_populate_filespec(r, p->two, &dpf_options) ||
fceb9072 6486 (p->one->size != p->two->size) ||
b78ea5fc 6487 !diff_filespec_is_identical(r, p->one, p->two)) /* (2) */
f34b205f
NTND
6488 p->skip_stat_unmatch_result = 1;
6489 return p->skip_stat_unmatch_result;
fceb9072
NTND
6490}
6491
fb13227e
JH
6492static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
6493{
6494 int i;
6495 struct diff_queue_struct *q = &diff_queued_diff;
6496 struct diff_queue_struct outq;
9ca5df90 6497 DIFF_QUEUE_CLEAR(&outq);
fb13227e
JH
6498
6499 for (i = 0; i < q->nr; i++) {
6500 struct diff_filepair *p = q->queue[i];
6501
b78ea5fc 6502 if (diff_filespec_check_stat_unmatch(diffopt->repo, p))
fb13227e
JH
6503 diff_q(&outq, p);
6504 else {
6505 /*
6506 * The caller can subtract 1 from skip_stat_unmatch
6507 * to determine how many paths were dirty only
6508 * due to stat info mismatch.
6509 */
0d1e0e78 6510 if (!diffopt->flags.no_index)
6d2d9e86 6511 diffopt->skip_stat_unmatch++;
fb13227e
JH
6512 diff_free_filepair(p);
6513 }
6514 }
6515 free(q->queue);
6516 *q = outq;
6517}
6518
730f7284
JH
6519static int diffnamecmp(const void *a_, const void *b_)
6520{
6521 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
6522 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
6523 const char *name_a, *name_b;
6524
6525 name_a = a->one ? a->one->path : a->two->path;
6526 name_b = b->one ? b->one->path : b->two->path;
6527 return strcmp(name_a, name_b);
6528}
6529
784c0dae 6530void diffcore_fix_diff_index(void)
730f7284
JH
6531{
6532 struct diff_queue_struct *q = &diff_queued_diff;
9ed0d8d6 6533 QSORT(q->queue, q->nr, diffnamecmp);
730f7284
JH
6534}
6535
95acf11a
JT
6536void diff_add_if_missing(struct repository *r,
6537 struct oid_array *to_fetch,
6538 const struct diff_filespec *filespec)
7fbbcb21
JT
6539{
6540 if (filespec && filespec->oid_valid &&
a63694f5 6541 !S_ISGITLINK(filespec->mode) &&
7fbbcb21
JT
6542 oid_object_info_extended(r, &filespec->oid, NULL,
6543 OBJECT_INFO_FOR_PREFETCH))
6544 oid_array_append(to_fetch, &filespec->oid);
6545}
6546
95acf11a 6547void diff_queued_diff_prefetch(void *repository)
6973dcae 6548{
95acf11a
JT
6549 struct repository *repo = repository;
6550 int i;
6551 struct diff_queue_struct *q = &diff_queued_diff;
6552 struct oid_array to_fetch = OID_ARRAY_INIT;
7fbbcb21 6553
95acf11a
JT
6554 for (i = 0; i < q->nr; i++) {
6555 struct diff_filepair *p = q->queue[i];
6556 diff_add_if_missing(repo, &to_fetch, p->one);
6557 diff_add_if_missing(repo, &to_fetch, p->two);
7fbbcb21
JT
6558 }
6559
95acf11a
JT
6560 /*
6561 * NEEDSWORK: Consider deduplicating the OIDs sent.
6562 */
6563 promisor_remote_get_direct(repo, to_fetch.oid, to_fetch.nr);
6564
6565 oid_array_clear(&to_fetch);
6566}
6567
6568void diffcore_std(struct diff_options *options)
6569{
6570 int output_formats_to_prefetch = DIFF_FORMAT_DIFFSTAT |
6571 DIFF_FORMAT_NUMSTAT |
6572 DIFF_FORMAT_PATCH |
6573 DIFF_FORMAT_SHORTSTAT |
6574 DIFF_FORMAT_DIRSTAT;
6575
6576 /*
6577 * Check if the user requested a blob-data-requiring diff output and/or
6578 * break-rewrite detection (which requires blob data). If yes, prefetch
6579 * the diff pairs.
6580 *
6581 * If no prefetching occurs, diffcore_rename() will prefetch if it
6582 * decides that it needs inexact rename detection.
6583 */
6584 if (options->repo == the_repository && has_promisor_remote() &&
6585 (options->output_format & output_formats_to_prefetch ||
6586 options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
6587 diff_queued_diff_prefetch(options->repo);
6588
7195fbfa 6589 /* NOTE please keep the following in sync with diff_tree_combined() */
9d865356 6590 if (options->skip_stat_unmatch)
fb13227e 6591 diffcore_skip_stat_unmatch(options);
44c48a90
JH
6592 if (!options->found_follow) {
6593 /* See try_to_follow_renames() in tree-diff.c */
6594 if (options->break_opt != -1)
b78ea5fc
NTND
6595 diffcore_break(options->repo,
6596 options->break_opt);
44c48a90
JH
6597 if (options->detect_rename)
6598 diffcore_rename(options);
6599 if (options->break_opt != -1)
6600 diffcore_merge_broken();
6601 }
cf63051a 6602 if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
382f013b 6603 diffcore_pickaxe(options);
6973dcae
JH
6604 if (options->orderfile)
6605 diffcore_order(options->orderfile);
44c48a90
JH
6606 if (!options->found_follow)
6607 /* See try_to_follow_renames() in tree-diff.c */
6608 diff_resolve_rename_copy();
949226fe 6609 diffcore_apply_filter(options);
68aacb2f 6610
0d1e0e78
BW
6611 if (diff_queued_diff.nr && !options->flags.diff_from_contents)
6612 options->flags.has_changes = 1;
8f67f8ae 6613 else
0d1e0e78 6614 options->flags.has_changes = 0;
1da6175d 6615
44c48a90 6616 options->found_follow = 0;
6973dcae
JH
6617}
6618
da31b358
JH
6619int diff_result_code(struct diff_options *opt, int status)
6620{
6621 int result = 0;
f31027c9 6622
c9fc4415 6623 diff_warn_rename_limit("diff.renameLimit",
f31027c9
JH
6624 opt->needed_rename_limit,
6625 opt->degraded_cc_to_c);
0d1e0e78 6626 if (!opt->flags.exit_with_status &&
da31b358
JH
6627 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
6628 return status;
0d1e0e78
BW
6629 if (opt->flags.exit_with_status &&
6630 opt->flags.has_changes)
da31b358
JH
6631 result |= 01;
6632 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
0d1e0e78 6633 opt->flags.check_failed)
da31b358
JH
6634 result |= 02;
6635 return result;
6636}
6973dcae 6637
28b9264d
JH
6638int diff_can_quit_early(struct diff_options *opt)
6639{
0d1e0e78 6640 return (opt->flags.quick &&
28b9264d 6641 !opt->filter &&
0d1e0e78 6642 opt->flags.has_changes);
28b9264d
JH
6643}
6644
aee9c7d6
JL
6645/*
6646 * Shall changes to this submodule be ignored?
6647 *
6648 * Submodule changes can be configured to be ignored separately for each path,
6649 * but that configuration can be overridden from the command line.
6650 */
6651static int is_submodule_ignored(const char *path, struct diff_options *options)
6652{
6653 int ignored = 0;
02f2f56b 6654 struct diff_flags orig_flags = options->flags;
0d1e0e78 6655 if (!options->flags.override_submodule_config)
aee9c7d6 6656 set_diffopt_flags_from_submodule_config(options, path);
0d1e0e78 6657 if (options->flags.ignore_submodules)
aee9c7d6
JL
6658 ignored = 1;
6659 options->flags = orig_flags;
6660 return ignored;
6661}
6662
e4cb659e
DF
6663void compute_diffstat(struct diff_options *options,
6664 struct diffstat_t *diffstat,
6665 struct diff_queue_struct *q)
6666{
6667 int i;
6668
6669 memset(diffstat, 0, sizeof(struct diffstat_t));
6670 for (i = 0; i < q->nr; i++) {
6671 struct diff_filepair *p = q->queue[i];
6672 if (check_pair_status(p))
6673 diff_flush_stat(p, options, diffstat);
6674 }
6675}
6676
6973dcae
JH
6677void diff_addremove(struct diff_options *options,
6678 int addremove, unsigned mode,
c26022ea
BW
6679 const struct object_id *oid,
6680 int oid_valid,
e3d42c47 6681 const char *concatpath, unsigned dirty_submodule)
6973dcae 6682{
6973dcae
JH
6683 struct diff_filespec *one, *two;
6684
aee9c7d6 6685 if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
50fd9bd8
JS
6686 return;
6687
6973dcae
JH
6688 /* This may look odd, but it is a preparation for
6689 * feeding "there are unchanged files which should
6690 * not produce diffs, but when you are doing copy
6691 * detection you would need them, so here they are"
6692 * entries to the diff-core. They will be prefixed
6693 * with something like '=' or '*' (I haven't decided
6694 * which but should not make any difference).
a6080a0a 6695 * Feeding the same new and old to diff_change()
6973dcae
JH
6696 * also has the same effect.
6697 * Before the final output happens, they are pruned after
6698 * merged into rename/copy pairs as appropriate.
6699 */
0d1e0e78 6700 if (options->flags.reverse_diff)
6973dcae
JH
6701 addremove = (addremove == '+' ? '-' :
6702 addremove == '-' ? '+' : addremove);
6703
cd676a51
JH
6704 if (options->prefix &&
6705 strncmp(concatpath, options->prefix, options->prefix_length))
6706 return;
6707
6973dcae
JH
6708 one = alloc_filespec(concatpath);
6709 two = alloc_filespec(concatpath);
6710
6711 if (addremove != '+')
f9704c2d 6712 fill_filespec(one, oid, oid_valid, mode);
e3d42c47 6713 if (addremove != '-') {
f9704c2d 6714 fill_filespec(two, oid, oid_valid, mode);
e3d42c47
JL
6715 two->dirty_submodule = dirty_submodule;
6716 }
6973dcae
JH
6717
6718 diff_queue(&diff_queued_diff, one, two);
0d1e0e78
BW
6719 if (!options->flags.diff_from_contents)
6720 options->flags.has_changes = 1;
6973dcae
JH
6721}
6722
6723void diff_change(struct diff_options *options,
6724 unsigned old_mode, unsigned new_mode,
94a0097a
BW
6725 const struct object_id *old_oid,
6726 const struct object_id *new_oid,
6727 int old_oid_valid, int new_oid_valid,
e3d42c47
JL
6728 const char *concatpath,
6729 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
6973dcae 6730{
6973dcae 6731 struct diff_filespec *one, *two;
f34b205f 6732 struct diff_filepair *p;
6973dcae 6733
aee9c7d6
JL
6734 if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
6735 is_submodule_ignored(concatpath, options))
50fd9bd8
JS
6736 return;
6737
0d1e0e78 6738 if (options->flags.reverse_diff) {
35d803bc 6739 SWAP(old_mode, new_mode);
94a0097a
BW
6740 SWAP(old_oid, new_oid);
6741 SWAP(old_oid_valid, new_oid_valid);
35d803bc 6742 SWAP(old_dirty_submodule, new_dirty_submodule);
6973dcae 6743 }
cd676a51
JH
6744
6745 if (options->prefix &&
6746 strncmp(concatpath, options->prefix, options->prefix_length))
6747 return;
6748
6973dcae
JH
6749 one = alloc_filespec(concatpath);
6750 two = alloc_filespec(concatpath);
f9704c2d
BW
6751 fill_filespec(one, old_oid, old_oid_valid, old_mode);
6752 fill_filespec(two, new_oid, new_oid_valid, new_mode);
e3d42c47
JL
6753 one->dirty_submodule = old_dirty_submodule;
6754 two->dirty_submodule = new_dirty_submodule;
f34b205f 6755 p = diff_queue(&diff_queued_diff, one, two);
6973dcae 6756
0d1e0e78 6757 if (options->flags.diff_from_contents)
f34b205f
NTND
6758 return;
6759
0d1e0e78 6760 if (options->flags.quick && options->skip_stat_unmatch &&
b78ea5fc 6761 !diff_filespec_check_stat_unmatch(options->repo, p))
f34b205f
NTND
6762 return;
6763
0d1e0e78 6764 options->flags.has_changes = 1;
6973dcae
JH
6765}
6766
fa7b2908 6767struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
6973dcae 6768{
76399c01 6769 struct diff_filepair *pair;
6973dcae 6770 struct diff_filespec *one, *two;
cd676a51
JH
6771
6772 if (options->prefix &&
6773 strncmp(path, options->prefix, options->prefix_length))
76399c01 6774 return NULL;
cd676a51 6775
6973dcae
JH
6776 one = alloc_filespec(path);
6777 two = alloc_filespec(path);
76399c01
JH
6778 pair = diff_queue(&diff_queued_diff, one, two);
6779 pair->is_unmerged = 1;
6780 return pair;
6973dcae 6781}
9cb92c39 6782
b78ea5fc
NTND
6783static char *run_textconv(struct repository *r,
6784 const char *pgm,
6785 struct diff_filespec *spec,
6786 size_t *outsize)
9cb92c39 6787{
479b0ae8 6788 struct diff_tempfile *temp;
9cb92c39
JK
6789 const char *argv[3];
6790 const char **arg = argv;
d3180279 6791 struct child_process child = CHILD_PROCESS_INIT;
9cb92c39 6792 struct strbuf buf = STRBUF_INIT;
da1fbed3 6793 int err = 0;
9cb92c39 6794
b78ea5fc 6795 temp = prepare_temp_file(r, spec->path, spec);
9cb92c39 6796 *arg++ = pgm;
479b0ae8 6797 *arg++ = temp->name;
9cb92c39
JK
6798 *arg = NULL;
6799
41a457e4 6800 child.use_shell = 1;
9cb92c39
JK
6801 child.argv = argv;
6802 child.out = -1;
da1fbed3 6803 if (start_command(&child)) {
479b0ae8 6804 remove_tempfile();
9cb92c39
JK
6805 return NULL;
6806 }
da1fbed3
JS
6807
6808 if (strbuf_read(&buf, child.out, 0) < 0)
6809 err = error("error reading from textconv command '%s'", pgm);
70d70999 6810 close(child.out);
da1fbed3
JS
6811
6812 if (finish_command(&child) || err) {
6813 strbuf_release(&buf);
6814 remove_tempfile();
6815 return NULL;
6816 }
479b0ae8 6817 remove_tempfile();
9cb92c39
JK
6818
6819 return strbuf_detach(&buf, outsize);
6820}
840383b2 6821
6afaf807
NTND
6822size_t fill_textconv(struct repository *r,
6823 struct userdiff_driver *driver,
a788d7d5
AB
6824 struct diff_filespec *df,
6825 char **outbuf)
840383b2
JK
6826{
6827 size_t size;
6828
a64e6a44 6829 if (!driver) {
840383b2
JK
6830 if (!DIFF_FILE_VALID(df)) {
6831 *outbuf = "";
6832 return 0;
6833 }
1c37e86a 6834 if (diff_populate_filespec(r, df, NULL))
840383b2
JK
6835 die("unable to read files to diff");
6836 *outbuf = df->data;
6837 return df->size;
6838 }
6839
a64e6a44 6840 if (!driver->textconv)
033abf97 6841 BUG("fill_textconv called with non-textconv driver");
a64e6a44 6842
41c9560e 6843 if (driver->textconv_cache && df->oid_valid) {
a0d12c44 6844 *outbuf = notes_cache_get(driver->textconv_cache,
569aa376 6845 &df->oid,
d9bae1a1
JK
6846 &size);
6847 if (*outbuf)
6848 return size;
6849 }
6850
b78ea5fc 6851 *outbuf = run_textconv(r, driver->textconv, df, &size);
840383b2
JK
6852 if (!*outbuf)
6853 die("unable to read files to diff");
d9bae1a1 6854
41c9560e 6855 if (driver->textconv_cache && df->oid_valid) {
d9bae1a1 6856 /* ignore errors, as we might be in a readonly repository */
569aa376 6857 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
d9bae1a1
JK
6858 size);
6859 /*
6860 * we could save up changes and flush them all at the end,
6861 * but we would need an extra call after all diffing is done.
6862 * Since generating a cache entry is the slow path anyway,
6863 * this extra overhead probably isn't a big deal.
6864 */
6865 notes_cache_write(driver->textconv_cache);
6866 }
6867
840383b2
JK
6868 return size;
6869}
4914c962 6870
6afaf807
NTND
6871int textconv_object(struct repository *r,
6872 const char *path,
3a35cb2e
JS
6873 unsigned mode,
6874 const struct object_id *oid,
6875 int oid_valid,
6876 char **buf,
6877 unsigned long *buf_size)
6878{
6879 struct diff_filespec *df;
6880 struct userdiff_driver *textconv;
6881
6882 df = alloc_filespec(path);
a6f38c10 6883 fill_filespec(df, oid, oid_valid, mode);
bd7ad45b 6884 textconv = get_textconv(r, df);
3a35cb2e
JS
6885 if (!textconv) {
6886 free_filespec(df);
6887 return 0;
6888 }
6889
6afaf807 6890 *buf_size = fill_textconv(r, textconv, df, buf);
3a35cb2e
JS
6891 free_filespec(df);
6892 return 1;
6893}
6894
4914c962
NTND
6895void setup_diff_pager(struct diff_options *opt)
6896{
6897 /*
6898 * If the user asked for our exit code, then either they want --quiet
6899 * or --exit-code. We should definitely not bother with a pager in the
6900 * former case, as we will generate no output. Since we still properly
6901 * report our exit code even when a pager is run, we _could_ run a
6902 * pager with --exit-code. But since we have not done so historically,
6903 * and because it is easy to find people oneline advising "git diff
6904 * --exit-code" in hooks and other scripts, we do not do so.
6905 */
0d1e0e78 6906 if (!opt->flags.exit_with_status &&
4914c962
NTND
6907 check_pager_config("diff") != 0)
6908 setup_pager();
6909}