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