diff.c: factor advance_or_nullify out of mark_color_as_moved
[git/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"
be58e70d 16#include "userdiff.h"
851e18c3 17#include "submodule-config.h"
752c0c24 18#include "submodule.h"
2e2d5ac1 19#include "hashmap.h"
a757c646 20#include "ll-merge.h"
02e8ca0e 21#include "string-list.h"
82fbf269 22#include "argv-array.h"
660e113c 23#include "graph.h"
150e3001 24#include "packfile.h"
6973dcae 25
1510fea7
SP
26#ifdef NO_FAST_WORKING_DIRECTORY
27#define FAST_WORKING_DIRECTORY 0
28#else
29#define FAST_WORKING_DIRECTORY 1
30#endif
31
96f1e58f 32static int diff_detect_rename_default;
33de7163 33static int diff_indent_heuristic = 1;
92c57e5c 34static int diff_rename_limit_default = 400;
a624eaa7 35static int diff_suppress_blank_empty;
d2aea137 36static int diff_use_color_default = -1;
2e2d5ac1 37static int diff_color_moved_default;
6468a4e5 38static int diff_context_default = 3;
c4888677 39static int diff_interhunk_context_default;
98a4d87b 40static const char *diff_word_regex_cfg;
cbe02100 41static const char *external_diff_cmd_cfg;
6d8940b5 42static const char *diff_order_file_cfg;
aecbf914 43int diff_auto_refresh_index = 1;
a5a818ee 44static int diff_mnemonic_prefix;
f89504dd 45static int diff_no_prefix;
df44483a 46static int diff_stat_graph_width;
712d2c7d 47static int diff_dirstat_permille_default = 30;
be4f2b40 48static struct diff_options default_diff_options;
07ab4dec 49static long diff_algorithm;
a17505f2 50static unsigned ws_error_highlight_default = WSEH_NEW;
6973dcae 51
7c92fe0e 52static char diff_colors[][COLOR_MAXLEN] = {
dc6ebd4c 53 GIT_COLOR_RESET,
8dbf3eb6 54 GIT_COLOR_NORMAL, /* CONTEXT */
dc6ebd4c
AL
55 GIT_COLOR_BOLD, /* METAINFO */
56 GIT_COLOR_CYAN, /* FRAGINFO */
57 GIT_COLOR_RED, /* OLD */
58 GIT_COLOR_GREEN, /* NEW */
59 GIT_COLOR_YELLOW, /* COMMIT */
60 GIT_COLOR_BG_RED, /* WHITESPACE */
89cb73a1 61 GIT_COLOR_NORMAL, /* FUNCINFO */
86b452e2
SB
62 GIT_COLOR_BOLD_MAGENTA, /* OLD_MOVED */
63 GIT_COLOR_BOLD_BLUE, /* OLD_MOVED ALTERNATIVE */
64 GIT_COLOR_FAINT, /* OLD_MOVED_DIM */
65 GIT_COLOR_FAINT_ITALIC, /* OLD_MOVED_ALTERNATIVE_DIM */
66 GIT_COLOR_BOLD_CYAN, /* NEW_MOVED */
67 GIT_COLOR_BOLD_YELLOW, /* NEW_MOVED ALTERNATIVE */
68 GIT_COLOR_FAINT, /* NEW_MOVED_DIM */
69 GIT_COLOR_FAINT_ITALIC, /* NEW_MOVED_ALTERNATIVE_DIM */
cd112cef
JS
70};
71
a2f05c94
JNA
72static NORETURN void die_want_option(const char *option_name)
73{
74 die(_("option '%s' requires a value"), option_name);
75}
76
9e1a5ebe 77static int parse_diff_color_slot(const char *var)
801235c5 78{
74b15bfb 79 if (!strcasecmp(var, "context") || !strcasecmp(var, "plain"))
8dbf3eb6 80 return DIFF_CONTEXT;
9e1a5ebe 81 if (!strcasecmp(var, "meta"))
801235c5 82 return DIFF_METAINFO;
9e1a5ebe 83 if (!strcasecmp(var, "frag"))
801235c5 84 return DIFF_FRAGINFO;
9e1a5ebe 85 if (!strcasecmp(var, "old"))
801235c5 86 return DIFF_FILE_OLD;
9e1a5ebe 87 if (!strcasecmp(var, "new"))
801235c5 88 return DIFF_FILE_NEW;
9e1a5ebe 89 if (!strcasecmp(var, "commit"))
ce436973 90 return DIFF_COMMIT;
9e1a5ebe 91 if (!strcasecmp(var, "whitespace"))
448c3ef1 92 return DIFF_WHITESPACE;
9e1a5ebe 93 if (!strcasecmp(var, "func"))
89cb73a1 94 return DIFF_FUNCINFO;
2e2d5ac1
SB
95 if (!strcasecmp(var, "oldmoved"))
96 return DIFF_FILE_OLD_MOVED;
97 if (!strcasecmp(var, "oldmovedalternative"))
98 return DIFF_FILE_OLD_MOVED_ALT;
86b452e2
SB
99 if (!strcasecmp(var, "oldmoveddimmed"))
100 return DIFF_FILE_OLD_MOVED_DIM;
101 if (!strcasecmp(var, "oldmovedalternativedimmed"))
102 return DIFF_FILE_OLD_MOVED_ALT_DIM;
2e2d5ac1
SB
103 if (!strcasecmp(var, "newmoved"))
104 return DIFF_FILE_NEW_MOVED;
105 if (!strcasecmp(var, "newmovedalternative"))
106 return DIFF_FILE_NEW_MOVED_ALT;
86b452e2
SB
107 if (!strcasecmp(var, "newmoveddimmed"))
108 return DIFF_FILE_NEW_MOVED_DIM;
109 if (!strcasecmp(var, "newmovedalternativedimmed"))
110 return DIFF_FILE_NEW_MOVED_ALT_DIM;
8b8e8624 111 return -1;
801235c5
JH
112}
113
02e8ca0e 114static int parse_dirstat_params(struct diff_options *options, const char *params_string,
51670fc8 115 struct strbuf *errmsg)
333f3fb0 116{
02e8ca0e
MH
117 char *params_copy = xstrdup(params_string);
118 struct string_list params = STRING_LIST_INIT_NODUP;
119 int ret = 0;
120 int i;
51670fc8 121
02e8ca0e
MH
122 if (*params_copy)
123 string_list_split_in_place(&params, params_copy, ',', -1);
124 for (i = 0; i < params.nr; i++) {
125 const char *p = params.items[i].string;
126 if (!strcmp(p, "changes")) {
0d1e0e78
BW
127 options->flags.dirstat_by_line = 0;
128 options->flags.dirstat_by_file = 0;
02e8ca0e 129 } else if (!strcmp(p, "lines")) {
0d1e0e78
BW
130 options->flags.dirstat_by_line = 1;
131 options->flags.dirstat_by_file = 0;
02e8ca0e 132 } else if (!strcmp(p, "files")) {
0d1e0e78
BW
133 options->flags.dirstat_by_line = 0;
134 options->flags.dirstat_by_file = 1;
02e8ca0e 135 } else if (!strcmp(p, "noncumulative")) {
0d1e0e78 136 options->flags.dirstat_cumulative = 0;
02e8ca0e 137 } else if (!strcmp(p, "cumulative")) {
0d1e0e78 138 options->flags.dirstat_cumulative = 1;
333f3fb0
JH
139 } else if (isdigit(*p)) {
140 char *end;
51670fc8
JH
141 int permille = strtoul(p, &end, 10) * 10;
142 if (*end == '.' && isdigit(*++end)) {
712d2c7d 143 /* only use first digit */
51670fc8 144 permille += *end - '0';
712d2c7d 145 /* .. and ignore any further digits */
51670fc8 146 while (isdigit(*++end))
712d2c7d
JH
147 ; /* nothing */
148 }
02e8ca0e 149 if (!*end)
51670fc8
JH
150 options->dirstat_permille = permille;
151 else {
02e8ca0e
MH
152 strbuf_addf(errmsg, _(" Failed to parse dirstat cut-off percentage '%s'\n"),
153 p);
51670fc8
JH
154 ret++;
155 }
156 } else {
02e8ca0e 157 strbuf_addf(errmsg, _(" Unknown dirstat parameter '%s'\n"), p);
51670fc8 158 ret++;
333f3fb0 159 }
51670fc8 160
333f3fb0 161 }
02e8ca0e
MH
162 string_list_clear(&params, 0);
163 free(params_copy);
51670fc8 164 return ret;
333f3fb0
JH
165}
166
c47ef57c
RR
167static int parse_submodule_params(struct diff_options *options, const char *value)
168{
169 if (!strcmp(value, "log"))
61cfbc05 170 options->submodule_format = DIFF_SUBMODULE_LOG;
c47ef57c 171 else if (!strcmp(value, "short"))
61cfbc05 172 options->submodule_format = DIFF_SUBMODULE_SHORT;
fd47ae6a
JK
173 else if (!strcmp(value, "diff"))
174 options->submodule_format = DIFF_SUBMODULE_INLINE_DIFF;
c47ef57c
RR
175 else
176 return -1;
177 return 0;
178}
179
cced5fbc
LT
180static int git_config_rename(const char *var, const char *value)
181{
182 if (!value)
183 return DIFF_DETECT_RENAME;
184 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
185 return DIFF_DETECT_COPY;
186 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
187}
188
07924d4d 189long parse_algorithm_value(const char *value)
07ab4dec
MP
190{
191 if (!value)
192 return -1;
193 else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
194 return 0;
195 else if (!strcasecmp(value, "minimal"))
196 return XDF_NEED_MINIMAL;
197 else if (!strcasecmp(value, "patience"))
198 return XDF_PATIENCE_DIFF;
199 else if (!strcasecmp(value, "histogram"))
200 return XDF_HISTOGRAM_DIFF;
201 return -1;
202}
203
0b4b42e7
JH
204static int parse_one_token(const char **arg, const char *token)
205{
206 const char *rest;
207 if (skip_prefix(*arg, token, &rest) && (!*rest || *rest == ',')) {
208 *arg = rest;
209 return 1;
210 }
211 return 0;
212}
213
214static int parse_ws_error_highlight(const char *arg)
215{
216 const char *orig_arg = arg;
217 unsigned val = 0;
218
219 while (*arg) {
220 if (parse_one_token(&arg, "none"))
221 val = 0;
222 else if (parse_one_token(&arg, "default"))
223 val = WSEH_NEW;
224 else if (parse_one_token(&arg, "all"))
225 val = WSEH_NEW | WSEH_OLD | WSEH_CONTEXT;
226 else if (parse_one_token(&arg, "new"))
227 val |= WSEH_NEW;
228 else if (parse_one_token(&arg, "old"))
229 val |= WSEH_OLD;
230 else if (parse_one_token(&arg, "context"))
231 val |= WSEH_CONTEXT;
232 else {
233 return -1 - (int)(arg - orig_arg);
234 }
235 if (*arg)
236 arg++;
237 }
238 return val;
239}
240
83ad63cf
JH
241/*
242 * These are to give UI layer defaults.
243 * The core-level commands such as git-diff-files should
244 * never be affected by the setting of diff.renames
245 * the user happens to have in the configuration file.
246 */
5404c116
MM
247void init_diff_ui_defaults(void)
248{
06dba2b0 249 diff_detect_rename_default = DIFF_DETECT_RENAME;
5404c116
MM
250}
251
5b162879
MH
252int git_diff_heuristic_config(const char *var, const char *value, void *cb)
253{
3cde4e02 254 if (!strcmp(var, "diff.indentheuristic"))
5b162879 255 diff_indent_heuristic = git_config_bool(var, value);
5b162879
MH
256 return 0;
257}
258
2e2d5ac1
SB
259static int parse_color_moved(const char *arg)
260{
261 switch (git_parse_maybe_bool(arg)) {
262 case 0:
263 return COLOR_MOVED_NO;
264 case 1:
265 return COLOR_MOVED_DEFAULT;
266 default:
267 break;
268 }
269
270 if (!strcmp(arg, "no"))
271 return COLOR_MOVED_NO;
176841f0
SB
272 else if (!strcmp(arg, "plain"))
273 return COLOR_MOVED_PLAIN;
51da15eb
SB
274 else if (!strcmp(arg, "blocks"))
275 return COLOR_MOVED_BLOCKS;
2e2d5ac1
SB
276 else if (!strcmp(arg, "zebra"))
277 return COLOR_MOVED_ZEBRA;
278 else if (!strcmp(arg, "default"))
279 return COLOR_MOVED_DEFAULT;
86b452e2
SB
280 else if (!strcmp(arg, "dimmed_zebra"))
281 return COLOR_MOVED_ZEBRA_DIM;
2e2d5ac1 282 else
51da15eb 283 return error(_("color moved setting must be one of 'no', 'default', 'blocks', 'zebra', 'dimmed_zebra', 'plain'"));
2e2d5ac1
SB
284}
285
b3095712
SB
286static int parse_color_moved_ws(const char *arg)
287{
288 int ret = 0;
289 struct string_list l = STRING_LIST_INIT_DUP;
290 struct string_list_item *i;
291
292 string_list_split(&l, arg, ',', -1);
293
294 for_each_string_list_item(i, &l) {
295 struct strbuf sb = STRBUF_INIT;
296 strbuf_addstr(&sb, i->string);
297 strbuf_trim(&sb);
298
299 if (!strcmp(sb.buf, "ignore-space-change"))
300 ret |= XDF_IGNORE_WHITESPACE_CHANGE;
301 else if (!strcmp(sb.buf, "ignore-space-at-eol"))
302 ret |= XDF_IGNORE_WHITESPACE_AT_EOL;
303 else if (!strcmp(sb.buf, "ignore-all-space"))
304 ret |= XDF_IGNORE_WHITESPACE;
305 else
306 error(_("ignoring unknown color-moved-ws mode '%s'"), sb.buf);
307
308 strbuf_release(&sb);
309 }
310
311 string_list_clear(&l, 0);
312
313 return ret;
314}
315
ef90d6d4 316int git_diff_ui_config(const char *var, const char *value, void *cb)
801235c5 317{
a159ca0c 318 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
e269eb79 319 diff_use_color_default = git_config_colorbool(var, value);
801235c5
JH
320 return 0;
321 }
2e2d5ac1
SB
322 if (!strcmp(var, "diff.colormoved")) {
323 int cm = parse_color_moved(value);
324 if (cm < 0)
325 return -1;
326 diff_color_moved_default = cm;
327 return 0;
328 }
6468a4e5
JM
329 if (!strcmp(var, "diff.context")) {
330 diff_context_default = git_config_int(var, value);
331 if (diff_context_default < 0)
332 return -1;
333 return 0;
334 }
c4888677
VN
335 if (!strcmp(var, "diff.interhunkcontext")) {
336 diff_interhunk_context_default = git_config_int(var, value);
337 if (diff_interhunk_context_default < 0)
338 return -1;
339 return 0;
340 }
b68ea12e 341 if (!strcmp(var, "diff.renames")) {
cced5fbc 342 diff_detect_rename_default = git_config_rename(var, value);
b68ea12e
EW
343 return 0;
344 }
aecbf914
JH
345 if (!strcmp(var, "diff.autorefreshindex")) {
346 diff_auto_refresh_index = git_config_bool(var, value);
347 return 0;
348 }
a5a818ee
JH
349 if (!strcmp(var, "diff.mnemonicprefix")) {
350 diff_mnemonic_prefix = git_config_bool(var, value);
351 return 0;
352 }
f89504dd
EC
353 if (!strcmp(var, "diff.noprefix")) {
354 diff_no_prefix = git_config_bool(var, value);
355 return 0;
356 }
df44483a
ZJS
357 if (!strcmp(var, "diff.statgraphwidth")) {
358 diff_stat_graph_width = git_config_int(var, value);
359 return 0;
360 }
daec808c
BH
361 if (!strcmp(var, "diff.external"))
362 return git_config_string(&external_diff_cmd_cfg, var, value);
98a4d87b
BSSJ
363 if (!strcmp(var, "diff.wordregex"))
364 return git_config_string(&diff_word_regex_cfg, var, value);
6d8940b5
SB
365 if (!strcmp(var, "diff.orderfile"))
366 return git_config_pathname(&diff_order_file_cfg, var, value);
f1af60bd 367
be4f2b40
JS
368 if (!strcmp(var, "diff.ignoresubmodules"))
369 handle_ignore_submodules_arg(&default_diff_options, value);
370
c47ef57c
RR
371 if (!strcmp(var, "diff.submodule")) {
372 if (parse_submodule_params(&default_diff_options, value))
373 warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
374 value);
375 return 0;
376 }
377
07ab4dec
MP
378 if (!strcmp(var, "diff.algorithm")) {
379 diff_algorithm = parse_algorithm_value(value);
380 if (diff_algorithm < 0)
381 return -1;
382 return 0;
383 }
384
a17505f2
JH
385 if (!strcmp(var, "diff.wserrorhighlight")) {
386 int val = parse_ws_error_highlight(value);
387 if (val < 0)
388 return -1;
389 ws_error_highlight_default = val;
390 return 0;
391 }
392
33c643bb
JK
393 if (git_color_config(var, value, cb) < 0)
394 return -1;
395
ef90d6d4 396 return git_diff_basic_config(var, value, cb);
9a1805a8
JK
397}
398
ef90d6d4 399int git_diff_basic_config(const char *var, const char *value, void *cb)
9a1805a8 400{
ae021d87
JK
401 const char *name;
402
2b6ca6df
LT
403 if (!strcmp(var, "diff.renamelimit")) {
404 diff_rename_limit_default = git_config_int(var, value);
405 return 0;
406 }
407
6680a087
JK
408 if (userdiff_config(var, value) < 0)
409 return -1;
c7534ef4 410
ae021d87
JK
411 if (skip_prefix(var, "diff.color.", &name) ||
412 skip_prefix(var, "color.diff.", &name)) {
413 int slot = parse_diff_color_slot(name);
8b8e8624
JK
414 if (slot < 0)
415 return 0;
64f30e94
JH
416 if (!value)
417 return config_error_nonbool(var);
f6c5a296 418 return color_parse(value, diff_colors[slot]);
801235c5 419 }
f1af60bd 420
a624eaa7 421 /* like GNU diff's --suppress-blank-empty option */
950db879
JS
422 if (!strcmp(var, "diff.suppressblankempty") ||
423 /* for backwards compatibility */
424 !strcmp(var, "diff.suppress-blank-empty")) {
a624eaa7
JM
425 diff_suppress_blank_empty = git_config_bool(var, value);
426 return 0;
427 }
428
2d174951 429 if (!strcmp(var, "diff.dirstat")) {
51670fc8 430 struct strbuf errmsg = STRBUF_INIT;
712d2c7d 431 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
51670fc8 432 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
7478ac57 433 warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
51670fc8
JH
434 errmsg.buf);
435 strbuf_release(&errmsg);
712d2c7d 436 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
2d174951
JH
437 return 0;
438 }
439
cf5e7722
MB
440 if (git_diff_heuristic_config(var, value, cb) < 0)
441 return -1;
442
3e1dd17a 443 return git_default_config(var, value, cb);
801235c5
JH
444}
445
6973dcae
JH
446static char *quote_two(const char *one, const char *two)
447{
448 int need_one = quote_c_style(one, NULL, NULL, 1);
449 int need_two = quote_c_style(two, NULL, NULL, 1);
f285a2d7 450 struct strbuf res = STRBUF_INIT;
6973dcae
JH
451
452 if (need_one + need_two) {
663af342
PH
453 strbuf_addch(&res, '"');
454 quote_c_style(one, &res, NULL, 1);
455 quote_c_style(two, &res, NULL, 1);
456 strbuf_addch(&res, '"');
457 } else {
458 strbuf_addstr(&res, one);
459 strbuf_addstr(&res, two);
6973dcae 460 }
b315c5c0 461 return strbuf_detach(&res, NULL);
6973dcae
JH
462}
463
464static const char *external_diff(void)
465{
466 static const char *external_diff_cmd = NULL;
467 static int done_preparing = 0;
468
469 if (done_preparing)
470 return external_diff_cmd;
471 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
cbe02100
JS
472 if (!external_diff_cmd)
473 external_diff_cmd = external_diff_cmd_cfg;
6973dcae
JH
474 done_preparing = 1;
475 return external_diff_cmd;
476}
477
284098f1
MH
478/*
479 * Keep track of files used for diffing. Sometimes such an entry
480 * refers to a temporary file, sometimes to an existing file, and
481 * sometimes to "/dev/null".
482 */
6973dcae 483static struct diff_tempfile {
284098f1
MH
484 /*
485 * filename external diff should read from, or NULL if this
486 * entry is currently not in use:
487 */
488 const char *name;
489
dc01505f 490 char hex[GIT_MAX_HEXSZ + 1];
6973dcae 491 char mode[10];
284098f1
MH
492
493 /*
494 * If this diff_tempfile instance refers to a temporary file,
495 * this tempfile object is used to manage its lifetime.
496 */
076aa2cb 497 struct tempfile *tempfile;
6973dcae
JH
498} diff_temp[2];
499
6957eb9a 500struct emit_callback {
6957eb9a
JH
501 int color_diff;
502 unsigned ws_rule;
503 int blank_at_eof_in_preimage;
504 int blank_at_eof_in_postimage;
505 int lno_in_preimage;
506 int lno_in_postimage;
6957eb9a
JH
507 const char **label_path;
508 struct diff_words_data *diff_words;
a3c158d4 509 struct diff_options *opt;
3e97c7c6 510 struct strbuf *header;
6957eb9a
JH
511};
512
6973dcae
JH
513static int count_lines(const char *data, int size)
514{
515 int count, ch, completely_empty = 1, nl_just_seen = 0;
516 count = 0;
517 while (0 < size--) {
518 ch = *data++;
519 if (ch == '\n') {
520 count++;
521 nl_just_seen = 1;
522 completely_empty = 0;
523 }
524 else {
525 nl_just_seen = 0;
526 completely_empty = 0;
527 }
528 }
529 if (completely_empty)
530 return 0;
531 if (!nl_just_seen)
532 count++; /* no trailing newline */
533 return count;
534}
535
6957eb9a
JH
536static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
537{
538 if (!DIFF_FILE_VALID(one)) {
539 mf->ptr = (char *)""; /* does not matter */
540 mf->size = 0;
541 return 0;
542 }
543 else if (diff_populate_filespec(one, 0))
544 return -1;
bb35fefb 545
6957eb9a
JH
546 mf->ptr = one->data;
547 mf->size = one->size;
548 return 0;
549}
550
abb371a1
JK
551/* like fill_mmfile, but only for size, so we can avoid retrieving blob */
552static unsigned long diff_filespec_size(struct diff_filespec *one)
553{
554 if (!DIFF_FILE_VALID(one))
555 return 0;
8e5dd3d6 556 diff_populate_filespec(one, CHECK_SIZE_ONLY);
abb371a1
JK
557 return one->size;
558}
559
6957eb9a
JH
560static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
561{
562 char *ptr = mf->ptr;
563 long size = mf->size;
564 int cnt = 0;
565
566 if (!size)
567 return cnt;
568 ptr += size - 1; /* pointing at the very end */
569 if (*ptr != '\n')
570 ; /* incomplete line */
571 else
572 ptr--; /* skip the last LF */
573 while (mf->ptr < ptr) {
574 char *prev_eol;
575 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
576 if (*prev_eol == '\n')
577 break;
578 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
579 break;
580 cnt++;
581 ptr = prev_eol - 1;
582 }
583 return cnt;
584}
585
586static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
587 struct emit_callback *ecbdata)
588{
589 int l1, l2, at;
590 unsigned ws_rule = ecbdata->ws_rule;
591 l1 = count_trailing_blank(mf1, ws_rule);
592 l2 = count_trailing_blank(mf2, ws_rule);
593 if (l2 <= l1) {
594 ecbdata->blank_at_eof_in_preimage = 0;
595 ecbdata->blank_at_eof_in_postimage = 0;
596 return;
597 }
598 at = count_lines(mf1->ptr, mf1->size);
599 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
600
601 at = count_lines(mf2->ptr, mf2->size);
602 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
603}
604
a3c158d4 605static void emit_line_0(struct diff_options *o, const char *set, const char *reset,
250f7993 606 int first, const char *line, int len)
6957eb9a
JH
607{
608 int has_trailing_newline, has_trailing_carriage_return;
250f7993 609 int nofirst;
a3c158d4
BY
610 FILE *file = o->file;
611
30997bb8 612 fputs(diff_line_prefix(o), file);
6957eb9a 613
250f7993
JH
614 if (len == 0) {
615 has_trailing_newline = (first == '\n');
616 has_trailing_carriage_return = (!has_trailing_newline &&
617 (first == '\r'));
618 nofirst = has_trailing_newline || has_trailing_carriage_return;
619 } else {
620 has_trailing_newline = (len > 0 && line[len-1] == '\n');
621 if (has_trailing_newline)
622 len--;
623 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
624 if (has_trailing_carriage_return)
625 len--;
626 nofirst = 0;
627 }
6957eb9a 628
06a47552
JH
629 if (len || !nofirst) {
630 fputs(set, file);
631 if (!nofirst)
632 fputc(first, file);
633 fwrite(line, len, 1, file);
634 fputs(reset, file);
635 }
6957eb9a
JH
636 if (has_trailing_carriage_return)
637 fputc('\r', file);
638 if (has_trailing_newline)
639 fputc('\n', file);
640}
641
a3c158d4 642static void emit_line(struct diff_options *o, const char *set, const char *reset,
250f7993
JH
643 const char *line, int len)
644{
a3c158d4 645 emit_line_0(o, set, reset, line[0], line+1, len-1);
250f7993
JH
646}
647
36a4cefd 648enum diff_symbol {
4eed0ebd
SB
649 DIFF_SYMBOL_BINARY_DIFF_HEADER,
650 DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
651 DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
652 DIFF_SYMBOL_BINARY_DIFF_BODY,
653 DIFF_SYMBOL_BINARY_DIFF_FOOTER,
0911c475
SB
654 DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
655 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
656 DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
657 DIFF_SYMBOL_STATS_LINE,
bd033291 658 DIFF_SYMBOL_WORD_DIFF,
30b7e1e7 659 DIFF_SYMBOL_STAT_SEP,
146fdb0d 660 DIFF_SYMBOL_SUMMARY,
f3597138
SB
661 DIFF_SYMBOL_SUBMODULE_ADD,
662 DIFF_SYMBOL_SUBMODULE_DEL,
663 DIFF_SYMBOL_SUBMODULE_UNTRACKED,
664 DIFF_SYMBOL_SUBMODULE_MODIFIED,
665 DIFF_SYMBOL_SUBMODULE_HEADER,
666 DIFF_SYMBOL_SUBMODULE_ERROR,
667 DIFF_SYMBOL_SUBMODULE_PIPETHROUGH,
5af6ea95 668 DIFF_SYMBOL_REWRITE_DIFF,
4acaaa7a 669 DIFF_SYMBOL_BINARY_FILES,
a29b0a13 670 DIFF_SYMBOL_HEADER,
3ee8b7bf
SB
671 DIFF_SYMBOL_FILEPAIR_PLUS,
672 DIFF_SYMBOL_FILEPAIR_MINUS,
ff958679
SB
673 DIFF_SYMBOL_WORDS_PORCELAIN,
674 DIFF_SYMBOL_WORDS,
091f8e28 675 DIFF_SYMBOL_CONTEXT,
f2bb1218 676 DIFF_SYMBOL_CONTEXT_INCOMPLETE,
091f8e28
SB
677 DIFF_SYMBOL_PLUS,
678 DIFF_SYMBOL_MINUS,
b9cbfde6 679 DIFF_SYMBOL_NO_LF_EOF,
68abc6f1 680 DIFF_SYMBOL_CONTEXT_FRAGINFO,
c64b420b 681 DIFF_SYMBOL_CONTEXT_MARKER,
36a4cefd
SB
682 DIFF_SYMBOL_SEPARATOR
683};
091f8e28
SB
684/*
685 * Flags for content lines:
686 * 0..12 are whitespace rules
687 * 13-15 are WSEH_NEW | WSEH_OLD | WSEH_CONTEXT
688 * 16 is marking if the line is blank at EOF
689 */
2e2d5ac1
SB
690#define DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF (1<<16)
691#define DIFF_SYMBOL_MOVED_LINE (1<<17)
692#define DIFF_SYMBOL_MOVED_LINE_ALT (1<<18)
86b452e2 693#define DIFF_SYMBOL_MOVED_LINE_UNINTERESTING (1<<19)
091f8e28
SB
694#define DIFF_SYMBOL_CONTENT_WS_MASK (WSEH_NEW | WSEH_OLD | WSEH_CONTEXT | WS_RULE_MASK)
695
e6e045f8
SB
696/*
697 * This struct is used when we need to buffer the output of the diff output.
698 *
699 * NEEDSWORK: Instead of storing a copy of the line, add an offset pointer
700 * into the pre/post image file. This pointer could be a union with the
701 * line pointer. By storing an offset into the file instead of the literal line,
702 * we can decrease the memory footprint for the buffered output. At first we
703 * may want to only have indirection for the content lines, but we could also
704 * enhance the state for emitting prefabricated lines, e.g. the similarity
705 * score line or hunk/file headers would only need to store a number or path
706 * and then the output can be constructed later on depending on state.
707 */
708struct emitted_diff_symbol {
709 const char *line;
710 int len;
711 int flags;
712 enum diff_symbol s;
713};
714#define EMITTED_DIFF_SYMBOL_INIT {NULL}
715
716struct emitted_diff_symbols {
717 struct emitted_diff_symbol *buf;
718 int nr, alloc;
719};
720#define EMITTED_DIFF_SYMBOLS_INIT {NULL, 0, 0}
721
722static void append_emitted_diff_symbol(struct diff_options *o,
723 struct emitted_diff_symbol *e)
6957eb9a 724{
e6e045f8
SB
725 struct emitted_diff_symbol *f;
726
727 ALLOC_GROW(o->emitted_symbols->buf,
728 o->emitted_symbols->nr + 1,
729 o->emitted_symbols->alloc);
730 f = &o->emitted_symbols->buf[o->emitted_symbols->nr++];
731
732 memcpy(f, e, sizeof(struct emitted_diff_symbol));
733 f->line = e->line ? xmemdupz(e->line, e->len) : NULL;
6957eb9a
JH
734}
735
2e2d5ac1
SB
736struct moved_entry {
737 struct hashmap_entry ent;
738 const struct emitted_diff_symbol *es;
739 struct moved_entry *next_line;
740};
741
ee1df66f
SB
742static int moved_entry_cmp(const void *hashmap_cmp_fn_data,
743 const void *entry,
744 const void *entry_or_key,
2e2d5ac1
SB
745 const void *keydata)
746{
ee1df66f
SB
747 const struct diff_options *diffopt = hashmap_cmp_fn_data;
748 const struct moved_entry *a = entry;
749 const struct moved_entry *b = entry_or_key;
b3095712
SB
750 unsigned flags = diffopt->color_moved_ws_handling
751 & XDF_WHITESPACE_FLAGS;
ee1df66f 752
01be97c2
SB
753 return !xdiff_compare_lines(a->es->line, a->es->len,
754 b->es->line, b->es->len,
b3095712 755 flags);
2e2d5ac1
SB
756}
757
758static struct moved_entry *prepare_entry(struct diff_options *o,
759 int line_no)
760{
761 struct moved_entry *ret = xmalloc(sizeof(*ret));
762 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[line_no];
b3095712 763 unsigned flags = o->color_moved_ws_handling & XDF_WHITESPACE_FLAGS;
2e2d5ac1 764
b3095712 765 ret->ent.hash = xdiff_hash_string(l->line, l->len, flags);
2e2d5ac1
SB
766 ret->es = l;
767 ret->next_line = NULL;
768
769 return ret;
770}
771
772static void add_lines_to_move_detection(struct diff_options *o,
773 struct hashmap *add_lines,
774 struct hashmap *del_lines)
775{
776 struct moved_entry *prev_line = NULL;
777
778 int n;
779 for (n = 0; n < o->emitted_symbols->nr; n++) {
780 struct hashmap *hm;
781 struct moved_entry *key;
782
783 switch (o->emitted_symbols->buf[n].s) {
784 case DIFF_SYMBOL_PLUS:
785 hm = add_lines;
786 break;
787 case DIFF_SYMBOL_MINUS:
788 hm = del_lines;
789 break;
790 default:
791 prev_line = NULL;
792 continue;
793 }
794
795 key = prepare_entry(o, n);
796 if (prev_line && prev_line->es->s == o->emitted_symbols->buf[n].s)
797 prev_line->next_line = key;
798
799 hashmap_add(hm, key);
800 prev_line = key;
801 }
802}
803
e2fe6abc
SB
804static void pmb_advance_or_null(struct diff_options *o,
805 struct moved_entry *match,
806 struct hashmap *hm,
807 struct moved_entry **pmb,
808 int pmb_nr)
809{
810 int i;
811 for (i = 0; i < pmb_nr; i++) {
812 struct moved_entry *prev = pmb[i];
813 struct moved_entry *cur = (prev && prev->next_line) ?
814 prev->next_line : NULL;
815 if (cur && !hm->cmpfn(o, cur, match, NULL)) {
816 pmb[i] = cur;
817 } else {
818 pmb[i] = NULL;
819 }
820 }
821}
822
2e2d5ac1
SB
823static int shrink_potential_moved_blocks(struct moved_entry **pmb,
824 int pmb_nr)
825{
826 int lp, rp;
827
828 /* Shrink the set of potential block to the remaining running */
829 for (lp = 0, rp = pmb_nr - 1; lp <= rp;) {
830 while (lp < pmb_nr && pmb[lp])
831 lp++;
832 /* lp points at the first NULL now */
833
834 while (rp > -1 && !pmb[rp])
835 rp--;
836 /* rp points at the last non-NULL */
837
838 if (lp < pmb_nr && rp > -1 && lp < rp) {
839 pmb[lp] = pmb[rp];
840 pmb[rp] = NULL;
841 rp--;
842 lp++;
843 }
844 }
845
846 /* Remember the number of running sets */
847 return rp + 1;
848}
849
09153277
JT
850/*
851 * If o->color_moved is COLOR_MOVED_PLAIN, this function does nothing.
852 *
f0b8fb6e
JT
853 * Otherwise, if the last block has fewer alphanumeric characters than
854 * COLOR_MOVED_MIN_ALNUM_COUNT, unset DIFF_SYMBOL_MOVED_LINE on all lines in
09153277
JT
855 * that block.
856 *
857 * The last block consists of the (n - block_length)'th line up to but not
858 * including the nth line.
f0b8fb6e
JT
859 *
860 * NEEDSWORK: This uses the same heuristic as blame_entry_score() in blame.c.
861 * Think of a way to unify them.
09153277
JT
862 */
863static void adjust_last_block(struct diff_options *o, int n, int block_length)
864{
f0b8fb6e
JT
865 int i, alnum_count = 0;
866 if (o->color_moved == COLOR_MOVED_PLAIN)
09153277 867 return;
f0b8fb6e
JT
868 for (i = 1; i < block_length + 1; i++) {
869 const char *c = o->emitted_symbols->buf[n - i].line;
870 for (; *c; c++) {
871 if (!isalnum(*c))
872 continue;
873 alnum_count++;
874 if (alnum_count >= COLOR_MOVED_MIN_ALNUM_COUNT)
875 return;
876 }
877 }
09153277
JT
878 for (i = 1; i < block_length + 1; i++)
879 o->emitted_symbols->buf[n - i].flags &= ~DIFF_SYMBOL_MOVED_LINE;
880}
881
2e2d5ac1
SB
882/* Find blocks of moved code, delegate actual coloring decision to helper */
883static void mark_color_as_moved(struct diff_options *o,
884 struct hashmap *add_lines,
885 struct hashmap *del_lines)
886{
887 struct moved_entry **pmb = NULL; /* potentially moved blocks */
888 int pmb_nr = 0, pmb_alloc = 0;
889 int n, flipped_block = 1, block_length = 0;
890
891
892 for (n = 0; n < o->emitted_symbols->nr; n++) {
893 struct hashmap *hm = NULL;
894 struct moved_entry *key;
895 struct moved_entry *match = NULL;
896 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
2e2d5ac1
SB
897
898 switch (l->s) {
899 case DIFF_SYMBOL_PLUS:
900 hm = del_lines;
901 key = prepare_entry(o, n);
3783aad4 902 match = hashmap_get(hm, key, NULL);
2e2d5ac1
SB
903 free(key);
904 break;
905 case DIFF_SYMBOL_MINUS:
906 hm = add_lines;
907 key = prepare_entry(o, n);
3783aad4 908 match = hashmap_get(hm, key, NULL);
2e2d5ac1
SB
909 free(key);
910 break;
911 default:
912 flipped_block = 1;
913 }
914
915 if (!match) {
09153277 916 adjust_last_block(o, n, block_length);
2e2d5ac1
SB
917 pmb_nr = 0;
918 block_length = 0;
919 continue;
920 }
921
922 l->flags |= DIFF_SYMBOL_MOVED_LINE;
2e2d5ac1 923
176841f0
SB
924 if (o->color_moved == COLOR_MOVED_PLAIN)
925 continue;
926
e2fe6abc 927 pmb_advance_or_null(o, match, hm, pmb, pmb_nr);
2e2d5ac1
SB
928
929 pmb_nr = shrink_potential_moved_blocks(pmb, pmb_nr);
930
931 if (pmb_nr == 0) {
932 /*
933 * The current line is the start of a new block.
934 * Setup the set of potential blocks.
935 */
936 for (; match; match = hashmap_get_next(hm, match)) {
937 ALLOC_GROW(pmb, pmb_nr + 1, pmb_alloc);
938 pmb[pmb_nr++] = match;
939 }
940
941 flipped_block = (flipped_block + 1) % 2;
f0b8fb6e
JT
942
943 adjust_last_block(o, n, block_length);
944 block_length = 0;
2e2d5ac1
SB
945 }
946
f0b8fb6e
JT
947 block_length++;
948
51da15eb 949 if (flipped_block && o->color_moved != COLOR_MOVED_BLOCKS)
2e2d5ac1
SB
950 l->flags |= DIFF_SYMBOL_MOVED_LINE_ALT;
951 }
09153277 952 adjust_last_block(o, n, block_length);
2e2d5ac1
SB
953
954 free(pmb);
955}
e6e045f8 956
86b452e2
SB
957#define DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK \
958 (DIFF_SYMBOL_MOVED_LINE | DIFF_SYMBOL_MOVED_LINE_ALT)
959static void dim_moved_lines(struct diff_options *o)
960{
961 int n;
962 for (n = 0; n < o->emitted_symbols->nr; n++) {
963 struct emitted_diff_symbol *prev = (n != 0) ?
964 &o->emitted_symbols->buf[n - 1] : NULL;
965 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
966 struct emitted_diff_symbol *next =
967 (n < o->emitted_symbols->nr - 1) ?
968 &o->emitted_symbols->buf[n + 1] : NULL;
969
970 /* Not a plus or minus line? */
971 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS)
972 continue;
973
974 /* Not a moved line? */
975 if (!(l->flags & DIFF_SYMBOL_MOVED_LINE))
976 continue;
977
978 /*
979 * If prev or next are not a plus or minus line,
980 * pretend they don't exist
981 */
982 if (prev && prev->s != DIFF_SYMBOL_PLUS &&
983 prev->s != DIFF_SYMBOL_MINUS)
984 prev = NULL;
985 if (next && next->s != DIFF_SYMBOL_PLUS &&
986 next->s != DIFF_SYMBOL_MINUS)
987 next = NULL;
988
989 /* Inside a block? */
990 if ((prev &&
991 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
992 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK)) &&
993 (next &&
994 (next->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
995 (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK))) {
996 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
997 continue;
998 }
999
1000 /* Check if we are at an interesting bound: */
1001 if (prev && (prev->flags & DIFF_SYMBOL_MOVED_LINE) &&
1002 (prev->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1003 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1004 continue;
1005 if (next && (next->flags & DIFF_SYMBOL_MOVED_LINE) &&
1006 (next->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1007 (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1008 continue;
1009
1010 /*
1011 * The boundary to prev and next are not interesting,
1012 * so this line is not interesting as a whole
1013 */
1014 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1015 }
1016}
1017
091f8e28
SB
1018static void emit_line_ws_markup(struct diff_options *o,
1019 const char *set, const char *reset,
1020 const char *line, int len, char sign,
1021 unsigned ws_rule, int blank_at_eof)
6957eb9a 1022{
b8767f79 1023 const char *ws = NULL;
6957eb9a 1024
091f8e28
SB
1025 if (o->ws_error_highlight & ws_rule) {
1026 ws = diff_get_color_opt(o, DIFF_WHITESPACE);
b8767f79
JH
1027 if (!*ws)
1028 ws = NULL;
1029 }
1030
1031 if (!ws)
091f8e28
SB
1032 emit_line_0(o, set, reset, sign, line, len);
1033 else if (blank_at_eof)
6957eb9a 1034 /* Blank line at EOF - paint '+' as well */
091f8e28 1035 emit_line_0(o, ws, reset, sign, line, len);
6957eb9a
JH
1036 else {
1037 /* Emit just the prefix, then the rest. */
091f8e28
SB
1038 emit_line_0(o, set, reset, sign, "", 0);
1039 ws_check_emit(line, len, ws_rule,
1040 o->file, set, reset, ws);
6957eb9a
JH
1041 }
1042}
1043
e6e045f8
SB
1044static void emit_diff_symbol_from_struct(struct diff_options *o,
1045 struct emitted_diff_symbol *eds)
36a4cefd 1046{
b9cbfde6 1047 static const char *nneof = " No newline at end of file\n";
5af6ea95 1048 const char *context, *reset, *set, *meta, *fraginfo;
0911c475 1049 struct strbuf sb = STRBUF_INIT;
e6e045f8
SB
1050
1051 enum diff_symbol s = eds->s;
1052 const char *line = eds->line;
1053 int len = eds->len;
1054 unsigned flags = eds->flags;
1055
36a4cefd 1056 switch (s) {
b9cbfde6
SB
1057 case DIFF_SYMBOL_NO_LF_EOF:
1058 context = diff_get_color_opt(o, DIFF_CONTEXT);
1059 reset = diff_get_color_opt(o, DIFF_RESET);
1060 putc('\n', o->file);
1061 emit_line_0(o, context, reset, '\\',
1062 nneof, strlen(nneof));
1063 break;
f3597138
SB
1064 case DIFF_SYMBOL_SUBMODULE_HEADER:
1065 case DIFF_SYMBOL_SUBMODULE_ERROR:
1066 case DIFF_SYMBOL_SUBMODULE_PIPETHROUGH:
0911c475 1067 case DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES:
146fdb0d 1068 case DIFF_SYMBOL_SUMMARY:
0911c475 1069 case DIFF_SYMBOL_STATS_LINE:
4eed0ebd 1070 case DIFF_SYMBOL_BINARY_DIFF_BODY:
68abc6f1
SB
1071 case DIFF_SYMBOL_CONTEXT_FRAGINFO:
1072 emit_line(o, "", "", line, len);
1073 break;
f2bb1218 1074 case DIFF_SYMBOL_CONTEXT_INCOMPLETE:
c64b420b
SB
1075 case DIFF_SYMBOL_CONTEXT_MARKER:
1076 context = diff_get_color_opt(o, DIFF_CONTEXT);
1077 reset = diff_get_color_opt(o, DIFF_RESET);
1078 emit_line(o, context, reset, line, len);
1079 break;
36a4cefd
SB
1080 case DIFF_SYMBOL_SEPARATOR:
1081 fprintf(o->file, "%s%c",
1082 diff_line_prefix(o),
1083 o->line_termination);
1084 break;
091f8e28
SB
1085 case DIFF_SYMBOL_CONTEXT:
1086 set = diff_get_color_opt(o, DIFF_CONTEXT);
1087 reset = diff_get_color_opt(o, DIFF_RESET);
1088 emit_line_ws_markup(o, set, reset, line, len, ' ',
1089 flags & (DIFF_SYMBOL_CONTENT_WS_MASK), 0);
1090 break;
1091 case DIFF_SYMBOL_PLUS:
86b452e2
SB
1092 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1093 DIFF_SYMBOL_MOVED_LINE_ALT |
1094 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1095 case DIFF_SYMBOL_MOVED_LINE |
1096 DIFF_SYMBOL_MOVED_LINE_ALT |
1097 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1098 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT_DIM);
1099 break;
1100 case DIFF_SYMBOL_MOVED_LINE |
1101 DIFF_SYMBOL_MOVED_LINE_ALT:
2e2d5ac1 1102 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT);
86b452e2
SB
1103 break;
1104 case DIFF_SYMBOL_MOVED_LINE |
1105 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1106 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_DIM);
1107 break;
1108 case DIFF_SYMBOL_MOVED_LINE:
2e2d5ac1 1109 set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED);
86b452e2
SB
1110 break;
1111 default:
2e2d5ac1 1112 set = diff_get_color_opt(o, DIFF_FILE_NEW);
86b452e2 1113 }
091f8e28
SB
1114 reset = diff_get_color_opt(o, DIFF_RESET);
1115 emit_line_ws_markup(o, set, reset, line, len, '+',
1116 flags & DIFF_SYMBOL_CONTENT_WS_MASK,
1117 flags & DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF);
1118 break;
1119 case DIFF_SYMBOL_MINUS:
86b452e2
SB
1120 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1121 DIFF_SYMBOL_MOVED_LINE_ALT |
1122 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1123 case DIFF_SYMBOL_MOVED_LINE |
1124 DIFF_SYMBOL_MOVED_LINE_ALT |
1125 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1126 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT_DIM);
1127 break;
1128 case DIFF_SYMBOL_MOVED_LINE |
1129 DIFF_SYMBOL_MOVED_LINE_ALT:
2e2d5ac1 1130 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT);
86b452e2
SB
1131 break;
1132 case DIFF_SYMBOL_MOVED_LINE |
1133 DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1134 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_DIM);
1135 break;
1136 case DIFF_SYMBOL_MOVED_LINE:
2e2d5ac1 1137 set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED);
86b452e2
SB
1138 break;
1139 default:
2e2d5ac1 1140 set = diff_get_color_opt(o, DIFF_FILE_OLD);
86b452e2 1141 }
091f8e28
SB
1142 reset = diff_get_color_opt(o, DIFF_RESET);
1143 emit_line_ws_markup(o, set, reset, line, len, '-',
1144 flags & DIFF_SYMBOL_CONTENT_WS_MASK, 0);
1145 break;
ff958679
SB
1146 case DIFF_SYMBOL_WORDS_PORCELAIN:
1147 context = diff_get_color_opt(o, DIFF_CONTEXT);
1148 reset = diff_get_color_opt(o, DIFF_RESET);
1149 emit_line(o, context, reset, line, len);
1150 fputs("~\n", o->file);
1151 break;
1152 case DIFF_SYMBOL_WORDS:
1153 context = diff_get_color_opt(o, DIFF_CONTEXT);
1154 reset = diff_get_color_opt(o, DIFF_RESET);
1155 /*
1156 * Skip the prefix character, if any. With
1157 * diff_suppress_blank_empty, there may be
1158 * none.
1159 */
1160 if (line[0] != '\n') {
1161 line++;
1162 len--;
1163 }
1164 emit_line(o, context, reset, line, len);
1165 break;
3ee8b7bf
SB
1166 case DIFF_SYMBOL_FILEPAIR_PLUS:
1167 meta = diff_get_color_opt(o, DIFF_METAINFO);
1168 reset = diff_get_color_opt(o, DIFF_RESET);
1169 fprintf(o->file, "%s%s+++ %s%s%s\n", diff_line_prefix(o), meta,
1170 line, reset,
1171 strchr(line, ' ') ? "\t" : "");
1172 break;
1173 case DIFF_SYMBOL_FILEPAIR_MINUS:
1174 meta = diff_get_color_opt(o, DIFF_METAINFO);
1175 reset = diff_get_color_opt(o, DIFF_RESET);
1176 fprintf(o->file, "%s%s--- %s%s%s\n", diff_line_prefix(o), meta,
1177 line, reset,
1178 strchr(line, ' ') ? "\t" : "");
1179 break;
4acaaa7a 1180 case DIFF_SYMBOL_BINARY_FILES:
a29b0a13
SB
1181 case DIFF_SYMBOL_HEADER:
1182 fprintf(o->file, "%s", line);
1183 break;
4eed0ebd
SB
1184 case DIFF_SYMBOL_BINARY_DIFF_HEADER:
1185 fprintf(o->file, "%sGIT binary patch\n", diff_line_prefix(o));
1186 break;
1187 case DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA:
1188 fprintf(o->file, "%sdelta %s\n", diff_line_prefix(o), line);
1189 break;
1190 case DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL:
1191 fprintf(o->file, "%sliteral %s\n", diff_line_prefix(o), line);
1192 break;
1193 case DIFF_SYMBOL_BINARY_DIFF_FOOTER:
1194 fputs(diff_line_prefix(o), o->file);
1195 fputc('\n', o->file);
1196 break;
5af6ea95
SB
1197 case DIFF_SYMBOL_REWRITE_DIFF:
1198 fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
1199 reset = diff_get_color_opt(o, DIFF_RESET);
1200 emit_line(o, fraginfo, reset, line, len);
1201 break;
f3597138
SB
1202 case DIFF_SYMBOL_SUBMODULE_ADD:
1203 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1204 reset = diff_get_color_opt(o, DIFF_RESET);
1205 emit_line(o, set, reset, line, len);
1206 break;
1207 case DIFF_SYMBOL_SUBMODULE_DEL:
1208 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1209 reset = diff_get_color_opt(o, DIFF_RESET);
1210 emit_line(o, set, reset, line, len);
1211 break;
1212 case DIFF_SYMBOL_SUBMODULE_UNTRACKED:
1213 fprintf(o->file, "%sSubmodule %s contains untracked content\n",
1214 diff_line_prefix(o), line);
1215 break;
1216 case DIFF_SYMBOL_SUBMODULE_MODIFIED:
1217 fprintf(o->file, "%sSubmodule %s contains modified content\n",
1218 diff_line_prefix(o), line);
1219 break;
0911c475
SB
1220 case DIFF_SYMBOL_STATS_SUMMARY_NO_FILES:
1221 emit_line(o, "", "", " 0 files changed\n",
1222 strlen(" 0 files changed\n"));
1223 break;
1224 case DIFF_SYMBOL_STATS_SUMMARY_ABBREV:
1225 emit_line(o, "", "", " ...\n", strlen(" ...\n"));
1226 break;
bd033291
SB
1227 case DIFF_SYMBOL_WORD_DIFF:
1228 fprintf(o->file, "%.*s", len, line);
1229 break;
30b7e1e7
SB
1230 case DIFF_SYMBOL_STAT_SEP:
1231 fputs(o->stat_sep, o->file);
1232 break;
36a4cefd
SB
1233 default:
1234 die("BUG: unknown diff symbol");
1235 }
0911c475 1236 strbuf_release(&sb);
36a4cefd
SB
1237}
1238
e6e045f8
SB
1239static void emit_diff_symbol(struct diff_options *o, enum diff_symbol s,
1240 const char *line, int len, unsigned flags)
1241{
1242 struct emitted_diff_symbol e = {line, len, flags, s};
1243
1244 if (o->emitted_symbols)
1245 append_emitted_diff_symbol(o, &e);
1246 else
1247 emit_diff_symbol_from_struct(o, &e);
1248}
1249
f3597138
SB
1250void diff_emit_submodule_del(struct diff_options *o, const char *line)
1251{
1252 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_DEL, line, strlen(line), 0);
1253}
1254
1255void diff_emit_submodule_add(struct diff_options *o, const char *line)
1256{
1257 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ADD, line, strlen(line), 0);
1258}
1259
1260void diff_emit_submodule_untracked(struct diff_options *o, const char *path)
1261{
1262 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_UNTRACKED,
1263 path, strlen(path), 0);
1264}
1265
1266void diff_emit_submodule_modified(struct diff_options *o, const char *path)
1267{
1268 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_MODIFIED,
1269 path, strlen(path), 0);
1270}
1271
1272void diff_emit_submodule_header(struct diff_options *o, const char *header)
1273{
1274 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_HEADER,
1275 header, strlen(header), 0);
1276}
1277
1278void diff_emit_submodule_error(struct diff_options *o, const char *err)
1279{
1280 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ERROR, err, strlen(err), 0);
1281}
1282
1283void diff_emit_submodule_pipethrough(struct diff_options *o,
1284 const char *line, int len)
1285{
1286 emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_PIPETHROUGH, line, len, 0);
1287}
1288
6957eb9a
JH
1289static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
1290{
1291 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
1292 ecbdata->blank_at_eof_in_preimage &&
1293 ecbdata->blank_at_eof_in_postimage &&
1294 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
1295 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
1296 return 0;
018cff70 1297 return ws_blank_line(line, len, ecbdata->ws_rule);
6957eb9a
JH
1298}
1299
b8767f79 1300static void emit_add_line(const char *reset,
0e383e18
JH
1301 struct emit_callback *ecbdata,
1302 const char *line, int len)
1303{
091f8e28
SB
1304 unsigned flags = WSEH_NEW | ecbdata->ws_rule;
1305 if (new_blank_line_at_eof(ecbdata, line, len))
1306 flags |= DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF;
1307
1308 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_PLUS, line, len, flags);
b8767f79 1309}
0e383e18 1310
b8767f79
JH
1311static void emit_del_line(const char *reset,
1312 struct emit_callback *ecbdata,
1313 const char *line, int len)
1314{
091f8e28
SB
1315 unsigned flags = WSEH_OLD | ecbdata->ws_rule;
1316 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_MINUS, line, len, flags);
0e383e18
JH
1317}
1318
1319static void emit_context_line(const char *reset,
1320 struct emit_callback *ecbdata,
1321 const char *line, int len)
1322{
091f8e28
SB
1323 unsigned flags = WSEH_CONTEXT | ecbdata->ws_rule;
1324 emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT, line, len, flags);
0e383e18
JH
1325}
1326
89cb73a1
BW
1327static void emit_hunk_header(struct emit_callback *ecbdata,
1328 const char *line, int len)
1329{
8dbf3eb6 1330 const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
89cb73a1
BW
1331 const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
1332 const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
1333 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1334 static const char atat[2] = { '@', '@' };
1335 const char *cp, *ep;
2efcc977
BY
1336 struct strbuf msgbuf = STRBUF_INIT;
1337 int org_len = len;
1338 int i = 1;
89cb73a1
BW
1339
1340 /*
1341 * As a hunk header must begin with "@@ -<old>, +<new> @@",
1342 * it always is at least 10 bytes long.
1343 */
1344 if (len < 10 ||
1345 memcmp(line, atat, 2) ||
1346 !(ep = memmem(line + 2, len - 2, atat, 2))) {
c64b420b 1347 emit_diff_symbol(ecbdata->opt,
091f8e28 1348 DIFF_SYMBOL_CONTEXT_MARKER, line, len, 0);
89cb73a1
BW
1349 return;
1350 }
1351 ep += 2; /* skip over @@ */
1352
1353 /* The hunk header in fraginfo color */
cedc61a9 1354 strbuf_addstr(&msgbuf, frag);
2efcc977 1355 strbuf_add(&msgbuf, line, ep - line);
cedc61a9 1356 strbuf_addstr(&msgbuf, reset);
2efcc977
BY
1357
1358 /*
1359 * trailing "\r\n"
1360 */
1361 for ( ; i < 3; i++)
1362 if (line[len - i] == '\r' || line[len - i] == '\n')
1363 len--;
89cb73a1
BW
1364
1365 /* blank before the func header */
1366 for (cp = ep; ep - line < len; ep++)
1367 if (*ep != ' ' && *ep != '\t')
1368 break;
2efcc977 1369 if (ep != cp) {
8dbf3eb6 1370 strbuf_addstr(&msgbuf, context);
2efcc977 1371 strbuf_add(&msgbuf, cp, ep - cp);
cedc61a9 1372 strbuf_addstr(&msgbuf, reset);
2efcc977
BY
1373 }
1374
1375 if (ep < line + len) {
cedc61a9 1376 strbuf_addstr(&msgbuf, func);
2efcc977 1377 strbuf_add(&msgbuf, ep, line + len - ep);
cedc61a9 1378 strbuf_addstr(&msgbuf, reset);
2efcc977 1379 }
89cb73a1 1380
2efcc977 1381 strbuf_add(&msgbuf, line + len, org_len - len);
dfb7728f 1382 strbuf_complete_line(&msgbuf);
68abc6f1 1383 emit_diff_symbol(ecbdata->opt,
091f8e28 1384 DIFF_SYMBOL_CONTEXT_FRAGINFO, msgbuf.buf, msgbuf.len, 0);
2efcc977 1385 strbuf_release(&msgbuf);
89cb73a1
BW
1386}
1387
479b0ae8
JK
1388static struct diff_tempfile *claim_diff_tempfile(void) {
1389 int i;
1390 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
1391 if (!diff_temp[i].name)
1392 return diff_temp + i;
1393 die("BUG: diff is failing to clean up its tempfiles");
1394}
1395
479b0ae8
JK
1396static void remove_tempfile(void)
1397{
1398 int i;
a8344abe 1399 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
076aa2cb 1400 if (is_tempfile_active(diff_temp[i].tempfile))
284098f1 1401 delete_tempfile(&diff_temp[i].tempfile);
a8344abe
NR
1402 diff_temp[i].name = NULL;
1403 }
479b0ae8
JK
1404}
1405
5af6ea95 1406static void add_line_count(struct strbuf *out, int count)
6973dcae
JH
1407{
1408 switch (count) {
1409 case 0:
5af6ea95 1410 strbuf_addstr(out, "0,0");
6973dcae
JH
1411 break;
1412 case 1:
5af6ea95 1413 strbuf_addstr(out, "1");
6973dcae
JH
1414 break;
1415 default:
5af6ea95 1416 strbuf_addf(out, "1,%d", count);
6973dcae
JH
1417 break;
1418 }
1419}
1420
7f7ee2ff
JH
1421static void emit_rewrite_lines(struct emit_callback *ecb,
1422 int prefix, const char *data, int size)
6973dcae 1423{
7f7ee2ff 1424 const char *endp = NULL;
7f7ee2ff
JH
1425 const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
1426
1427 while (0 < size) {
1428 int len;
1429
1430 endp = memchr(data, '\n', size);
1431 len = endp ? (endp - data + 1) : size;
1432 if (prefix != '+') {
1433 ecb->lno_in_preimage++;
0e383e18 1434 emit_del_line(reset, ecb, data, len);
7f7ee2ff
JH
1435 } else {
1436 ecb->lno_in_postimage++;
1437 emit_add_line(reset, ecb, data, len);
13e36ec5 1438 }
7f7ee2ff
JH
1439 size -= len;
1440 data += len;
1441 }
b9cbfde6 1442 if (!endp)
091f8e28 1443 emit_diff_symbol(ecb->opt, DIFF_SYMBOL_NO_LF_EOF, NULL, 0, 0);
6973dcae
JH
1444}
1445
1446static void emit_rewrite_diff(const char *name_a,
1447 const char *name_b,
1448 struct diff_filespec *one,
13e36ec5 1449 struct diff_filespec *two,
d9bae1a1
JK
1450 struct userdiff_driver *textconv_one,
1451 struct userdiff_driver *textconv_two,
eab9a40b 1452 struct diff_options *o)
6973dcae
JH
1453{
1454 int lc_a, lc_b;
d5625091 1455 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
a5a818ee 1456 const char *a_prefix, *b_prefix;
840383b2 1457 char *data_one, *data_two;
3aa1f7ca 1458 size_t size_one, size_two;
7f7ee2ff 1459 struct emit_callback ecbdata;
5af6ea95 1460 struct strbuf out = STRBUF_INIT;
a5a818ee 1461
0d1e0e78 1462 if (diff_mnemonic_prefix && o->flags.reverse_diff) {
a5a818ee
JH
1463 a_prefix = o->b_prefix;
1464 b_prefix = o->a_prefix;
1465 } else {
1466 a_prefix = o->a_prefix;
1467 b_prefix = o->b_prefix;
1468 }
1a9eb3b9 1469
8a13becc
JH
1470 name_a += (*name_a == '/');
1471 name_b += (*name_b == '/');
1a9eb3b9 1472
d5625091
JH
1473 strbuf_reset(&a_name);
1474 strbuf_reset(&b_name);
a5a818ee
JH
1475 quote_two_c_style(&a_name, a_prefix, name_a, 0);
1476 quote_two_c_style(&b_name, b_prefix, name_b, 0);
d5625091 1477
840383b2
JK
1478 size_one = fill_textconv(textconv_one, one, &data_one);
1479 size_two = fill_textconv(textconv_two, two, &data_two);
3aa1f7ca 1480
d91ba8fa 1481 memset(&ecbdata, 0, sizeof(ecbdata));
daa0c3d9 1482 ecbdata.color_diff = want_color(o->use_color);
c189c4f2 1483 ecbdata.ws_rule = whitespace_rule(name_b);
a3c158d4 1484 ecbdata.opt = o;
d91ba8fa
JH
1485 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1486 mmfile_t mf1, mf2;
1487 mf1.ptr = (char *)data_one;
1488 mf2.ptr = (char *)data_two;
1489 mf1.size = size_one;
1490 mf2.size = size_two;
1491 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1492 }
1493 ecbdata.lno_in_preimage = 1;
1494 ecbdata.lno_in_postimage = 1;
1495
3aa1f7ca
JK
1496 lc_a = count_lines(data_one, size_one);
1497 lc_b = count_lines(data_two, size_two);
3ee8b7bf
SB
1498
1499 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1500 a_name.buf, a_name.len, 0);
1501 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1502 b_name.buf, b_name.len, 0);
1503
5af6ea95 1504 strbuf_addstr(&out, "@@ -");
467ddc14 1505 if (!o->irreversible_delete)
5af6ea95 1506 add_line_count(&out, lc_a);
467ddc14 1507 else
5af6ea95
SB
1508 strbuf_addstr(&out, "?,?");
1509 strbuf_addstr(&out, " +");
1510 add_line_count(&out, lc_b);
1511 strbuf_addstr(&out, " @@\n");
1512 emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1513 strbuf_release(&out);
1514
467ddc14 1515 if (lc_a && !o->irreversible_delete)
d91ba8fa 1516 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
6973dcae 1517 if (lc_b)
d91ba8fa 1518 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
b76c056b 1519 if (textconv_one)
aed6ca52 1520 free((char *)data_one);
b76c056b 1521 if (textconv_two)
aed6ca52 1522 free((char *)data_two);
6973dcae
JH
1523}
1524
f59a59e2
JS
1525struct diff_words_buffer {
1526 mmfile_t text;
071bcaab 1527 unsigned long alloc;
2e5d2003
JS
1528 struct diff_words_orig {
1529 const char *begin, *end;
1530 } *orig;
1531 int orig_nr, orig_alloc;
f59a59e2
JS
1532};
1533
1534static void diff_words_append(char *line, unsigned long len,
1535 struct diff_words_buffer *buffer)
1536{
23c1575f 1537 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
f59a59e2
JS
1538 line++;
1539 len--;
1540 memcpy(buffer->text.ptr + buffer->text.size, line, len);
1541 buffer->text.size += len;
2b6a5417 1542 buffer->text.ptr[buffer->text.size] = '\0';
f59a59e2
JS
1543}
1544
9cba13ca 1545struct diff_words_style_elem {
882749a0
TR
1546 const char *prefix;
1547 const char *suffix;
1548 const char *color; /* NULL; filled in by the setup code if
1549 * color is enabled */
1550};
1551
9cba13ca 1552struct diff_words_style {
882749a0 1553 enum diff_words_type type;
63a01c3f 1554 struct diff_words_style_elem new_word, old_word, ctx;
882749a0
TR
1555 const char *newline;
1556};
1557
c2e86add 1558static struct diff_words_style diff_words_styles[] = {
882749a0
TR
1559 { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1560 { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1561 { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1562};
1563
f59a59e2 1564struct diff_words_data {
f59a59e2 1565 struct diff_words_buffer minus, plus;
2e5d2003 1566 const char *current_plus;
4297c0ae
BY
1567 int last_minus;
1568 struct diff_options *opt;
2b6a5417 1569 regex_t *word_regex;
882749a0
TR
1570 enum diff_words_type type;
1571 struct diff_words_style *style;
f59a59e2
JS
1572};
1573
bd033291 1574static int fn_out_diff_words_write_helper(struct diff_options *o,
882749a0
TR
1575 struct diff_words_style_elem *st_el,
1576 const char *newline,
bd033291 1577 size_t count, const char *buf)
882749a0 1578{
4297c0ae 1579 int print = 0;
bd033291 1580 struct strbuf sb = STRBUF_INIT;
4297c0ae 1581
882749a0
TR
1582 while (count) {
1583 char *p = memchr(buf, '\n', count);
4297c0ae 1584 if (print)
bd033291
SB
1585 strbuf_addstr(&sb, diff_line_prefix(o));
1586
882749a0 1587 if (p != buf) {
bd033291
SB
1588 const char *reset = st_el->color && *st_el->color ?
1589 GIT_COLOR_RESET : NULL;
1590 if (st_el->color && *st_el->color)
1591 strbuf_addstr(&sb, st_el->color);
1592 strbuf_addstr(&sb, st_el->prefix);
1593 strbuf_add(&sb, buf, p ? p - buf : count);
1594 strbuf_addstr(&sb, st_el->suffix);
1595 if (reset)
1596 strbuf_addstr(&sb, reset);
882749a0
TR
1597 }
1598 if (!p)
bd033291
SB
1599 goto out;
1600
1601 strbuf_addstr(&sb, newline);
882749a0
TR
1602 count -= p + 1 - buf;
1603 buf = p + 1;
4297c0ae 1604 print = 1;
bd033291
SB
1605 if (count) {
1606 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1607 sb.buf, sb.len, 0);
1608 strbuf_reset(&sb);
1609 }
882749a0 1610 }
bd033291
SB
1611
1612out:
1613 if (sb.len)
1614 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1615 sb.buf, sb.len, 0);
1616 strbuf_release(&sb);
882749a0
TR
1617 return 0;
1618}
1619
4297c0ae
BY
1620/*
1621 * '--color-words' algorithm can be described as:
1622 *
5621760f 1623 * 1. collect the minus/plus lines of a diff hunk, divided into
4297c0ae
BY
1624 * minus-lines and plus-lines;
1625 *
1626 * 2. break both minus-lines and plus-lines into words and
1627 * place them into two mmfile_t with one word for each line;
1628 *
1629 * 3. use xdiff to run diff on the two mmfile_t to get the words level diff;
1630 *
1631 * And for the common parts of the both file, we output the plus side text.
1632 * diff_words->current_plus is used to trace the current position of the plus file
1633 * which printed. diff_words->last_minus is used to trace the last minus word
1634 * printed.
1635 *
1636 * For '--graph' to work with '--color-words', we need to output the graph prefix
1637 * on each line of color words output. Generally, there are two conditions on
1638 * which we should output the prefix.
1639 *
1640 * 1. diff_words->last_minus == 0 &&
1641 * diff_words->current_plus == diff_words->plus.text.ptr
1642 *
1643 * that is: the plus text must start as a new line, and if there is no minus
1644 * word printed, a graph prefix must be printed.
1645 *
1646 * 2. diff_words->current_plus > diff_words->plus.text.ptr &&
1647 * *(diff_words->current_plus - 1) == '\n'
1648 *
1649 * that is: a graph prefix must be printed following a '\n'
1650 */
1651static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
1652{
1653 if ((diff_words->last_minus == 0 &&
1654 diff_words->current_plus == diff_words->plus.text.ptr) ||
1655 (diff_words->current_plus > diff_words->plus.text.ptr &&
1656 *(diff_words->current_plus - 1) == '\n')) {
1657 return 1;
1658 } else {
1659 return 0;
1660 }
1661}
1662
f59a59e2 1663static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
f59a59e2 1664{
f59a59e2 1665 struct diff_words_data *diff_words = priv;
882749a0 1666 struct diff_words_style *style = diff_words->style;
2e5d2003
JS
1667 int minus_first, minus_len, plus_first, plus_len;
1668 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
4297c0ae 1669 struct diff_options *opt = diff_words->opt;
30997bb8 1670 const char *line_prefix;
f59a59e2 1671
2e5d2003
JS
1672 if (line[0] != '@' || parse_hunk_header(line, len,
1673 &minus_first, &minus_len, &plus_first, &plus_len))
f59a59e2
JS
1674 return;
1675
4297c0ae 1676 assert(opt);
30997bb8 1677 line_prefix = diff_line_prefix(opt);
4297c0ae 1678
2e5d2003
JS
1679 /* POSIX requires that first be decremented by one if len == 0... */
1680 if (minus_len) {
1681 minus_begin = diff_words->minus.orig[minus_first].begin;
1682 minus_end =
1683 diff_words->minus.orig[minus_first + minus_len - 1].end;
1684 } else
1685 minus_begin = minus_end =
1686 diff_words->minus.orig[minus_first].end;
1687
1688 if (plus_len) {
1689 plus_begin = diff_words->plus.orig[plus_first].begin;
1690 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
1691 } else
1692 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
1693
4297c0ae
BY
1694 if (color_words_output_graph_prefix(diff_words)) {
1695 fputs(line_prefix, diff_words->opt->file);
1696 }
1697 if (diff_words->current_plus != plus_begin) {
bd033291 1698 fn_out_diff_words_write_helper(diff_words->opt,
882749a0
TR
1699 &style->ctx, style->newline,
1700 plus_begin - diff_words->current_plus,
bd033291 1701 diff_words->current_plus);
4297c0ae
BY
1702 }
1703 if (minus_begin != minus_end) {
bd033291 1704 fn_out_diff_words_write_helper(diff_words->opt,
63a01c3f 1705 &style->old_word, style->newline,
bd033291 1706 minus_end - minus_begin, minus_begin);
4297c0ae
BY
1707 }
1708 if (plus_begin != plus_end) {
bd033291 1709 fn_out_diff_words_write_helper(diff_words->opt,
63a01c3f 1710 &style->new_word, style->newline,
bd033291 1711 plus_end - plus_begin, plus_begin);
4297c0ae 1712 }
2e5d2003
JS
1713
1714 diff_words->current_plus = plus_end;
4297c0ae 1715 diff_words->last_minus = minus_first;
f59a59e2
JS
1716}
1717
2b6a5417
JS
1718/* This function starts looking at *begin, and returns 0 iff a word was found. */
1719static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
1720 int *begin, int *end)
1721{
1722 if (word_regex && *begin < buffer->size) {
1723 regmatch_t match[1];
b7d36ffc
JS
1724 if (!regexec_buf(word_regex, buffer->ptr + *begin,
1725 buffer->size - *begin, 1, match, 0)) {
2b6a5417
JS
1726 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
1727 '\n', match[0].rm_eo - match[0].rm_so);
1728 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
1729 *begin += match[0].rm_so;
1730 return *begin >= *end;
1731 }
1732 return -1;
f59a59e2
JS
1733 }
1734
2b6a5417
JS
1735 /* find the next word */
1736 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
1737 (*begin)++;
1738 if (*begin >= buffer->size)
1739 return -1;
f59a59e2 1740
2b6a5417
JS
1741 /* find the end of the word */
1742 *end = *begin + 1;
1743 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
1744 (*end)++;
1745
1746 return 0;
f59a59e2
JS
1747}
1748
23c1575f 1749/*
2e5d2003
JS
1750 * This function splits the words in buffer->text, stores the list with
1751 * newline separator into out, and saves the offsets of the original words
1752 * in buffer->orig.
23c1575f 1753 */
2b6a5417
JS
1754static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
1755 regex_t *word_regex)
f59a59e2 1756{
2e5d2003 1757 int i, j;
2b6a5417 1758 long alloc = 0;
f59a59e2 1759
2e5d2003 1760 out->size = 0;
2b6a5417 1761 out->ptr = NULL;
f59a59e2 1762
2e5d2003
JS
1763 /* fake an empty "0th" word */
1764 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
1765 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
1766 buffer->orig_nr = 1;
1767
1768 for (i = 0; i < buffer->text.size; i++) {
2b6a5417
JS
1769 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
1770 return;
2e5d2003
JS
1771
1772 /* store original boundaries */
1773 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
1774 buffer->orig_alloc);
1775 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
1776 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
1777 buffer->orig_nr++;
1778
1779 /* store one word */
2b6a5417 1780 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
2e5d2003
JS
1781 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
1782 out->ptr[out->size + j - i] = '\n';
1783 out->size += j - i + 1;
1784
1785 i = j - 1;
f59a59e2
JS
1786 }
1787}
1788
1789/* this executes the word diff on the accumulated buffers */
1790static void diff_words_show(struct diff_words_data *diff_words)
1791{
1792 xpparam_t xpp;
1793 xdemitconf_t xecfg;
f59a59e2 1794 mmfile_t minus, plus;
882749a0 1795 struct diff_words_style *style = diff_words->style;
f59a59e2 1796
4297c0ae 1797 struct diff_options *opt = diff_words->opt;
30997bb8 1798 const char *line_prefix;
4297c0ae
BY
1799
1800 assert(opt);
30997bb8 1801 line_prefix = diff_line_prefix(opt);
4297c0ae 1802
2e5d2003
JS
1803 /* special case: only removal */
1804 if (!diff_words->plus.text.size) {
bd033291
SB
1805 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
1806 line_prefix, strlen(line_prefix), 0);
1807 fn_out_diff_words_write_helper(diff_words->opt,
63a01c3f 1808 &style->old_word, style->newline,
4297c0ae 1809 diff_words->minus.text.size,
bd033291 1810 diff_words->minus.text.ptr);
2e5d2003
JS
1811 diff_words->minus.text.size = 0;
1812 return;
1813 }
1814
1815 diff_words->current_plus = diff_words->plus.text.ptr;
4297c0ae 1816 diff_words->last_minus = 0;
f59a59e2 1817
9ccd0a88 1818 memset(&xpp, 0, sizeof(xpp));
30b25010 1819 memset(&xecfg, 0, sizeof(xecfg));
2b6a5417
JS
1820 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
1821 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
582aa00b 1822 xpp.flags = 0;
2b6a5417 1823 /* as only the hunk header will be parsed, we need a 0-context */
2e5d2003 1824 xecfg.ctxlen = 0;
3efb9880
JK
1825 if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
1826 &xpp, &xecfg))
1827 die("unable to generate word diff");
f59a59e2
JS
1828 free(minus.ptr);
1829 free(plus.ptr);
2e5d2003 1830 if (diff_words->current_plus != diff_words->plus.text.ptr +
4297c0ae
BY
1831 diff_words->plus.text.size) {
1832 if (color_words_output_graph_prefix(diff_words))
bd033291
SB
1833 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
1834 line_prefix, strlen(line_prefix), 0);
1835 fn_out_diff_words_write_helper(diff_words->opt,
882749a0 1836 &style->ctx, style->newline,
2e5d2003 1837 diff_words->plus.text.ptr + diff_words->plus.text.size
bd033291 1838 - diff_words->current_plus, diff_words->current_plus);
4297c0ae 1839 }
f59a59e2 1840 diff_words->minus.text.size = diff_words->plus.text.size = 0;
f59a59e2
JS
1841}
1842
76fd2828
JH
1843/* In "color-words" mode, show word-diff of words accumulated in the buffer */
1844static void diff_words_flush(struct emit_callback *ecbdata)
1845{
e6e045f8
SB
1846 struct diff_options *wo = ecbdata->diff_words->opt;
1847
76fd2828
JH
1848 if (ecbdata->diff_words->minus.text.size ||
1849 ecbdata->diff_words->plus.text.size)
1850 diff_words_show(ecbdata->diff_words);
e6e045f8
SB
1851
1852 if (wo->emitted_symbols) {
1853 struct diff_options *o = ecbdata->opt;
1854 struct emitted_diff_symbols *wol = wo->emitted_symbols;
1855 int i;
1856
1857 /*
1858 * NEEDSWORK:
1859 * Instead of appending each, concat all words to a line?
1860 */
1861 for (i = 0; i < wol->nr; i++)
1862 append_emitted_diff_symbol(o, &wol->buf[i]);
1863
1864 for (i = 0; i < wol->nr; i++)
1865 free((void *)wol->buf[i].line);
1866
1867 wol->nr = 0;
1868 }
76fd2828
JH
1869}
1870
77d1a520
TR
1871static void diff_filespec_load_driver(struct diff_filespec *one)
1872{
1873 /* Use already-loaded driver */
1874 if (one->driver)
1875 return;
1876
1877 if (S_ISREG(one->mode))
1878 one->driver = userdiff_find_by_path(one->path);
1879
1880 /* Fallback to default settings */
1881 if (!one->driver)
1882 one->driver = userdiff_find_by_name("default");
1883}
1884
1885static const char *userdiff_word_regex(struct diff_filespec *one)
1886{
1887 diff_filespec_load_driver(one);
1888 return one->driver->word_regex;
1889}
1890
1891static void init_diff_words_data(struct emit_callback *ecbdata,
6440d341 1892 struct diff_options *orig_opts,
77d1a520
TR
1893 struct diff_filespec *one,
1894 struct diff_filespec *two)
1895{
1896 int i;
6440d341
TR
1897 struct diff_options *o = xmalloc(sizeof(struct diff_options));
1898 memcpy(o, orig_opts, sizeof(struct diff_options));
77d1a520
TR
1899
1900 ecbdata->diff_words =
1901 xcalloc(1, sizeof(struct diff_words_data));
1902 ecbdata->diff_words->type = o->word_diff;
1903 ecbdata->diff_words->opt = o;
e6e045f8
SB
1904
1905 if (orig_opts->emitted_symbols)
1906 o->emitted_symbols =
1907 xcalloc(1, sizeof(struct emitted_diff_symbols));
1908
77d1a520
TR
1909 if (!o->word_regex)
1910 o->word_regex = userdiff_word_regex(one);
1911 if (!o->word_regex)
1912 o->word_regex = userdiff_word_regex(two);
1913 if (!o->word_regex)
1914 o->word_regex = diff_word_regex_cfg;
1915 if (o->word_regex) {
1916 ecbdata->diff_words->word_regex = (regex_t *)
1917 xmalloc(sizeof(regex_t));
1918 if (regcomp(ecbdata->diff_words->word_regex,
1919 o->word_regex,
1920 REG_EXTENDED | REG_NEWLINE))
1921 die ("Invalid regular expression: %s",
1922 o->word_regex);
1923 }
1924 for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
1925 if (o->word_diff == diff_words_styles[i].type) {
1926 ecbdata->diff_words->style =
1927 &diff_words_styles[i];
1928 break;
1929 }
1930 }
1931 if (want_color(o->use_color)) {
1932 struct diff_words_style *st = ecbdata->diff_words->style;
63a01c3f
BW
1933 st->old_word.color = diff_get_color_opt(o, DIFF_FILE_OLD);
1934 st->new_word.color = diff_get_color_opt(o, DIFF_FILE_NEW);
8dbf3eb6 1935 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
77d1a520
TR
1936 }
1937}
1938
f59a59e2
JS
1939static void free_diff_words_data(struct emit_callback *ecbdata)
1940{
1941 if (ecbdata->diff_words) {
76fd2828 1942 diff_words_flush(ecbdata);
e6e045f8 1943 free (ecbdata->diff_words->opt->emitted_symbols);
6440d341 1944 free (ecbdata->diff_words->opt);
8e0f7003 1945 free (ecbdata->diff_words->minus.text.ptr);
2e5d2003 1946 free (ecbdata->diff_words->minus.orig);
8e0f7003 1947 free (ecbdata->diff_words->plus.text.ptr);
2e5d2003 1948 free (ecbdata->diff_words->plus.orig);
ef5644ea
BC
1949 if (ecbdata->diff_words->word_regex) {
1950 regfree(ecbdata->diff_words->word_regex);
1951 free(ecbdata->diff_words->word_regex);
1952 }
6a83d902 1953 FREE_AND_NULL(ecbdata->diff_words);
f59a59e2
JS
1954 }
1955}
1956
ce436973 1957const char *diff_get_color(int diff_use_color, enum color_diff ix)
cd112cef 1958{
daa0c3d9 1959 if (want_color(diff_use_color))
50f575fc
LT
1960 return diff_colors[ix];
1961 return "";
cd112cef
JS
1962}
1963
f1922234
JK
1964const char *diff_line_prefix(struct diff_options *opt)
1965{
1966 struct strbuf *msgbuf;
1967 if (!opt->output_prefix)
1968 return "";
1969
1970 msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
1971 return msgbuf->buf;
1972}
1973
23707811
JH
1974static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
1975{
1976 const char *cp;
1977 unsigned long allot;
1978 size_t l = len;
1979
23707811
JH
1980 cp = line;
1981 allot = l;
1982 while (0 < l) {
1983 (void) utf8_width(&cp, &l);
1984 if (!cp)
1985 break; /* truncated in the middle? */
1986 }
1987 return allot - l;
1988}
1989
d68fe26f 1990static void find_lno(const char *line, struct emit_callback *ecbdata)
690ed843 1991{
d68fe26f
JH
1992 const char *p;
1993 ecbdata->lno_in_preimage = 0;
1994 ecbdata->lno_in_postimage = 0;
1995 p = strchr(line, '-');
690ed843 1996 if (!p)
d68fe26f
JH
1997 return; /* cannot happen */
1998 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
1999 p = strchr(p, '+');
2000 if (!p)
2001 return; /* cannot happen */
2002 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
690ed843
JH
2003}
2004
cd112cef 2005static void fn_out_consume(void *priv, char *line, unsigned long len)
6973dcae 2006{
6973dcae 2007 struct emit_callback *ecbdata = priv;
ce436973 2008 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
7be57610 2009 struct diff_options *o = ecbdata->opt;
6973dcae 2010
ba16233c
SB
2011 o->found_changes = 1;
2012
3e97c7c6 2013 if (ecbdata->header) {
a29b0a13
SB
2014 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2015 ecbdata->header->buf, ecbdata->header->len, 0);
3e97c7c6
GB
2016 strbuf_reset(ecbdata->header);
2017 ecbdata->header = NULL;
2018 }
34a5e1a2 2019
6973dcae 2020 if (ecbdata->label_path[0]) {
3ee8b7bf
SB
2021 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
2022 ecbdata->label_path[0],
2023 strlen(ecbdata->label_path[0]), 0);
2024 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
2025 ecbdata->label_path[1],
2026 strlen(ecbdata->label_path[1]), 0);
6973dcae
JH
2027 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
2028 }
cd112cef 2029
a624eaa7
JM
2030 if (diff_suppress_blank_empty
2031 && len == 2 && line[0] == ' ' && line[1] == '\n') {
2032 line[0] = '\n';
2033 len = 1;
2034 }
2035
b8d9c1a6 2036 if (line[0] == '@') {
76fd2828
JH
2037 if (ecbdata->diff_words)
2038 diff_words_flush(ecbdata);
23707811 2039 len = sane_truncate_line(ecbdata, line, len);
d68fe26f 2040 find_lno(line, ecbdata);
89cb73a1 2041 emit_hunk_header(ecbdata, line, len);
448c3ef1 2042 return;
cd112cef 2043 }
448c3ef1 2044
448c3ef1 2045 if (ecbdata->diff_words) {
ff958679
SB
2046 enum diff_symbol s =
2047 ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
2048 DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
448c3ef1
JH
2049 if (line[0] == '-') {
2050 diff_words_append(line, len,
2051 &ecbdata->diff_words->minus);
2052 return;
2053 } else if (line[0] == '+') {
2054 diff_words_append(line, len,
2055 &ecbdata->diff_words->plus);
2056 return;
59556548 2057 } else if (starts_with(line, "\\ ")) {
c7c2bc0a
TR
2058 /*
2059 * Eat the "no newline at eof" marker as if we
2060 * saw a "+" or "-" line with nothing on it,
2061 * and return without diff_words_flush() to
2062 * defer processing. If this is the end of
2063 * preimage, more "+" lines may come after it.
2064 */
2065 return;
448c3ef1 2066 }
76fd2828 2067 diff_words_flush(ecbdata);
ff958679 2068 emit_diff_symbol(o, s, line, len, 0);
448c3ef1
JH
2069 return;
2070 }
448c3ef1 2071
0e383e18
JH
2072 switch (line[0]) {
2073 case '+':
d68fe26f 2074 ecbdata->lno_in_postimage++;
018cff70 2075 emit_add_line(reset, ecbdata, line + 1, len - 1);
0e383e18
JH
2076 break;
2077 case '-':
2078 ecbdata->lno_in_preimage++;
2079 emit_del_line(reset, ecbdata, line + 1, len - 1);
2080 break;
2081 case ' ':
2082 ecbdata->lno_in_postimage++;
2083 ecbdata->lno_in_preimage++;
2084 emit_context_line(reset, ecbdata, line + 1, len - 1);
2085 break;
2086 default:
2087 /* incomplete line at the end */
2088 ecbdata->lno_in_preimage++;
f2bb1218
SB
2089 emit_diff_symbol(o, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
2090 line, len, 0);
0e383e18 2091 break;
448c3ef1 2092 }
6973dcae
JH
2093}
2094
c905cbc4 2095static void pprint_rename(struct strbuf *name, const char *a, const char *b)
6973dcae 2096{
63a01c3f
BW
2097 const char *old_name = a;
2098 const char *new_name = b;
6973dcae 2099 int pfx_length, sfx_length;
dd281f09 2100 int pfx_adjust_for_slash;
6973dcae
JH
2101 int len_a = strlen(a);
2102 int len_b = strlen(b);
663af342 2103 int a_midlen, b_midlen;
e5bfbf9b
AJ
2104 int qlen_a = quote_c_style(a, NULL, NULL, 0);
2105 int qlen_b = quote_c_style(b, NULL, NULL, 0);
2106
2107 if (qlen_a || qlen_b) {
c905cbc4
NTND
2108 quote_c_style(a, name, NULL, 0);
2109 strbuf_addstr(name, " => ");
2110 quote_c_style(b, name, NULL, 0);
2111 return;
e5bfbf9b 2112 }
6973dcae
JH
2113
2114 /* Find common prefix */
2115 pfx_length = 0;
63a01c3f
BW
2116 while (*old_name && *new_name && *old_name == *new_name) {
2117 if (*old_name == '/')
2118 pfx_length = old_name - a + 1;
2119 old_name++;
2120 new_name++;
6973dcae
JH
2121 }
2122
2123 /* Find common suffix */
63a01c3f
BW
2124 old_name = a + len_a;
2125 new_name = b + len_b;
6973dcae 2126 sfx_length = 0;
d020e27f 2127 /*
dd281f09
TR
2128 * If there is a common prefix, it must end in a slash. In
2129 * that case we let this loop run 1 into the prefix to see the
2130 * same slash.
2131 *
2132 * If there is no common prefix, we cannot do this as it would
2133 * underrun the input strings.
d020e27f 2134 */
dd281f09 2135 pfx_adjust_for_slash = (pfx_length ? 1 : 0);
63a01c3f
BW
2136 while (a + pfx_length - pfx_adjust_for_slash <= old_name &&
2137 b + pfx_length - pfx_adjust_for_slash <= new_name &&
2138 *old_name == *new_name) {
2139 if (*old_name == '/')
2140 sfx_length = len_a - (old_name - a);
2141 old_name--;
2142 new_name--;
6973dcae
JH
2143 }
2144
2145 /*
2146 * pfx{mid-a => mid-b}sfx
2147 * {pfx-a => pfx-b}sfx
2148 * pfx{sfx-a => sfx-b}
2149 * name-a => name-b
2150 */
663af342
PH
2151 a_midlen = len_a - pfx_length - sfx_length;
2152 b_midlen = len_b - pfx_length - sfx_length;
2153 if (a_midlen < 0)
2154 a_midlen = 0;
2155 if (b_midlen < 0)
2156 b_midlen = 0;
2157
c905cbc4 2158 strbuf_grow(name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
6973dcae 2159 if (pfx_length + sfx_length) {
c905cbc4
NTND
2160 strbuf_add(name, a, pfx_length);
2161 strbuf_addch(name, '{');
6973dcae 2162 }
c905cbc4
NTND
2163 strbuf_add(name, a + pfx_length, a_midlen);
2164 strbuf_addstr(name, " => ");
2165 strbuf_add(name, b + pfx_length, b_midlen);
663af342 2166 if (pfx_length + sfx_length) {
c905cbc4
NTND
2167 strbuf_addch(name, '}');
2168 strbuf_add(name, a + len_a - sfx_length, sfx_length);
6973dcae 2169 }
6973dcae
JH
2170}
2171
2172struct diffstat_t {
6973dcae
JH
2173 int nr;
2174 int alloc;
2175 struct diffstat_file {
f604652e 2176 char *from_name;
6973dcae 2177 char *name;
f604652e 2178 char *print_name;
ddf88fa6 2179 const char *comments;
6973dcae
JH
2180 unsigned is_unmerged:1;
2181 unsigned is_binary:1;
2182 unsigned is_renamed:1;
74faaa16 2183 unsigned is_interesting:1;
0974c117 2184 uintmax_t added, deleted;
6973dcae
JH
2185 } **files;
2186};
2187
2188static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
2189 const char *name_a,
2190 const char *name_b)
2191{
2192 struct diffstat_file *x;
1a4927c5 2193 x = xcalloc(1, sizeof(*x));
4c960a43 2194 ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
6973dcae
JH
2195 diffstat->files[diffstat->nr++] = x;
2196 if (name_b) {
f604652e
JH
2197 x->from_name = xstrdup(name_a);
2198 x->name = xstrdup(name_b);
6973dcae
JH
2199 x->is_renamed = 1;
2200 }
f604652e
JH
2201 else {
2202 x->from_name = NULL;
9befac47 2203 x->name = xstrdup(name_a);
f604652e 2204 }
6973dcae
JH
2205 return x;
2206}
2207
2208static void diffstat_consume(void *priv, char *line, unsigned long len)
2209{
2210 struct diffstat_t *diffstat = priv;
2211 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
2212
2213 if (line[0] == '+')
2214 x->added++;
2215 else if (line[0] == '-')
2216 x->deleted++;
2217}
2218
698ce6f8 2219const char mime_boundary_leader[] = "------------";
6973dcae 2220
a2540023
JH
2221static int scale_linear(int it, int width, int max_change)
2222{
2eeeef24
JH
2223 if (!it)
2224 return 0;
a2540023 2225 /*
2eeeef24
JH
2226 * make sure that at least one '-' or '+' is printed if
2227 * there is any change to this path. The easiest way is to
2228 * scale linearly as if the alloted width is one column shorter
2229 * than it is, and then add 1 to the result.
a2540023 2230 */
2eeeef24 2231 return 1 + (it * (width - 1) / max_change);
a2540023
JH
2232}
2233
0911c475
SB
2234static void show_graph(struct strbuf *out, char ch, int cnt,
2235 const char *set, const char *reset)
a2540023
JH
2236{
2237 if (cnt <= 0)
2238 return;
0911c475
SB
2239 strbuf_addstr(out, set);
2240 strbuf_addchars(out, ch, cnt);
2241 strbuf_addstr(out, reset);
a2540023
JH
2242}
2243
f604652e
JH
2244static void fill_print_name(struct diffstat_file *file)
2245{
c905cbc4 2246 struct strbuf pname = STRBUF_INIT;
f604652e
JH
2247
2248 if (file->print_name)
2249 return;
2250
c905cbc4
NTND
2251 if (file->is_renamed)
2252 pprint_rename(&pname, file->from_name, file->name);
2253 else
2254 quote_c_style(file->name, &pname, NULL, 0);
2255
ddf88fa6
NTND
2256 if (file->comments)
2257 strbuf_addf(&pname, " (%s)", file->comments);
2258
c905cbc4 2259 file->print_name = strbuf_detach(&pname, NULL);
f604652e
JH
2260}
2261
0911c475
SB
2262static void print_stat_summary_inserts_deletes(struct diff_options *options,
2263 int files, int insertions, int deletions)
7f814632
NTND
2264{
2265 struct strbuf sb = STRBUF_INIT;
7f814632
NTND
2266
2267 if (!files) {
2268 assert(insertions == 0 && deletions == 0);
0911c475
SB
2269 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
2270 NULL, 0, 0);
2271 return;
7f814632
NTND
2272 }
2273
2274 strbuf_addf(&sb,
218adaaa 2275 (files == 1) ? " %d file changed" : " %d files changed",
7f814632
NTND
2276 files);
2277
2278 /*
2279 * For binary diff, the caller may want to print "x files
2280 * changed" with insertions == 0 && deletions == 0.
2281 *
2282 * Not omitting "0 insertions(+), 0 deletions(-)" in this case
2283 * is probably less confusing (i.e skip over "2 files changed
2284 * but nothing about added/removed lines? Is this a bug in Git?").
2285 */
2286 if (insertions || deletions == 0) {
7f814632 2287 strbuf_addf(&sb,
218adaaa 2288 (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
7f814632
NTND
2289 insertions);
2290 }
2291
2292 if (deletions || insertions == 0) {
7f814632 2293 strbuf_addf(&sb,
218adaaa 2294 (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
7f814632
NTND
2295 deletions);
2296 }
2297 strbuf_addch(&sb, '\n');
0911c475
SB
2298 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
2299 sb.buf, sb.len, 0);
7f814632 2300 strbuf_release(&sb);
0911c475
SB
2301}
2302
2303void print_stat_summary(FILE *fp, int files,
2304 int insertions, int deletions)
2305{
2306 struct diff_options o;
2307 memset(&o, 0, sizeof(o));
2308 o.file = fp;
2309
2310 print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
7f814632
NTND
2311}
2312
4b25d091 2313static void show_stats(struct diffstat_t *data, struct diff_options *options)
6973dcae 2314{
eb3a9dd3 2315 int i, len, add, del, adds = 0, dels = 0;
0974c117 2316 uintmax_t max_change = 0, max_len = 0;
dc801e71
ZJS
2317 int total_files = data->nr, count;
2318 int width, name_width, graph_width, number_width = 0, bin_width = 0;
c0aa335c 2319 const char *reset, *add_c, *del_c;
e5f85df8 2320 int extra_shown = 0;
0911c475
SB
2321 const char *line_prefix = diff_line_prefix(options);
2322 struct strbuf out = STRBUF_INIT;
6973dcae
JH
2323
2324 if (data->nr == 0)
2325 return;
2326
808e1db2 2327 count = options->stat_count ? options->stat_count : data->nr;
a2540023 2328
8f67f8ae 2329 reset = diff_get_color_opt(options, DIFF_RESET);
8f67f8ae
PH
2330 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
2331 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
785f7432 2332
1b058bc3
ZJS
2333 /*
2334 * Find the longest filename and max number of changes
2335 */
808e1db2 2336 for (i = 0; (i < count) && (i < data->nr); i++) {
6973dcae 2337 struct diffstat_file *file = data->files[i];
0974c117 2338 uintmax_t change = file->added + file->deleted;
af0ed819
JH
2339
2340 if (!file->is_interesting && (change == 0)) {
808e1db2 2341 count++; /* not shown == room for one more */
358e460e
MG
2342 continue;
2343 }
f604652e
JH
2344 fill_print_name(file);
2345 len = strlen(file->print_name);
6973dcae
JH
2346 if (max_len < len)
2347 max_len = len;
2348
dc801e71
ZJS
2349 if (file->is_unmerged) {
2350 /* "Unmerged" is 8 characters */
2351 bin_width = bin_width < 8 ? 8 : bin_width;
6973dcae 2352 continue;
dc801e71
ZJS
2353 }
2354 if (file->is_binary) {
2355 /* "Bin XXX -> YYY bytes" */
2356 int w = 14 + decimal_width(file->added)
2357 + decimal_width(file->deleted);
2358 bin_width = bin_width < w ? w : bin_width;
2359 /* Display change counts aligned with "Bin" */
2360 number_width = 3;
2361 continue;
2362 }
2363
a2540023
JH
2364 if (max_change < change)
2365 max_change = change;
6973dcae 2366 }
a20d3c0d 2367 count = i; /* where we can stop scanning in data->files[] */
6973dcae 2368
1b058bc3
ZJS
2369 /*
2370 * We have width = stat_width or term_columns() columns total.
2371 * We want a maximum of min(max_len, stat_name_width) for the name part.
969fe57b 2372 * We want a maximum of min(max_change, stat_graph_width) for the +- part.
1b058bc3
ZJS
2373 * We also need 1 for " " and 4 + decimal_width(max_change)
2374 * for " | NNNN " and one the empty column at the end, altogether
2375 * 6 + decimal_width(max_change).
2376 *
2377 * If there's not enough space, we will use the smaller of
2378 * stat_name_width (if set) and 5/8*width for the filename,
969fe57b
ZJS
2379 * and the rest for constant elements + graph part, but no more
2380 * than stat_graph_width for the graph part.
1b058bc3
ZJS
2381 * (5/8 gives 50 for filename and 30 for the constant parts + graph
2382 * for the standard terminal size).
a2540023 2383 *
1b058bc3
ZJS
2384 * In other words: stat_width limits the maximum width, and
2385 * stat_name_width fixes the maximum width of the filename,
2386 * and is also used to divide available columns if there
2387 * aren't enough.
dc801e71
ZJS
2388 *
2389 * Binary files are displayed with "Bin XXX -> YYY bytes"
2390 * instead of the change count and graph. This part is treated
2391 * similarly to the graph part, except that it is not
41ccfdd9 2392 * "scaled". If total width is too small to accommodate the
dc801e71
ZJS
2393 * guaranteed minimum width of the filename part and the
2394 * separators and this message, this message will "overflow"
2395 * making the line longer than the maximum width.
a2540023 2396 */
1b058bc3
ZJS
2397
2398 if (options->stat_width == -1)
cd48dadb 2399 width = term_columns() - strlen(line_prefix);
a2540023 2400 else
1b058bc3 2401 width = options->stat_width ? options->stat_width : 80;
dc801e71
ZJS
2402 number_width = decimal_width(max_change) > number_width ?
2403 decimal_width(max_change) : number_width;
a2540023 2404
df44483a
ZJS
2405 if (options->stat_graph_width == -1)
2406 options->stat_graph_width = diff_stat_graph_width;
a2540023 2407
1b058bc3
ZJS
2408 /*
2409 * Guarantee 3/8*16==6 for the graph part
2410 * and 5/8*16==10 for the filename part
2411 */
2412 if (width < 16 + 6 + number_width)
2413 width = 16 + 6 + number_width;
2414
2415 /*
2416 * First assign sizes that are wanted, ignoring available width.
dc801e71
ZJS
2417 * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
2418 * starting from "XXX" should fit in graph_width.
1b058bc3 2419 */
dc801e71
ZJS
2420 graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
2421 if (options->stat_graph_width &&
2422 options->stat_graph_width < graph_width)
2423 graph_width = options->stat_graph_width;
2424
1b058bc3
ZJS
2425 name_width = (options->stat_name_width > 0 &&
2426 options->stat_name_width < max_len) ?
2427 options->stat_name_width : max_len;
2428
2429 /*
2430 * Adjust adjustable widths not to exceed maximum width
2431 */
2432 if (name_width + number_width + 6 + graph_width > width) {
678c5741 2433 if (graph_width > width * 3/8 - number_width - 6) {
1b058bc3 2434 graph_width = width * 3/8 - number_width - 6;
678c5741
LP
2435 if (graph_width < 6)
2436 graph_width = 6;
2437 }
2438
969fe57b
ZJS
2439 if (options->stat_graph_width &&
2440 graph_width > options->stat_graph_width)
2441 graph_width = options->stat_graph_width;
1b058bc3
ZJS
2442 if (name_width > width - number_width - 6 - graph_width)
2443 name_width = width - number_width - 6 - graph_width;
2444 else
2445 graph_width = width - number_width - 6 - name_width;
2446 }
2447
2448 /*
2449 * From here name_width is the width of the name area,
2450 * and graph_width is the width of the graph area.
2451 * max_change is used to scale graph properly.
2452 */
808e1db2 2453 for (i = 0; i < count; i++) {
d2543b8e 2454 const char *prefix = "";
af0ed819
JH
2455 struct diffstat_file *file = data->files[i];
2456 char *name = file->print_name;
2457 uintmax_t added = file->added;
2458 uintmax_t deleted = file->deleted;
a2540023 2459 int name_len;
6973dcae 2460
a20d3c0d 2461 if (!file->is_interesting && (added + deleted == 0))
358e460e 2462 continue;
a20d3c0d 2463
6973dcae
JH
2464 /*
2465 * "scale" the filename
2466 */
a2540023
JH
2467 len = name_width;
2468 name_len = strlen(name);
2469 if (name_width < name_len) {
6973dcae
JH
2470 char *slash;
2471 prefix = "...";
a2540023
JH
2472 len -= 3;
2473 name += name_len - len;
6973dcae
JH
2474 slash = strchr(name, '/');
2475 if (slash)
2476 name = slash;
2477 }
6973dcae 2478
af0ed819 2479 if (file->is_binary) {
0911c475
SB
2480 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2481 strbuf_addf(&out, " %*s", number_width, "Bin");
e18872b2 2482 if (!added && !deleted) {
0911c475
SB
2483 strbuf_addch(&out, '\n');
2484 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2485 out.buf, out.len, 0);
2486 strbuf_reset(&out);
e18872b2
ZJS
2487 continue;
2488 }
0911c475 2489 strbuf_addf(&out, " %s%"PRIuMAX"%s",
0974c117 2490 del_c, deleted, reset);
0911c475
SB
2491 strbuf_addstr(&out, " -> ");
2492 strbuf_addf(&out, "%s%"PRIuMAX"%s",
0974c117 2493 add_c, added, reset);
0911c475
SB
2494 strbuf_addstr(&out, " bytes\n");
2495 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2496 out.buf, out.len, 0);
2497 strbuf_reset(&out);
f604652e 2498 continue;
6973dcae 2499 }
af0ed819 2500 else if (file->is_unmerged) {
0911c475
SB
2501 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2502 strbuf_addstr(&out, " Unmerged\n");
2503 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2504 out.buf, out.len, 0);
2505 strbuf_reset(&out);
f604652e 2506 continue;
6973dcae 2507 }
6973dcae 2508
a2540023
JH
2509 /*
2510 * scale the add/delete
2511 */
6973dcae
JH
2512 add = added;
2513 del = deleted;
6973dcae 2514
1b058bc3 2515 if (graph_width <= max_change) {
d3c9cf32 2516 int total = scale_linear(add + del, graph_width, max_change);
2eeeef24
JH
2517 if (total < 2 && add && del)
2518 /* width >= 2 due to the sanity check */
2519 total = 2;
2520 if (add < del) {
1b058bc3 2521 add = scale_linear(add, graph_width, max_change);
2eeeef24
JH
2522 del = total - add;
2523 } else {
1b058bc3 2524 del = scale_linear(del, graph_width, max_change);
2eeeef24
JH
2525 add = total - del;
2526 }
6973dcae 2527 }
0911c475
SB
2528 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2529 strbuf_addf(&out, " %*"PRIuMAX"%s",
dc801e71
ZJS
2530 number_width, added + deleted,
2531 added + deleted ? " " : "");
0911c475
SB
2532 show_graph(&out, '+', add, add_c, reset);
2533 show_graph(&out, '-', del, del_c, reset);
2534 strbuf_addch(&out, '\n');
2535 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2536 out.buf, out.len, 0);
2537 strbuf_reset(&out);
c0c77734 2538 }
a20d3c0d
JH
2539
2540 for (i = 0; i < data->nr; i++) {
af0ed819
JH
2541 struct diffstat_file *file = data->files[i];
2542 uintmax_t added = file->added;
2543 uintmax_t deleted = file->deleted;
82dfc2c4
JH
2544
2545 if (file->is_unmerged ||
2546 (!file->is_interesting && (added + deleted == 0))) {
808e1db2
MG
2547 total_files--;
2548 continue;
2549 }
a20d3c0d 2550
82dfc2c4 2551 if (!file->is_binary) {
a20d3c0d
JH
2552 adds += added;
2553 dels += deleted;
2554 }
2555 if (i < count)
2556 continue;
e5f85df8 2557 if (!extra_shown)
0911c475
SB
2558 emit_diff_symbol(options,
2559 DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
2560 NULL, 0, 0);
e5f85df8 2561 extra_shown = 1;
808e1db2 2562 }
0911c475
SB
2563
2564 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
5a612017 2565 strbuf_release(&out);
6973dcae
JH
2566}
2567
2775d92c 2568static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
ebd124c6
NP
2569{
2570 int i, adds = 0, dels = 0, total_files = data->nr;
2571
2572 if (data->nr == 0)
2573 return;
2574
2575 for (i = 0; i < data->nr; i++) {
e18872b2 2576 int added = data->files[i]->added;
0911c475 2577 int deleted = data->files[i]->deleted;
e18872b2 2578
20c8cde4
JH
2579 if (data->files[i]->is_unmerged ||
2580 (!data->files[i]->is_interesting && (added + deleted == 0))) {
e18872b2 2581 total_files--;
de9658b5 2582 } else if (!data->files[i]->is_binary) { /* don't count bytes */
e18872b2
ZJS
2583 adds += added;
2584 dels += deleted;
ebd124c6 2585 }
ebd124c6 2586 }
0911c475 2587 print_stat_summary_inserts_deletes(options, total_files, adds, dels);
ebd124c6
NP
2588}
2589
4b25d091 2590static void show_numstat(struct diffstat_t *data, struct diff_options *options)
74e2abe5
JH
2591{
2592 int i;
2593
f604652e
JH
2594 if (data->nr == 0)
2595 return;
2596
74e2abe5
JH
2597 for (i = 0; i < data->nr; i++) {
2598 struct diffstat_file *file = data->files[i];
2599
30997bb8 2600 fprintf(options->file, "%s", diff_line_prefix(options));
7be57610 2601
bfddbc5e 2602 if (file->is_binary)
c0c77734 2603 fprintf(options->file, "-\t-\t");
bfddbc5e 2604 else
c0c77734 2605 fprintf(options->file,
0974c117
JK
2606 "%"PRIuMAX"\t%"PRIuMAX"\t",
2607 file->added, file->deleted);
f604652e
JH
2608 if (options->line_termination) {
2609 fill_print_name(file);
2610 if (!file->is_renamed)
c0c77734 2611 write_name_quoted(file->name, options->file,
f604652e
JH
2612 options->line_termination);
2613 else {
c0c77734
DB
2614 fputs(file->print_name, options->file);
2615 putc(options->line_termination, options->file);
f604652e 2616 }
663af342 2617 } else {
f604652e 2618 if (file->is_renamed) {
c0c77734
DB
2619 putc('\0', options->file);
2620 write_name_quoted(file->from_name, options->file, '\0');
f604652e 2621 }
c0c77734 2622 write_name_quoted(file->name, options->file, '\0');
663af342 2623 }
74e2abe5
JH
2624 }
2625}
2626
c04a7155
JH
2627struct dirstat_file {
2628 const char *name;
2629 unsigned long changed;
7df7c019
LT
2630};
2631
c04a7155
JH
2632struct dirstat_dir {
2633 struct dirstat_file *files;
712d2c7d 2634 int alloc, nr, permille, cumulative;
c04a7155
JH
2635};
2636
7be57610
BY
2637static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
2638 unsigned long changed, const char *base, int baselen)
7df7c019 2639{
585c0e2e 2640 unsigned long sum_changes = 0;
7df7c019 2641 unsigned int sources = 0;
30997bb8 2642 const char *line_prefix = diff_line_prefix(opt);
7df7c019
LT
2643
2644 while (dir->nr) {
c04a7155 2645 struct dirstat_file *f = dir->files;
7df7c019 2646 int namelen = strlen(f->name);
585c0e2e 2647 unsigned long changes;
7df7c019
LT
2648 char *slash;
2649
2650 if (namelen < baselen)
2651 break;
2652 if (memcmp(f->name, base, baselen))
2653 break;
2654 slash = strchr(f->name + baselen, '/');
2655 if (slash) {
2656 int newbaselen = slash + 1 - f->name;
585c0e2e 2657 changes = gather_dirstat(opt, dir, changed, f->name, newbaselen);
7df7c019
LT
2658 sources++;
2659 } else {
585c0e2e 2660 changes = f->changed;
7df7c019
LT
2661 dir->files++;
2662 dir->nr--;
2663 sources += 2;
2664 }
585c0e2e 2665 sum_changes += changes;
7df7c019
LT
2666 }
2667
2668 /*
2669 * We don't report dirstat's for
2670 * - the top level
2671 * - or cases where everything came from a single directory
2672 * under this directory (sources == 1).
2673 */
2674 if (baselen && sources != 1) {
585c0e2e
BW
2675 if (sum_changes) {
2676 int permille = sum_changes * 1000 / changed;
712d2c7d 2677 if (permille >= dir->permille) {
7be57610 2678 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
712d2c7d 2679 permille / 10, permille % 10, baselen, base);
7df7c019
LT
2680 if (!dir->cumulative)
2681 return 0;
2682 }
2683 }
2684 }
585c0e2e 2685 return sum_changes;
7df7c019
LT
2686}
2687
441bca0b
LT
2688static int dirstat_compare(const void *_a, const void *_b)
2689{
2690 const struct dirstat_file *a = _a;
2691 const struct dirstat_file *b = _b;
2692 return strcmp(a->name, b->name);
2693}
2694
c04a7155 2695static void show_dirstat(struct diff_options *options)
7df7c019
LT
2696{
2697 int i;
2698 unsigned long changed;
c04a7155
JH
2699 struct dirstat_dir dir;
2700 struct diff_queue_struct *q = &diff_queued_diff;
2701
2702 dir.files = NULL;
2703 dir.alloc = 0;
2704 dir.nr = 0;
712d2c7d 2705 dir.permille = options->dirstat_permille;
0d1e0e78 2706 dir.cumulative = options->flags.dirstat_cumulative;
7df7c019 2707
7df7c019 2708 changed = 0;
c04a7155
JH
2709 for (i = 0; i < q->nr; i++) {
2710 struct diff_filepair *p = q->queue[i];
2711 const char *name;
2712 unsigned long copied, added, damage;
0133dab7 2713 int content_changed;
c04a7155 2714
2ca86714 2715 name = p->two->path ? p->two->path : p->one->path;
c04a7155 2716
41c9560e 2717 if (p->one->oid_valid && p->two->oid_valid)
a0d12c44 2718 content_changed = oidcmp(&p->one->oid, &p->two->oid);
0133dab7
JH
2719 else
2720 content_changed = 1;
2721
2ff3a803
JH
2722 if (!content_changed) {
2723 /*
2724 * The SHA1 has not changed, so pre-/post-content is
2725 * identical. We can therefore skip looking at the
2726 * file contents altogether.
2727 */
2728 damage = 0;
2729 goto found_damage;
2730 }
2731
0d1e0e78 2732 if (options->flags.dirstat_by_file) {
0133dab7
JH
2733 /*
2734 * In --dirstat-by-file mode, we don't really need to
2735 * look at the actual file contents at all.
2736 * The fact that the SHA1 changed is enough for us to
2737 * add this file to the list of results
2738 * (with each file contributing equal damage).
2739 */
2ff3a803 2740 damage = 1;
0133dab7
JH
2741 goto found_damage;
2742 }
c04a7155
JH
2743
2744 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
2745 diff_populate_filespec(p->one, 0);
2746 diff_populate_filespec(p->two, 0);
974e0044 2747 diffcore_count_changes(p->one, p->two, NULL, NULL,
c04a7155
JH
2748 &copied, &added);
2749 diff_free_filespec_data(p->one);
2750 diff_free_filespec_data(p->two);
2751 } else if (DIFF_FILE_VALID(p->one)) {
8e5dd3d6 2752 diff_populate_filespec(p->one, CHECK_SIZE_ONLY);
c04a7155
JH
2753 copied = added = 0;
2754 diff_free_filespec_data(p->one);
2755 } else if (DIFF_FILE_VALID(p->two)) {
8e5dd3d6 2756 diff_populate_filespec(p->two, CHECK_SIZE_ONLY);
c04a7155
JH
2757 copied = 0;
2758 added = p->two->size;
2759 diff_free_filespec_data(p->two);
2760 } else
2b0b551d 2761 continue;
c04a7155
JH
2762
2763 /*
2764 * Original minus copied is the removed material,
2765 * added is the new material. They are both damages
0133dab7 2766 * made to the preimage.
2ff3a803
JH
2767 * If the resulting damage is zero, we know that
2768 * diffcore_count_changes() considers the two entries to
2769 * be identical, but since content_changed is true, we
2770 * know that there must have been _some_ kind of change,
2771 * so we force all entries to have damage > 0.
c04a7155
JH
2772 */
2773 damage = (p->one->size - copied) + added;
2ff3a803 2774 if (!damage)
fd33777b 2775 damage = 1;
c04a7155 2776
0133dab7 2777found_damage:
c04a7155
JH
2778 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
2779 dir.files[dir.nr].name = name;
2780 dir.files[dir.nr].changed = damage;
2781 changed += damage;
2782 dir.nr++;
7df7c019
LT
2783 }
2784
2785 /* This can happen even with many files, if everything was renames */
2786 if (!changed)
2787 return;
2788
2789 /* Show all directories with more than x% of the changes */
9ed0d8d6 2790 QSORT(dir.files, dir.nr, dirstat_compare);
7be57610 2791 gather_dirstat(options, &dir, changed, "", 0);
7df7c019
LT
2792}
2793
1c57a627
JH
2794static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
2795{
2796 int i;
2797 unsigned long changed;
2798 struct dirstat_dir dir;
2799
2800 if (data->nr == 0)
2801 return;
2802
2803 dir.files = NULL;
2804 dir.alloc = 0;
2805 dir.nr = 0;
2806 dir.permille = options->dirstat_permille;
0d1e0e78 2807 dir.cumulative = options->flags.dirstat_cumulative;
1c57a627
JH
2808
2809 changed = 0;
2810 for (i = 0; i < data->nr; i++) {
2811 struct diffstat_file *file = data->files[i];
2812 unsigned long damage = file->added + file->deleted;
2813 if (file->is_binary)
2814 /*
2815 * binary files counts bytes, not lines. Must find some
2816 * way to normalize binary bytes vs. textual lines.
2817 * The following heuristic assumes that there are 64
2818 * bytes per "line".
2819 * This is stupid and ugly, but very cheap...
2820 */
42c78a21 2821 damage = DIV_ROUND_UP(damage, 64);
1c57a627
JH
2822 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
2823 dir.files[dir.nr].name = file->name;
2824 dir.files[dir.nr].changed = damage;
2825 changed += damage;
2826 dir.nr++;
2827 }
2828
2829 /* This can happen even with many files, if everything was renames */
2830 if (!changed)
2831 return;
2832
2833 /* Show all directories with more than x% of the changes */
9ed0d8d6 2834 QSORT(dir.files, dir.nr, dirstat_compare);
1c57a627
JH
2835 gather_dirstat(options, &dir, changed, "", 0);
2836}
2837
f604652e
JH
2838static void free_diffstat_info(struct diffstat_t *diffstat)
2839{
2840 int i;
2841 for (i = 0; i < diffstat->nr; i++) {
2842 struct diffstat_file *f = diffstat->files[i];
c905cbc4 2843 free(f->print_name);
f604652e
JH
2844 free(f->name);
2845 free(f->from_name);
2846 free(f);
2847 }
2848 free(diffstat->files);
2849}
2850
88246898 2851struct checkdiff_t {
88246898 2852 const char *filename;
1ba111d1 2853 int lineno;
a757c646 2854 int conflict_marker_size;
1ba111d1 2855 struct diff_options *o;
cf1b7869 2856 unsigned ws_rule;
62c64895 2857 unsigned status;
88246898
JS
2858};
2859
a757c646 2860static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
04954043
JH
2861{
2862 char firstchar;
2863 int cnt;
2864
a757c646 2865 if (len < marker_size + 1)
04954043
JH
2866 return 0;
2867 firstchar = line[0];
2868 switch (firstchar) {
a757c646 2869 case '=': case '>': case '<': case '|':
04954043
JH
2870 break;
2871 default:
2872 return 0;
2873 }
a757c646 2874 for (cnt = 1; cnt < marker_size; cnt++)
04954043
JH
2875 if (line[cnt] != firstchar)
2876 return 0;
a757c646
JH
2877 /* line[1] thru line[marker_size-1] are same as firstchar */
2878 if (len < marker_size + 1 || !isspace(line[marker_size]))
04954043 2879 return 0;
04954043
JH
2880 return 1;
2881}
2882
88246898
JS
2883static void checkdiff_consume(void *priv, char *line, unsigned long len)
2884{
2885 struct checkdiff_t *data = priv;
a757c646 2886 int marker_size = data->conflict_marker_size;
f1c96261
JK
2887 const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
2888 const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
2889 const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
c1795bb0 2890 char *err;
30997bb8 2891 const char *line_prefix;
7be57610
BY
2892
2893 assert(data->o);
30997bb8 2894 line_prefix = diff_line_prefix(data->o);
88246898
JS
2895
2896 if (line[0] == '+') {
18374e58 2897 unsigned bad;
0ef617f4 2898 data->lineno++;
a757c646 2899 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
04954043
JH
2900 data->status |= 1;
2901 fprintf(data->o->file,
7be57610
BY
2902 "%s%s:%d: leftover conflict marker\n",
2903 line_prefix, data->filename, data->lineno);
04954043 2904 }
8f8841e9 2905 bad = ws_check(line + 1, len - 1, data->ws_rule);
18374e58 2906 if (!bad)
c1795bb0 2907 return;
18374e58
JH
2908 data->status |= bad;
2909 err = whitespace_error_string(bad);
7be57610
BY
2910 fprintf(data->o->file, "%s%s:%d: %s.\n",
2911 line_prefix, data->filename, data->lineno, err);
c1795bb0 2912 free(err);
a3c158d4 2913 emit_line(data->o, set, reset, line, 1);
8f8841e9 2914 ws_check_emit(line + 1, len - 1, data->ws_rule,
1ba111d1 2915 data->o->file, set, reset, ws);
877f23cc 2916 } else if (line[0] == ' ') {
88246898 2917 data->lineno++;
877f23cc 2918 } else if (line[0] == '@') {
88246898
JS
2919 char *plus = strchr(line, '+');
2920 if (plus)
0ef617f4 2921 data->lineno = strtol(plus, NULL, 10) - 1;
88246898
JS
2922 else
2923 die("invalid diff");
2924 }
2925}
2926
0660626c
JH
2927static unsigned char *deflate_it(char *data,
2928 unsigned long size,
2929 unsigned long *result_size)
051308f6 2930{
0660626c
JH
2931 int bound;
2932 unsigned char *deflated;
ef49a7a0 2933 git_zstream stream;
0660626c 2934
55bb5c91 2935 git_deflate_init(&stream, zlib_compression_level);
225a6f10 2936 bound = git_deflate_bound(&stream, size);
0660626c
JH
2937 deflated = xmalloc(bound);
2938 stream.next_out = deflated;
2939 stream.avail_out = bound;
2940
2941 stream.next_in = (unsigned char *)data;
2942 stream.avail_in = size;
55bb5c91 2943 while (git_deflate(&stream, Z_FINISH) == Z_OK)
0660626c 2944 ; /* nothing */
55bb5c91 2945 git_deflate_end(&stream);
0660626c
JH
2946 *result_size = stream.total_out;
2947 return deflated;
051308f6
JH
2948}
2949
4eed0ebd
SB
2950static void emit_binary_diff_body(struct diff_options *o,
2951 mmfile_t *one, mmfile_t *two)
051308f6 2952{
0660626c
JH
2953 void *cp;
2954 void *delta;
2955 void *deflated;
2956 void *data;
2957 unsigned long orig_size;
2958 unsigned long delta_size;
2959 unsigned long deflate_size;
2960 unsigned long data_size;
051308f6 2961
0660626c
JH
2962 /* We could do deflated delta, or we could do just deflated two,
2963 * whichever is smaller.
051308f6 2964 */
0660626c
JH
2965 delta = NULL;
2966 deflated = deflate_it(two->ptr, two->size, &deflate_size);
2967 if (one->size && two->size) {
2968 delta = diff_delta(one->ptr, one->size,
2969 two->ptr, two->size,
2970 &delta_size, deflate_size);
2971 if (delta) {
2972 void *to_free = delta;
2973 orig_size = delta_size;
2974 delta = deflate_it(delta, delta_size, &delta_size);
2975 free(to_free);
051308f6
JH
2976 }
2977 }
051308f6 2978
0660626c 2979 if (delta && delta_size < deflate_size) {
4eed0ebd
SB
2980 char *s = xstrfmt("%lu", orig_size);
2981 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
2982 s, strlen(s), 0);
2983 free(s);
0660626c
JH
2984 free(deflated);
2985 data = delta;
2986 data_size = delta_size;
4eed0ebd
SB
2987 } else {
2988 char *s = xstrfmt("%lu", two->size);
2989 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
2990 s, strlen(s), 0);
2991 free(s);
0660626c
JH
2992 free(delta);
2993 data = deflated;
2994 data_size = deflate_size;
2995 }
051308f6 2996
0660626c
JH
2997 /* emit data encoded in base85 */
2998 cp = data;
2999 while (data_size) {
4eed0ebd 3000 int len;
0660626c 3001 int bytes = (52 < data_size) ? 52 : data_size;
4eed0ebd 3002 char line[71];
0660626c 3003 data_size -= bytes;
051308f6
JH
3004 if (bytes <= 26)
3005 line[0] = bytes + 'A' - 1;
3006 else
3007 line[0] = bytes - 26 + 'a' - 1;
3008 encode_85(line + 1, cp, bytes);
1d7f171c 3009 cp = (char *) cp + bytes;
4eed0ebd
SB
3010
3011 len = strlen(line);
3012 line[len++] = '\n';
3013 line[len] = '\0';
3014
3015 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
3016 line, len, 0);
051308f6 3017 }
4eed0ebd 3018 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
0660626c 3019 free(data);
051308f6
JH
3020}
3021
4eed0ebd
SB
3022static void emit_binary_diff(struct diff_options *o,
3023 mmfile_t *one, mmfile_t *two)
d4c452f0 3024{
4eed0ebd
SB
3025 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
3026 emit_binary_diff_body(o, one, two);
3027 emit_binary_diff_body(o, two, one);
d4c452f0
JH
3028}
3029
29a3eefd
JH
3030int diff_filespec_is_binary(struct diff_filespec *one)
3031{
122aa6f9
JK
3032 if (one->is_binary == -1) {
3033 diff_filespec_load_driver(one);
3034 if (one->driver->binary != -1)
3035 one->is_binary = one->driver->binary;
3036 else {
3037 if (!one->data && DIFF_FILE_VALID(one))
6bf3b813
NTND
3038 diff_populate_filespec(one, CHECK_BINARY);
3039 if (one->is_binary == -1 && one->data)
122aa6f9
JK
3040 one->is_binary = buffer_is_binary(one->data,
3041 one->size);
3042 if (one->is_binary == -1)
3043 one->is_binary = 0;
3044 }
3045 }
29a3eefd 3046 return one->is_binary;
6973dcae
JH
3047}
3048
be58e70d 3049static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
f258475a 3050{
122aa6f9
JK
3051 diff_filespec_load_driver(one);
3052 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
f258475a
JH
3053}
3054
a5a818ee
JH
3055void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
3056{
3057 if (!options->a_prefix)
3058 options->a_prefix = a;
3059 if (!options->b_prefix)
3060 options->b_prefix = b;
3061}
3062
a788d7d5 3063struct userdiff_driver *get_textconv(struct diff_filespec *one)
04427ac8
JK
3064{
3065 if (!DIFF_FILE_VALID(one))
3066 return NULL;
d391c0ff 3067
04427ac8 3068 diff_filespec_load_driver(one);
3813e690 3069 return userdiff_get_textconv(one->driver);
04427ac8
JK
3070}
3071
6973dcae
JH
3072static void builtin_diff(const char *name_a,
3073 const char *name_b,
3074 struct diff_filespec *one,
3075 struct diff_filespec *two,
3076 const char *xfrm_msg,
296c6bb2 3077 int must_show_header,
051308f6 3078 struct diff_options *o,
6973dcae
JH
3079 int complete_rewrite)
3080{
3081 mmfile_t mf1, mf2;
3082 const char *lbl[2];
3083 char *a_one, *b_two;
d9c552f1 3084 const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
8f67f8ae 3085 const char *reset = diff_get_color_opt(o, DIFF_RESET);
a5a818ee 3086 const char *a_prefix, *b_prefix;
d9bae1a1
JK
3087 struct userdiff_driver *textconv_one = NULL;
3088 struct userdiff_driver *textconv_two = NULL;
3e97c7c6 3089 struct strbuf header = STRBUF_INIT;
30997bb8 3090 const char *line_prefix = diff_line_prefix(o);
a5a818ee 3091
fd47ae6a 3092 diff_set_mnemonic_prefix(o, "a/", "b/");
0d1e0e78 3093 if (o->flags.reverse_diff) {
fd47ae6a
JK
3094 a_prefix = o->b_prefix;
3095 b_prefix = o->a_prefix;
3096 } else {
3097 a_prefix = o->a_prefix;
3098 b_prefix = o->b_prefix;
3099 }
3100
61cfbc05
JK
3101 if (o->submodule_format == DIFF_SUBMODULE_LOG &&
3102 (!one->mode || S_ISGITLINK(one->mode)) &&
3103 (!two->mode || S_ISGITLINK(two->mode))) {
f3597138 3104 show_submodule_summary(o, one->path ? one->path : two->path,
602a283a 3105 &one->oid, &two->oid,
f3597138 3106 two->dirty_submodule);
752c0c24 3107 return;
fd47ae6a
JK
3108 } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3109 (!one->mode || S_ISGITLINK(one->mode)) &&
3110 (!two->mode || S_ISGITLINK(two->mode))) {
f3597138 3111 show_submodule_inline_diff(o, one->path ? one->path : two->path,
fd47ae6a 3112 &one->oid, &two->oid,
f3597138 3113 two->dirty_submodule);
fd47ae6a 3114 return;
752c0c24
JS
3115 }
3116
0d1e0e78 3117 if (o->flags.allow_textconv) {
3aa1f7ca
JK
3118 textconv_one = get_textconv(one);
3119 textconv_two = get_textconv(two);
3120 }
3121
71b989e7
LT
3122 /* Never use a non-valid filename anywhere if at all possible */
3123 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3124 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3125
a5a818ee
JH
3126 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3127 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
6973dcae
JH
3128 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3129 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
d9c552f1 3130 strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
6973dcae
JH
3131 if (lbl[0][0] == '/') {
3132 /* /dev/null */
d9c552f1 3133 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
37466447
BW
3134 if (xfrm_msg)
3135 strbuf_addstr(&header, xfrm_msg);
296c6bb2 3136 must_show_header = 1;
6973dcae
JH
3137 }
3138 else if (lbl[1][0] == '/') {
d9c552f1 3139 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
37466447
BW
3140 if (xfrm_msg)
3141 strbuf_addstr(&header, xfrm_msg);
296c6bb2 3142 must_show_header = 1;
6973dcae
JH
3143 }
3144 else {
3145 if (one->mode != two->mode) {
d9c552f1
JK
3146 strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3147 strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
296c6bb2 3148 must_show_header = 1;
cd112cef 3149 }
37466447
BW
3150 if (xfrm_msg)
3151 strbuf_addstr(&header, xfrm_msg);
3e97c7c6 3152
6973dcae
JH
3153 /*
3154 * we do not run diff between different kind
3155 * of objects.
3156 */
3157 if ((one->mode ^ two->mode) & S_IFMT)
3158 goto free_ab_and_return;
0c01857d 3159 if (complete_rewrite &&
3aa1f7ca
JK
3160 (textconv_one || !diff_filespec_is_binary(one)) &&
3161 (textconv_two || !diff_filespec_is_binary(two))) {
a29b0a13
SB
3162 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3163 header.buf, header.len, 0);
3e97c7c6 3164 strbuf_reset(&header);
3aa1f7ca
JK
3165 emit_rewrite_diff(name_a, name_b, one, two,
3166 textconv_one, textconv_two, o);
34a5e1a2 3167 o->found_changes = 1;
6973dcae
JH
3168 goto free_ab_and_return;
3169 }
3170 }
3171
467ddc14 3172 if (o->irreversible_delete && lbl[1][0] == '/') {
a29b0a13
SB
3173 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3174 header.len, 0);
467ddc14
JH
3175 strbuf_reset(&header);
3176 goto free_ab_and_return;
0d1e0e78 3177 } else if (!o->flags.text &&
b3373982
JK
3178 ( (!textconv_one && diff_filespec_is_binary(one)) ||
3179 (!textconv_two && diff_filespec_is_binary(two)) )) {
4acaaa7a 3180 struct strbuf sb = STRBUF_INIT;
1aaf69e6
NTND
3181 if (!one->data && !two->data &&
3182 S_ISREG(one->mode) && S_ISREG(two->mode) &&
0d1e0e78 3183 !o->flags.binary) {
a0d12c44 3184 if (!oidcmp(&one->oid, &two->oid)) {
1aaf69e6 3185 if (must_show_header)
a29b0a13
SB
3186 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3187 header.buf, header.len,
3188 0);
1aaf69e6
NTND
3189 goto free_ab_and_return;
3190 }
a29b0a13
SB
3191 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3192 header.buf, header.len, 0);
4acaaa7a
SB
3193 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3194 diff_line_prefix(o), lbl[0], lbl[1]);
3195 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3196 sb.buf, sb.len, 0);
3197 strbuf_release(&sb);
1aaf69e6
NTND
3198 goto free_ab_and_return;
3199 }
b3373982
JK
3200 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
3201 die("unable to read files to diff");
0660626c
JH
3202 /* Quite common confusing case */
3203 if (mf1.size == mf2.size &&
296c6bb2
CC
3204 !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3205 if (must_show_header)
a29b0a13
SB
3206 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3207 header.buf, header.len, 0);
0660626c 3208 goto free_ab_and_return;
296c6bb2 3209 }
a29b0a13 3210 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3e97c7c6 3211 strbuf_reset(&header);
0d1e0e78 3212 if (o->flags.binary)
4eed0ebd 3213 emit_binary_diff(o, &mf1, &mf2);
4acaaa7a
SB
3214 else {
3215 strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3216 diff_line_prefix(o), lbl[0], lbl[1]);
3217 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3218 sb.buf, sb.len, 0);
3219 strbuf_release(&sb);
3220 }
34a5e1a2 3221 o->found_changes = 1;
467ddc14 3222 } else {
6973dcae
JH
3223 /* Crazy xdl interfaces.. */
3224 const char *diffopts = getenv("GIT_DIFF_OPTS");
ae021d87 3225 const char *v;
6973dcae
JH
3226 xpparam_t xpp;
3227 xdemitconf_t xecfg;
6973dcae 3228 struct emit_callback ecbdata;
be58e70d 3229 const struct userdiff_funcname *pe;
f258475a 3230
b3f01ff2 3231 if (must_show_header) {
a29b0a13
SB
3232 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3233 header.buf, header.len, 0);
3e97c7c6
GB
3234 strbuf_reset(&header);
3235 }
3236
840383b2
JK
3237 mf1.size = fill_textconv(textconv_one, one, &mf1.ptr);
3238 mf2.size = fill_textconv(textconv_two, two, &mf2.ptr);
04427ac8 3239
45e7ca0f
BC
3240 pe = diff_funcname_pattern(one);
3241 if (!pe)
3242 pe = diff_funcname_pattern(two);
6973dcae 3243
9ccd0a88 3244 memset(&xpp, 0, sizeof(xpp));
30b25010 3245 memset(&xecfg, 0, sizeof(xecfg));
cd112cef 3246 memset(&ecbdata, 0, sizeof(ecbdata));
6973dcae 3247 ecbdata.label_path = lbl;
daa0c3d9 3248 ecbdata.color_diff = want_color(o->use_color);
c189c4f2 3249 ecbdata.ws_rule = whitespace_rule(name_b);
690ed843 3250 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
d68fe26f 3251 check_blank_at_eof(&mf1, &mf2, &ecbdata);
a3c158d4 3252 ecbdata.opt = o;
3e97c7c6 3253 ecbdata.header = header.len ? &header : NULL;
582aa00b 3254 xpp.flags = o->xdl_opts;
2477ab2e
JT
3255 xpp.anchors = o->anchors;
3256 xpp.anchors_nr = o->anchors_nr;
ee1e5412 3257 xecfg.ctxlen = o->context;
6d0e674a 3258 xecfg.interhunkctxlen = o->interhunkcontext;
6973dcae 3259 xecfg.flags = XDL_EMIT_FUNCNAMES;
0d1e0e78 3260 if (o->flags.funccontext)
14937c2c 3261 xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
45e7ca0f 3262 if (pe)
a013585b 3263 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
6973dcae
JH
3264 if (!diffopts)
3265 ;
ae021d87
JK
3266 else if (skip_prefix(diffopts, "--unified=", &v))
3267 xecfg.ctxlen = strtoul(v, NULL, 10);
3268 else if (skip_prefix(diffopts, "-u", &v))
3269 xecfg.ctxlen = strtoul(v, NULL, 10);
77d1a520
TR
3270 if (o->word_diff)
3271 init_diff_words_data(&ecbdata, o, one, two);
3efb9880
JK
3272 if (xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
3273 &xpp, &xecfg))
3274 die("unable to generate diff for %s", one->path);
882749a0 3275 if (o->word_diff)
f59a59e2 3276 free_diff_words_data(&ecbdata);
04427ac8
JK
3277 if (textconv_one)
3278 free(mf1.ptr);
3279 if (textconv_two)
3280 free(mf2.ptr);
8cfe5f1c 3281 xdiff_clear_find_func(&xecfg);
6973dcae
JH
3282 }
3283
3284 free_ab_and_return:
3e97c7c6 3285 strbuf_release(&header);
fc3abdf5
JH
3286 diff_free_filespec_data(one);
3287 diff_free_filespec_data(two);
6973dcae
JH
3288 free(a_one);
3289 free(b_two);
3290 return;
3291}
3292
ddf88fa6
NTND
3293static char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
3294{
3295 if (!is_renamed) {
3296 if (p->status == DIFF_STATUS_ADDED) {
3297 if (S_ISLNK(p->two->mode))
3298 return "new +l";
3299 else if ((p->two->mode & 0777) == 0755)
3300 return "new +x";
3301 else
3302 return "new";
3303 } else if (p->status == DIFF_STATUS_DELETED)
3304 return "gone";
3305 }
3306 if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
3307 return "mode -l";
3308 else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
3309 return "mode +l";
3310 else if ((p->one->mode & 0777) == 0644 &&
3311 (p->two->mode & 0777) == 0755)
3312 return "mode +x";
3313 else if ((p->one->mode & 0777) == 0755 &&
3314 (p->two->mode & 0777) == 0644)
3315 return "mode -x";
3316 return NULL;
3317}
3318
6973dcae
JH
3319static void builtin_diffstat(const char *name_a, const char *name_b,
3320 struct diff_filespec *one,
3321 struct diff_filespec *two,
710158e3 3322 struct diffstat_t *diffstat,
0d21efa5 3323 struct diff_options *o,
74faaa16 3324 struct diff_filepair *p)
6973dcae
JH
3325{
3326 mmfile_t mf1, mf2;
3327 struct diffstat_file *data;
352ca4e1 3328 int same_contents;
74faaa16
LT
3329 int complete_rewrite = 0;
3330
3331 if (!DIFF_PAIR_UNMERGED(p)) {
3332 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3333 complete_rewrite = 1;
3334 }
6973dcae
JH
3335
3336 data = diffstat_add(diffstat, name_a, name_b);
99bfd407 3337 data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
ddf88fa6
NTND
3338 if (o->flags.stat_with_summary)
3339 data->comments = get_compact_summary(p, data->is_renamed);
6973dcae
JH
3340
3341 if (!one || !two) {
3342 data->is_unmerged = 1;
3343 return;
3344 }
ded0abc7 3345
a0d12c44 3346 same_contents = !oidcmp(&one->oid, &two->oid);
352ca4e1 3347
ded0abc7 3348 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
ded0abc7 3349 data->is_binary = 1;
352ca4e1 3350 if (same_contents) {
e18872b2
ZJS
3351 data->added = 0;
3352 data->deleted = 0;
3353 } else {
3354 data->added = diff_filespec_size(two);
3355 data->deleted = diff_filespec_size(one);
3356 }
ded0abc7
JK
3357 }
3358
3359 else if (complete_rewrite) {
710158e3
JH
3360 diff_populate_filespec(one, 0);
3361 diff_populate_filespec(two, 0);
3362 data->deleted = count_lines(one->data, one->size);
3363 data->added = count_lines(two->data, two->size);
710158e3 3364 }
6973dcae 3365
352ca4e1 3366 else if (!same_contents) {
6973dcae
JH
3367 /* Crazy xdl interfaces.. */
3368 xpparam_t xpp;
3369 xdemitconf_t xecfg;
6973dcae 3370
ded0abc7
JK
3371 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
3372 die("unable to read files to diff");
3373
9ccd0a88 3374 memset(&xpp, 0, sizeof(xpp));
30b25010 3375 memset(&xecfg, 0, sizeof(xecfg));
582aa00b 3376 xpp.flags = o->xdl_opts;
2477ab2e
JT
3377 xpp.anchors = o->anchors;
3378 xpp.anchors_nr = o->anchors_nr;
f01cae91
JH
3379 xecfg.ctxlen = o->context;
3380 xecfg.interhunkctxlen = o->interhunkcontext;
3efb9880
JK
3381 if (xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
3382 &xpp, &xecfg))
3383 die("unable to generate diffstat for %s", one->path);
6973dcae 3384 }
fc3abdf5 3385
fc3abdf5
JH
3386 diff_free_filespec_data(one);
3387 diff_free_filespec_data(two);
6973dcae
JH
3388}
3389
88246898 3390static void builtin_checkdiff(const char *name_a, const char *name_b,
cd676a51 3391 const char *attr_path,
5ff10dd6
JH
3392 struct diff_filespec *one,
3393 struct diff_filespec *two,
3394 struct diff_options *o)
88246898
JS
3395{
3396 mmfile_t mf1, mf2;
3397 struct checkdiff_t data;
3398
3399 if (!two)
3400 return;
3401
3402 memset(&data, 0, sizeof(data));
88246898
JS
3403 data.filename = name_b ? name_b : name_a;
3404 data.lineno = 0;
1ba111d1 3405 data.o = o;
cd676a51 3406 data.ws_rule = whitespace_rule(attr_path);
a757c646 3407 data.conflict_marker_size = ll_merge_marker_size(attr_path);
88246898
JS
3408
3409 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
3410 die("unable to read files to diff");
3411
5ff10dd6
JH
3412 /*
3413 * All the other codepaths check both sides, but not checking
3414 * the "old" side here is deliberate. We are checking the newly
3415 * introduced changes, and as long as the "new" side is text, we
3416 * can and should check what it introduces.
3417 */
29a3eefd 3418 if (diff_filespec_is_binary(two))
fc3abdf5 3419 goto free_and_return;
88246898
JS
3420 else {
3421 /* Crazy xdl interfaces.. */
3422 xpparam_t xpp;
3423 xdemitconf_t xecfg;
88246898 3424
9ccd0a88 3425 memset(&xpp, 0, sizeof(xpp));
30b25010 3426 memset(&xecfg, 0, sizeof(xecfg));
c35539eb 3427 xecfg.ctxlen = 1; /* at least one context line */
582aa00b 3428 xpp.flags = 0;
3efb9880
JK
3429 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
3430 &xpp, &xecfg))
3431 die("unable to generate checkdiff for %s", one->path);
877f23cc 3432
467babf8 3433 if (data.ws_rule & WS_BLANK_AT_EOF) {
d68fe26f
JH
3434 struct emit_callback ecbdata;
3435 int blank_at_eof;
3436
3437 ecbdata.ws_rule = data.ws_rule;
3438 check_blank_at_eof(&mf1, &mf2, &ecbdata);
8837d335 3439 blank_at_eof = ecbdata.blank_at_eof_in_postimage;
d68fe26f 3440
467babf8
JH
3441 if (blank_at_eof) {
3442 static char *err;
3443 if (!err)
3444 err = whitespace_error_string(WS_BLANK_AT_EOF);
3445 fprintf(o->file, "%s:%d: %s.\n",
3446 data.filename, blank_at_eof, err);
3447 data.status = 1; /* report errors */
3448 }
877f23cc 3449 }
88246898 3450 }
fc3abdf5
JH
3451 free_and_return:
3452 diff_free_filespec_data(one);
3453 diff_free_filespec_data(two);
62c64895 3454 if (data.status)
0d1e0e78 3455 o->flags.check_failed = 1;
88246898
JS
3456}
3457
6973dcae
JH
3458struct diff_filespec *alloc_filespec(const char *path)
3459{
96ffc06f 3460 struct diff_filespec *spec;
6973dcae 3461
96ffc06f 3462 FLEXPTR_ALLOC_STR(spec, path, path);
9fb88419 3463 spec->count = 1;
122aa6f9 3464 spec->is_binary = -1;
6973dcae
JH
3465 return spec;
3466}
3467
9fb88419
LT
3468void free_filespec(struct diff_filespec *spec)
3469{
3470 if (!--spec->count) {
3471 diff_free_filespec_data(spec);
3472 free(spec);
3473 }
3474}
3475
f9704c2d
BW
3476void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3477 int oid_valid, unsigned short mode)
6973dcae
JH
3478{
3479 if (mode) {
3480 spec->mode = canon_mode(mode);
f9704c2d
BW
3481 oidcpy(&spec->oid, oid);
3482 spec->oid_valid = oid_valid;
6973dcae
JH
3483 }
3484}
3485
3486/*
5adf317b 3487 * Given a name and sha1 pair, if the index tells us the file in
6973dcae
JH
3488 * the work tree has that object contents, return true, so that
3489 * prepare_temp_file() does not have to inflate and extract.
3490 */
fb4a1c0d 3491static int reuse_worktree_file(const char *name, const struct object_id *oid, int want_file)
6973dcae 3492{
9c5e6c80 3493 const struct cache_entry *ce;
6973dcae
JH
3494 struct stat st;
3495 int pos, len;
3496
150115ad
JH
3497 /*
3498 * We do not read the cache ourselves here, because the
6973dcae
JH
3499 * benchmark with my previous version that always reads cache
3500 * shows that it makes things worse for diff-tree comparing
3501 * two linux-2.6 kernel trees in an already checked out work
3502 * tree. This is because most diff-tree comparisons deal with
3503 * only a small number of files, while reading the cache is
3504 * expensive for a large project, and its cost outweighs the
3505 * savings we get by not inflating the object to a temporary
3506 * file. Practically, this code only helps when we are used
3507 * by diff-cache --cached, which does read the cache before
3508 * calling us.
3509 */
3510 if (!active_cache)
3511 return 0;
3512
1510fea7
SP
3513 /* We want to avoid the working directory if our caller
3514 * doesn't need the data in a normal file, this system
3515 * is rather slow with its stat/open/mmap/close syscalls,
3516 * and the object is contained in a pack file. The pack
3517 * is probably already open and will be faster to obtain
3518 * the data through than the working directory. Loose
3519 * objects however would tend to be slower as they need
3520 * to be individually opened and inflated.
3521 */
fb4a1c0d 3522 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(oid->hash))
1510fea7
SP
3523 return 0;
3524
06dec439
JK
3525 /*
3526 * Similarly, if we'd have to convert the file contents anyway, that
3527 * makes the optimization not worthwhile.
3528 */
82b474e0 3529 if (!want_file && would_convert_to_git(&the_index, name))
06dec439
JK
3530 return 0;
3531
6973dcae
JH
3532 len = strlen(name);
3533 pos = cache_name_pos(name, len);
3534 if (pos < 0)
3535 return 0;
3536 ce = active_cache[pos];
eadb5831
JH
3537
3538 /*
3539 * This is not the sha1 we are looking for, or
3540 * unreusable because it is not a regular file.
3541 */
fb4a1c0d 3542 if (oidcmp(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
6973dcae 3543 return 0;
eadb5831 3544
150115ad
JH
3545 /*
3546 * If ce is marked as "assume unchanged", there is no
3547 * guarantee that work tree matches what we are looking for.
3548 */
b4d1690d 3549 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
150115ad
JH
3550 return 0;
3551
eadb5831
JH
3552 /*
3553 * If ce matches the file in the work tree, we can reuse it.
6973dcae 3554 */
eadb5831
JH
3555 if (ce_uptodate(ce) ||
3556 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
3557 return 1;
3558
3559 return 0;
6973dcae
JH
3560}
3561
04786756
LT
3562static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
3563{
b1ddfb91
JK
3564 struct strbuf buf = STRBUF_INIT;
3565 char *dirty = "";
8e08b419
JH
3566
3567 /* Are we looking at the work tree? */
85adbf2f 3568 if (s->dirty_submodule)
8e08b419
JH
3569 dirty = "-dirty";
3570
a0d12c44 3571 strbuf_addf(&buf, "Subproject commit %s%s\n",
3572 oid_to_hex(&s->oid), dirty);
b1ddfb91 3573 s->size = buf.len;
04786756
LT
3574 if (size_only) {
3575 s->data = NULL;
b1ddfb91
JK
3576 strbuf_release(&buf);
3577 } else {
3578 s->data = strbuf_detach(&buf, NULL);
3579 s->should_free = 1;
04786756
LT