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