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