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