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