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