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