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