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