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