Merge branch 'jc/maint-1.6.0-blank-at-eof' (early part) into jc/maint-blank-at-eof
[git/git.git] / diff.c
CommitLineData
6973dcae
JH
1/*
2 * Copyright (C) 2005 Junio C Hamano
3 */
6973dcae
JH
4#include "cache.h"
5#include "quote.h"
6#include "diff.h"
7#include "diffcore.h"
051308f6 8#include "delta.h"
6973dcae 9#include "xdiff-interface.h"
7c92fe0e 10#include "color.h"
8c701249 11#include "attr.h"
d5535ec7 12#include "run-command.h"
23707811 13#include "utf8.h"
be58e70d 14#include "userdiff.h"
4a16d072 15#include "sigchain.h"
6973dcae 16
1510fea7
SP
17#ifdef NO_FAST_WORKING_DIRECTORY
18#define FAST_WORKING_DIRECTORY 0
19#else
20#define FAST_WORKING_DIRECTORY 1
21#endif
22
96f1e58f 23static int diff_detect_rename_default;
50705915 24static int diff_rename_limit_default = 200;
a624eaa7 25static int diff_suppress_blank_empty;
6b2f2d98 26int diff_use_color_default = -1;
98a4d87b 27static const char *diff_word_regex_cfg;
cbe02100 28static const char *external_diff_cmd_cfg;
aecbf914 29int diff_auto_refresh_index = 1;
a5a818ee 30static int diff_mnemonic_prefix;
6973dcae 31
7c92fe0e 32static char diff_colors[][COLOR_MAXLEN] = {
dc6ebd4c
AL
33 GIT_COLOR_RESET,
34 GIT_COLOR_NORMAL, /* PLAIN */
35 GIT_COLOR_BOLD, /* METAINFO */
36 GIT_COLOR_CYAN, /* FRAGINFO */
37 GIT_COLOR_RED, /* OLD */
38 GIT_COLOR_GREEN, /* NEW */
39 GIT_COLOR_YELLOW, /* COMMIT */
40 GIT_COLOR_BG_RED, /* WHITESPACE */
cd112cef
JS
41};
42
9cb92c39
JK
43static void diff_filespec_load_driver(struct diff_filespec *one);
44static char *run_textconv(const char *, struct diff_filespec *, size_t *);
45
801235c5
JH
46static int parse_diff_color_slot(const char *var, int ofs)
47{
48 if (!strcasecmp(var+ofs, "plain"))
49 return DIFF_PLAIN;
50 if (!strcasecmp(var+ofs, "meta"))
51 return DIFF_METAINFO;
52 if (!strcasecmp(var+ofs, "frag"))
53 return DIFF_FRAGINFO;
54 if (!strcasecmp(var+ofs, "old"))
55 return DIFF_FILE_OLD;
56 if (!strcasecmp(var+ofs, "new"))
57 return DIFF_FILE_NEW;
ce436973
JK
58 if (!strcasecmp(var+ofs, "commit"))
59 return DIFF_COMMIT;
448c3ef1
JH
60 if (!strcasecmp(var+ofs, "whitespace"))
61 return DIFF_WHITESPACE;
801235c5
JH
62 die("bad config variable '%s'", var);
63}
64
cced5fbc
LT
65static int git_config_rename(const char *var, const char *value)
66{
67 if (!value)
68 return DIFF_DETECT_RENAME;
69 if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
70 return DIFF_DETECT_COPY;
71 return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
72}
73
83ad63cf
JH
74/*
75 * These are to give UI layer defaults.
76 * The core-level commands such as git-diff-files should
77 * never be affected by the setting of diff.renames
78 * the user happens to have in the configuration file.
79 */
ef90d6d4 80int git_diff_ui_config(const char *var, const char *value, void *cb)
801235c5 81{
a159ca0c 82 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
0f6f5a40 83 diff_use_color_default = git_config_colorbool(var, value, -1);
801235c5
JH
84 return 0;
85 }
b68ea12e 86 if (!strcmp(var, "diff.renames")) {
cced5fbc 87 diff_detect_rename_default = git_config_rename(var, value);
b68ea12e
EW
88 return 0;
89 }
aecbf914
JH
90 if (!strcmp(var, "diff.autorefreshindex")) {
91 diff_auto_refresh_index = git_config_bool(var, value);
92 return 0;
93 }
a5a818ee
JH
94 if (!strcmp(var, "diff.mnemonicprefix")) {
95 diff_mnemonic_prefix = git_config_bool(var, value);
96 return 0;
97 }
daec808c
BH
98 if (!strcmp(var, "diff.external"))
99 return git_config_string(&external_diff_cmd_cfg, var, value);
98a4d87b
BSSJ
100 if (!strcmp(var, "diff.wordregex"))
101 return git_config_string(&diff_word_regex_cfg, var, value);
f1af60bd 102
ef90d6d4 103 return git_diff_basic_config(var, value, cb);
9a1805a8
JK
104}
105
ef90d6d4 106int git_diff_basic_config(const char *var, const char *value, void *cb)
9a1805a8 107{
2b6ca6df
LT
108 if (!strcmp(var, "diff.renamelimit")) {
109 diff_rename_limit_default = git_config_int(var, value);
110 return 0;
111 }
112
c7534ef4
JK
113 switch (userdiff_config(var, value)) {
114 case 0: break;
115 case -1: return -1;
116 default: return 0;
117 }
118
1968d77d 119 if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
801235c5 120 int slot = parse_diff_color_slot(var, 11);
64f30e94
JH
121 if (!value)
122 return config_error_nonbool(var);
7c92fe0e 123 color_parse(value, var, diff_colors[slot]);
801235c5
JH
124 return 0;
125 }
f1af60bd 126
a624eaa7 127 /* like GNU diff's --suppress-blank-empty option */
950db879
JS
128 if (!strcmp(var, "diff.suppressblankempty") ||
129 /* for backwards compatibility */
130 !strcmp(var, "diff.suppress-blank-empty")) {
a624eaa7
JM
131 diff_suppress_blank_empty = git_config_bool(var, value);
132 return 0;
133 }
134
ef90d6d4 135 return git_color_default_config(var, value, cb);
801235c5
JH
136}
137
6973dcae
JH
138static char *quote_two(const char *one, const char *two)
139{
140 int need_one = quote_c_style(one, NULL, NULL, 1);
141 int need_two = quote_c_style(two, NULL, NULL, 1);
f285a2d7 142 struct strbuf res = STRBUF_INIT;
6973dcae
JH
143
144 if (need_one + need_two) {
663af342
PH
145 strbuf_addch(&res, '"');
146 quote_c_style(one, &res, NULL, 1);
147 quote_c_style(two, &res, NULL, 1);
148 strbuf_addch(&res, '"');
149 } else {
150 strbuf_addstr(&res, one);
151 strbuf_addstr(&res, two);
6973dcae 152 }
b315c5c0 153 return strbuf_detach(&res, NULL);
6973dcae
JH
154}
155
156static const char *external_diff(void)
157{
158 static const char *external_diff_cmd = NULL;
159 static int done_preparing = 0;
160
161 if (done_preparing)
162 return external_diff_cmd;
163 external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
cbe02100
JS
164 if (!external_diff_cmd)
165 external_diff_cmd = external_diff_cmd_cfg;
6973dcae
JH
166 done_preparing = 1;
167 return external_diff_cmd;
168}
169
6973dcae
JH
170static struct diff_tempfile {
171 const char *name; /* filename external diff should read from */
172 char hex[41];
173 char mode[10];
1472966c 174 char tmp_path[PATH_MAX];
6973dcae
JH
175} diff_temp[2];
176
6957eb9a
JH
177typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
178
179struct emit_callback {
6957eb9a
JH
180 int color_diff;
181 unsigned ws_rule;
182 int blank_at_eof_in_preimage;
183 int blank_at_eof_in_postimage;
184 int lno_in_preimage;
185 int lno_in_postimage;
186 sane_truncate_fn truncate;
187 const char **label_path;
188 struct diff_words_data *diff_words;
189 int *found_changesp;
190 FILE *file;
191};
192
6973dcae
JH
193static int count_lines(const char *data, int size)
194{
195 int count, ch, completely_empty = 1, nl_just_seen = 0;
196 count = 0;
197 while (0 < size--) {
198 ch = *data++;
199 if (ch == '\n') {
200 count++;
201 nl_just_seen = 1;
202 completely_empty = 0;
203 }
204 else {
205 nl_just_seen = 0;
206 completely_empty = 0;
207 }
208 }
209 if (completely_empty)
210 return 0;
211 if (!nl_just_seen)
212 count++; /* no trailing newline */
213 return count;
214}
215
6957eb9a
JH
216static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
217{
218 if (!DIFF_FILE_VALID(one)) {
219 mf->ptr = (char *)""; /* does not matter */
220 mf->size = 0;
221 return 0;
222 }
223 else if (diff_populate_filespec(one, 0))
224 return -1;
bb35fefb 225
6957eb9a
JH
226 mf->ptr = one->data;
227 mf->size = one->size;
228 return 0;
229}
230
231static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
232{
233 char *ptr = mf->ptr;
234 long size = mf->size;
235 int cnt = 0;
236
237 if (!size)
238 return cnt;
239 ptr += size - 1; /* pointing at the very end */
240 if (*ptr != '\n')
241 ; /* incomplete line */
242 else
243 ptr--; /* skip the last LF */
244 while (mf->ptr < ptr) {
245 char *prev_eol;
246 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
247 if (*prev_eol == '\n')
248 break;
249 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
250 break;
251 cnt++;
252 ptr = prev_eol - 1;
253 }
254 return cnt;
255}
256
257static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
258 struct emit_callback *ecbdata)
259{
260 int l1, l2, at;
261 unsigned ws_rule = ecbdata->ws_rule;
262 l1 = count_trailing_blank(mf1, ws_rule);
263 l2 = count_trailing_blank(mf2, ws_rule);
264 if (l2 <= l1) {
265 ecbdata->blank_at_eof_in_preimage = 0;
266 ecbdata->blank_at_eof_in_postimage = 0;
267 return;
268 }
269 at = count_lines(mf1->ptr, mf1->size);
270 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
271
272 at = count_lines(mf2->ptr, mf2->size);
273 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
274}
275
250f7993
JH
276static void emit_line_0(FILE *file, const char *set, const char *reset,
277 int first, const char *line, int len)
6957eb9a
JH
278{
279 int has_trailing_newline, has_trailing_carriage_return;
250f7993 280 int nofirst;
6957eb9a 281
250f7993
JH
282 if (len == 0) {
283 has_trailing_newline = (first == '\n');
284 has_trailing_carriage_return = (!has_trailing_newline &&
285 (first == '\r'));
286 nofirst = has_trailing_newline || has_trailing_carriage_return;
287 } else {
288 has_trailing_newline = (len > 0 && line[len-1] == '\n');
289 if (has_trailing_newline)
290 len--;
291 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
292 if (has_trailing_carriage_return)
293 len--;
294 nofirst = 0;
295 }
6957eb9a
JH
296
297 fputs(set, file);
250f7993
JH
298
299 if (!nofirst)
300 fputc(first, file);
6957eb9a
JH
301 fwrite(line, len, 1, file);
302 fputs(reset, file);
303 if (has_trailing_carriage_return)
304 fputc('\r', file);
305 if (has_trailing_newline)
306 fputc('\n', file);
307}
308
250f7993
JH
309static void emit_line(FILE *file, const char *set, const char *reset,
310 const char *line, int len)
311{
312 emit_line_0(file, set, reset, line[0], line+1, len-1);
313}
314
6957eb9a
JH
315static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
316{
317 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
318 ecbdata->blank_at_eof_in_preimage &&
319 ecbdata->blank_at_eof_in_postimage &&
320 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
321 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
322 return 0;
018cff70 323 return ws_blank_line(line, len, ecbdata->ws_rule);
6957eb9a
JH
324}
325
018cff70
JH
326static void emit_add_line(const char *reset,
327 struct emit_callback *ecbdata,
328 const char *line, int len)
6957eb9a
JH
329{
330 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
331 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
332
333 if (!*ws)
018cff70 334 emit_line_0(ecbdata->file, set, reset, '+', line, len);
6957eb9a
JH
335 else if (new_blank_line_at_eof(ecbdata, line, len))
336 /* Blank line at EOF - paint '+' as well */
018cff70 337 emit_line_0(ecbdata->file, ws, reset, '+', line, len);
6957eb9a
JH
338 else {
339 /* Emit just the prefix, then the rest. */
018cff70
JH
340 emit_line_0(ecbdata->file, set, reset, '+', "", 0);
341 ws_check_emit(line, len, ecbdata->ws_rule,
6957eb9a
JH
342 ecbdata->file, set, reset, ws);
343 }
344}
345
479b0ae8
JK
346static struct diff_tempfile *claim_diff_tempfile(void) {
347 int i;
348 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
349 if (!diff_temp[i].name)
350 return diff_temp + i;
351 die("BUG: diff is failing to clean up its tempfiles");
352}
353
354static int remove_tempfile_installed;
355
356static void remove_tempfile(void)
357{
358 int i;
a8344abe
NR
359 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
360 if (diff_temp[i].name == diff_temp[i].tmp_path)
691f1a28 361 unlink_or_warn(diff_temp[i].name);
a8344abe
NR
362 diff_temp[i].name = NULL;
363 }
479b0ae8
JK
364}
365
366static void remove_tempfile_on_signal(int signo)
367{
368 remove_tempfile();
4a16d072 369 sigchain_pop(signo);
479b0ae8
JK
370 raise(signo);
371}
372
c0c77734 373static void print_line_count(FILE *file, int count)
6973dcae
JH
374{
375 switch (count) {
376 case 0:
c0c77734 377 fprintf(file, "0,0");
6973dcae
JH
378 break;
379 case 1:
c0c77734 380 fprintf(file, "1");
6973dcae
JH
381 break;
382 default:
c0c77734 383 fprintf(file, "1,%d", count);
6973dcae
JH
384 break;
385 }
386}
387
c0c77734
DB
388static void copy_file_with_prefix(FILE *file,
389 int prefix, const char *data, int size,
1468bd47 390 const char *set, const char *reset)
6973dcae
JH
391{
392 int ch, nl_just_seen = 1;
393 while (0 < size--) {
394 ch = *data++;
13e36ec5 395 if (nl_just_seen) {
c0c77734
DB
396 fputs(set, file);
397 putc(prefix, file);
13e36ec5
JS
398 }
399 if (ch == '\n') {
6973dcae 400 nl_just_seen = 1;
c0c77734 401 fputs(reset, file);
13e36ec5 402 } else
6973dcae 403 nl_just_seen = 0;
c0c77734 404 putc(ch, file);
6973dcae
JH
405 }
406 if (!nl_just_seen)
c0c77734 407 fprintf(file, "%s\n\\ No newline at end of file\n", reset);
6973dcae
JH
408}
409
410static void emit_rewrite_diff(const char *name_a,
411 const char *name_b,
412 struct diff_filespec *one,
13e36ec5 413 struct diff_filespec *two,
3aa1f7ca
JK
414 const char *textconv_one,
415 const char *textconv_two,
eab9a40b 416 struct diff_options *o)
6973dcae
JH
417{
418 int lc_a, lc_b;
eab9a40b 419 int color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
1a9eb3b9 420 const char *name_a_tab, *name_b_tab;
13e36ec5
JS
421 const char *metainfo = diff_get_color(color_diff, DIFF_METAINFO);
422 const char *fraginfo = diff_get_color(color_diff, DIFF_FRAGINFO);
423 const char *old = diff_get_color(color_diff, DIFF_FILE_OLD);
424 const char *new = diff_get_color(color_diff, DIFF_FILE_NEW);
425 const char *reset = diff_get_color(color_diff, DIFF_RESET);
d5625091 426 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
a5a818ee 427 const char *a_prefix, *b_prefix;
3aa1f7ca
JK
428 const char *data_one, *data_two;
429 size_t size_one, size_two;
a5a818ee
JH
430
431 if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
432 a_prefix = o->b_prefix;
433 b_prefix = o->a_prefix;
434 } else {
435 a_prefix = o->a_prefix;
436 b_prefix = o->b_prefix;
437 }
1a9eb3b9 438
8a13becc
JH
439 name_a += (*name_a == '/');
440 name_b += (*name_b == '/');
1a9eb3b9
JH
441 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
442 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
443
d5625091
JH
444 strbuf_reset(&a_name);
445 strbuf_reset(&b_name);
a5a818ee
JH
446 quote_two_c_style(&a_name, a_prefix, name_a, 0);
447 quote_two_c_style(&b_name, b_prefix, name_b, 0);
d5625091 448
6973dcae
JH
449 diff_populate_filespec(one, 0);
450 diff_populate_filespec(two, 0);
3aa1f7ca
JK
451 if (textconv_one) {
452 data_one = run_textconv(textconv_one, one, &size_one);
453 if (!data_one)
454 die("unable to read files to diff");
455 }
456 else {
457 data_one = one->data;
458 size_one = one->size;
459 }
460 if (textconv_two) {
461 data_two = run_textconv(textconv_two, two, &size_two);
462 if (!data_two)
463 die("unable to read files to diff");
464 }
465 else {
466 data_two = two->data;
467 size_two = two->size;
468 }
469
470 lc_a = count_lines(data_one, size_one);
471 lc_b = count_lines(data_two, size_two);
c0c77734
DB
472 fprintf(o->file,
473 "%s--- %s%s%s\n%s+++ %s%s%s\n%s@@ -",
474 metainfo, a_name.buf, name_a_tab, reset,
475 metainfo, b_name.buf, name_b_tab, reset, fraginfo);
476 print_line_count(o->file, lc_a);
477 fprintf(o->file, " +");
478 print_line_count(o->file, lc_b);
479 fprintf(o->file, " @@%s\n", reset);
6973dcae 480 if (lc_a)
3aa1f7ca 481 copy_file_with_prefix(o->file, '-', data_one, size_one, old, reset);
6973dcae 482 if (lc_b)
3aa1f7ca 483 copy_file_with_prefix(o->file, '+', data_two, size_two, new, reset);
6973dcae
JH
484}
485
f59a59e2
JS
486struct diff_words_buffer {
487 mmfile_t text;
488 long alloc;
2e5d2003
JS
489 struct diff_words_orig {
490 const char *begin, *end;
491 } *orig;
492 int orig_nr, orig_alloc;
f59a59e2
JS
493};
494
495static void diff_words_append(char *line, unsigned long len,
496 struct diff_words_buffer *buffer)
497{
23c1575f 498 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
f59a59e2
JS
499 line++;
500 len--;
501 memcpy(buffer->text.ptr + buffer->text.size, line, len);
502 buffer->text.size += len;
2b6a5417 503 buffer->text.ptr[buffer->text.size] = '\0';
f59a59e2
JS
504}
505
506struct diff_words_data {
f59a59e2 507 struct diff_words_buffer minus, plus;
2e5d2003 508 const char *current_plus;
c0c77734 509 FILE *file;
2b6a5417 510 regex_t *word_regex;
f59a59e2
JS
511};
512
f59a59e2 513static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
f59a59e2 514{
f59a59e2 515 struct diff_words_data *diff_words = priv;
2e5d2003
JS
516 int minus_first, minus_len, plus_first, plus_len;
517 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
f59a59e2 518
2e5d2003
JS
519 if (line[0] != '@' || parse_hunk_header(line, len,
520 &minus_first, &minus_len, &plus_first, &plus_len))
f59a59e2
JS
521 return;
522
2e5d2003
JS
523 /* POSIX requires that first be decremented by one if len == 0... */
524 if (minus_len) {
525 minus_begin = diff_words->minus.orig[minus_first].begin;
526 minus_end =
527 diff_words->minus.orig[minus_first + minus_len - 1].end;
528 } else
529 minus_begin = minus_end =
530 diff_words->minus.orig[minus_first].end;
531
532 if (plus_len) {
533 plus_begin = diff_words->plus.orig[plus_first].begin;
534 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
535 } else
536 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
537
538 if (diff_words->current_plus != plus_begin)
539 fwrite(diff_words->current_plus,
540 plus_begin - diff_words->current_plus, 1,
541 diff_words->file);
542 if (minus_begin != minus_end)
543 color_fwrite_lines(diff_words->file,
544 diff_get_color(1, DIFF_FILE_OLD),
545 minus_end - minus_begin, minus_begin);
546 if (plus_begin != plus_end)
547 color_fwrite_lines(diff_words->file,
548 diff_get_color(1, DIFF_FILE_NEW),
549 plus_end - plus_begin, plus_begin);
550
551 diff_words->current_plus = plus_end;
f59a59e2
JS
552}
553
2b6a5417
JS
554/* This function starts looking at *begin, and returns 0 iff a word was found. */
555static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
556 int *begin, int *end)
557{
558 if (word_regex && *begin < buffer->size) {
559 regmatch_t match[1];
560 if (!regexec(word_regex, buffer->ptr + *begin, 1, match, 0)) {
561 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
562 '\n', match[0].rm_eo - match[0].rm_so);
563 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
564 *begin += match[0].rm_so;
565 return *begin >= *end;
566 }
567 return -1;
f59a59e2
JS
568 }
569
2b6a5417
JS
570 /* find the next word */
571 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
572 (*begin)++;
573 if (*begin >= buffer->size)
574 return -1;
f59a59e2 575
2b6a5417
JS
576 /* find the end of the word */
577 *end = *begin + 1;
578 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
579 (*end)++;
580
581 return 0;
f59a59e2
JS
582}
583
23c1575f 584/*
2e5d2003
JS
585 * This function splits the words in buffer->text, stores the list with
586 * newline separator into out, and saves the offsets of the original words
587 * in buffer->orig.
23c1575f 588 */
2b6a5417
JS
589static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
590 regex_t *word_regex)
f59a59e2 591{
2e5d2003 592 int i, j;
2b6a5417 593 long alloc = 0;
f59a59e2 594
2e5d2003 595 out->size = 0;
2b6a5417 596 out->ptr = NULL;
f59a59e2 597
2e5d2003
JS
598 /* fake an empty "0th" word */
599 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
600 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
601 buffer->orig_nr = 1;
602
603 for (i = 0; i < buffer->text.size; i++) {
2b6a5417
JS
604 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
605 return;
2e5d2003
JS
606
607 /* store original boundaries */
608 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
609 buffer->orig_alloc);
610 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
611 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
612 buffer->orig_nr++;
613
614 /* store one word */
2b6a5417 615 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
2e5d2003
JS
616 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
617 out->ptr[out->size + j - i] = '\n';
618 out->size += j - i + 1;
619
620 i = j - 1;
f59a59e2
JS
621 }
622}
623
624/* this executes the word diff on the accumulated buffers */
625static void diff_words_show(struct diff_words_data *diff_words)
626{
627 xpparam_t xpp;
628 xdemitconf_t xecfg;
629 xdemitcb_t ecb;
630 mmfile_t minus, plus;
f59a59e2 631
2e5d2003
JS
632 /* special case: only removal */
633 if (!diff_words->plus.text.size) {
634 color_fwrite_lines(diff_words->file,
635 diff_get_color(1, DIFF_FILE_OLD),
636 diff_words->minus.text.size, diff_words->minus.text.ptr);
637 diff_words->minus.text.size = 0;
638 return;
639 }
640
641 diff_words->current_plus = diff_words->plus.text.ptr;
f59a59e2 642
9ccd0a88 643 memset(&xpp, 0, sizeof(xpp));
30b25010 644 memset(&xecfg, 0, sizeof(xecfg));
2b6a5417
JS
645 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
646 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
f59a59e2 647 xpp.flags = XDF_NEED_MINIMAL;
2b6a5417 648 /* as only the hunk header will be parsed, we need a 0-context */
2e5d2003 649 xecfg.ctxlen = 0;
8a3f524b
JH
650 xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
651 &xpp, &xecfg, &ecb);
f59a59e2
JS
652 free(minus.ptr);
653 free(plus.ptr);
2e5d2003
JS
654 if (diff_words->current_plus != diff_words->plus.text.ptr +
655 diff_words->plus.text.size)
656 fwrite(diff_words->current_plus,
657 diff_words->plus.text.ptr + diff_words->plus.text.size
658 - diff_words->current_plus, 1,
659 diff_words->file);
f59a59e2 660 diff_words->minus.text.size = diff_words->plus.text.size = 0;
f59a59e2
JS
661}
662
f59a59e2
JS
663static void free_diff_words_data(struct emit_callback *ecbdata)
664{
665 if (ecbdata->diff_words) {
666 /* flush buffers */
667 if (ecbdata->diff_words->minus.text.size ||
668 ecbdata->diff_words->plus.text.size)
669 diff_words_show(ecbdata->diff_words);
670
8e0f7003 671 free (ecbdata->diff_words->minus.text.ptr);
2e5d2003 672 free (ecbdata->diff_words->minus.orig);
8e0f7003 673 free (ecbdata->diff_words->plus.text.ptr);
2e5d2003 674 free (ecbdata->diff_words->plus.orig);
2b6a5417 675 free(ecbdata->diff_words->word_regex);
f59a59e2
JS
676 free(ecbdata->diff_words);
677 ecbdata->diff_words = NULL;
678 }
679}
680
ce436973 681const char *diff_get_color(int diff_use_color, enum color_diff ix)
cd112cef
JS
682{
683 if (diff_use_color)
50f575fc
LT
684 return diff_colors[ix];
685 return "";
cd112cef
JS
686}
687
23707811
JH
688static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
689{
690 const char *cp;
691 unsigned long allot;
692 size_t l = len;
693
694 if (ecb->truncate)
695 return ecb->truncate(line, len);
696 cp = line;
697 allot = l;
698 while (0 < l) {
699 (void) utf8_width(&cp, &l);
700 if (!cp)
701 break; /* truncated in the middle? */
702 }
703 return allot - l;
704}
705
d68fe26f 706static void find_lno(const char *line, struct emit_callback *ecbdata)
690ed843 707{
d68fe26f
JH
708 const char *p;
709 ecbdata->lno_in_preimage = 0;
710 ecbdata->lno_in_postimage = 0;
711 p = strchr(line, '-');
690ed843 712 if (!p)
d68fe26f
JH
713 return; /* cannot happen */
714 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
715 p = strchr(p, '+');
716 if (!p)
717 return; /* cannot happen */
718 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
690ed843
JH
719}
720
cd112cef 721static void fn_out_consume(void *priv, char *line, unsigned long len)
6973dcae 722{
6973dcae 723 struct emit_callback *ecbdata = priv;
472ca780
JK
724 const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
725 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
ce436973 726 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
6973dcae 727
34a5e1a2
JS
728 *(ecbdata->found_changesp) = 1;
729
6973dcae 730 if (ecbdata->label_path[0]) {
1a9eb3b9
JH
731 const char *name_a_tab, *name_b_tab;
732
733 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
734 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
735
c0c77734
DB
736 fprintf(ecbdata->file, "%s--- %s%s%s\n",
737 meta, ecbdata->label_path[0], reset, name_a_tab);
738 fprintf(ecbdata->file, "%s+++ %s%s%s\n",
739 meta, ecbdata->label_path[1], reset, name_b_tab);
6973dcae
JH
740 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
741 }
cd112cef 742
a624eaa7
JM
743 if (diff_suppress_blank_empty
744 && len == 2 && line[0] == ' ' && line[1] == '\n') {
745 line[0] = '\n';
746 len = 1;
747 }
748
b8d9c1a6 749 if (line[0] == '@') {
23707811 750 len = sane_truncate_line(ecbdata, line, len);
d68fe26f 751 find_lno(line, ecbdata);
c0c77734
DB
752 emit_line(ecbdata->file,
753 diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO),
448c3ef1 754 reset, line, len);
23707811 755 if (line[len-1] != '\n')
c0c77734 756 putc('\n', ecbdata->file);
448c3ef1 757 return;
cd112cef 758 }
448c3ef1 759
b8d9c1a6 760 if (len < 1) {
c0c77734 761 emit_line(ecbdata->file, reset, reset, line, len);
448c3ef1 762 return;
cd112cef 763 }
448c3ef1 764
448c3ef1
JH
765 if (ecbdata->diff_words) {
766 if (line[0] == '-') {
767 diff_words_append(line, len,
768 &ecbdata->diff_words->minus);
769 return;
770 } else if (line[0] == '+') {
771 diff_words_append(line, len,
772 &ecbdata->diff_words->plus);
773 return;
774 }
775 if (ecbdata->diff_words->minus.text.size ||
776 ecbdata->diff_words->plus.text.size)
777 diff_words_show(ecbdata->diff_words);
778 line++;
50f575fc 779 len--;
c0c77734 780 emit_line(ecbdata->file, plain, reset, line, len);
448c3ef1
JH
781 return;
782 }
448c3ef1 783
690ed843
JH
784 if (line[0] != '+') {
785 const char *color =
786 diff_get_color(ecbdata->color_diff,
787 line[0] == '-' ? DIFF_FILE_OLD : DIFF_PLAIN);
788 ecbdata->lno_in_preimage++;
d68fe26f
JH
789 if (line[0] == ' ')
790 ecbdata->lno_in_postimage++;
690ed843 791 emit_line(ecbdata->file, color, reset, line, len);
d68fe26f
JH
792 } else {
793 ecbdata->lno_in_postimage++;
018cff70 794 emit_add_line(reset, ecbdata, line + 1, len - 1);
448c3ef1 795 }
6973dcae
JH
796}
797
798static char *pprint_rename(const char *a, const char *b)
799{
800 const char *old = a;
801 const char *new = b;
f285a2d7 802 struct strbuf name = STRBUF_INIT;
6973dcae
JH
803 int pfx_length, sfx_length;
804 int len_a = strlen(a);
805 int len_b = strlen(b);
663af342 806 int a_midlen, b_midlen;
e5bfbf9b
AJ
807 int qlen_a = quote_c_style(a, NULL, NULL, 0);
808 int qlen_b = quote_c_style(b, NULL, NULL, 0);
809
810 if (qlen_a || qlen_b) {
663af342
PH
811 quote_c_style(a, &name, NULL, 0);
812 strbuf_addstr(&name, " => ");
813 quote_c_style(b, &name, NULL, 0);
b315c5c0 814 return strbuf_detach(&name, NULL);
e5bfbf9b 815 }
6973dcae
JH
816
817 /* Find common prefix */
818 pfx_length = 0;
819 while (*old && *new && *old == *new) {
820 if (*old == '/')
821 pfx_length = old - a + 1;
822 old++;
823 new++;
824 }
825
826 /* Find common suffix */
827 old = a + len_a;
828 new = b + len_b;
829 sfx_length = 0;
830 while (a <= old && b <= new && *old == *new) {
831 if (*old == '/')
832 sfx_length = len_a - (old - a);
833 old--;
834 new--;
835 }
836
837 /*
838 * pfx{mid-a => mid-b}sfx
839 * {pfx-a => pfx-b}sfx
840 * pfx{sfx-a => sfx-b}
841 * name-a => name-b
842 */
663af342
PH
843 a_midlen = len_a - pfx_length - sfx_length;
844 b_midlen = len_b - pfx_length - sfx_length;
845 if (a_midlen < 0)
846 a_midlen = 0;
847 if (b_midlen < 0)
848 b_midlen = 0;
849
850 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
6973dcae 851 if (pfx_length + sfx_length) {
663af342
PH
852 strbuf_add(&name, a, pfx_length);
853 strbuf_addch(&name, '{');
6973dcae 854 }
663af342
PH
855 strbuf_add(&name, a + pfx_length, a_midlen);
856 strbuf_addstr(&name, " => ");
857 strbuf_add(&name, b + pfx_length, b_midlen);
858 if (pfx_length + sfx_length) {
859 strbuf_addch(&name, '}');
860 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
6973dcae 861 }
b315c5c0 862 return strbuf_detach(&name, NULL);
6973dcae
JH
863}
864
865struct diffstat_t {
6973dcae
JH
866 int nr;
867 int alloc;
868 struct diffstat_file {
f604652e 869 char *from_name;
6973dcae 870 char *name;
f604652e 871 char *print_name;
6973dcae
JH
872 unsigned is_unmerged:1;
873 unsigned is_binary:1;
874 unsigned is_renamed:1;
875 unsigned int added, deleted;
876 } **files;
877};
878
879static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
880 const char *name_a,
881 const char *name_b)
882{
883 struct diffstat_file *x;
884 x = xcalloc(sizeof (*x), 1);
885 if (diffstat->nr == diffstat->alloc) {
886 diffstat->alloc = alloc_nr(diffstat->alloc);
887 diffstat->files = xrealloc(diffstat->files,
888 diffstat->alloc * sizeof(x));
889 }
890 diffstat->files[diffstat->nr++] = x;
891 if (name_b) {
f604652e
JH
892 x->from_name = xstrdup(name_a);
893 x->name = xstrdup(name_b);
6973dcae
JH
894 x->is_renamed = 1;
895 }
f604652e
JH
896 else {
897 x->from_name = NULL;
9befac47 898 x->name = xstrdup(name_a);
f604652e 899 }
6973dcae
JH
900 return x;
901}
902
903static void diffstat_consume(void *priv, char *line, unsigned long len)
904{
905 struct diffstat_t *diffstat = priv;
906 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
907
908 if (line[0] == '+')
909 x->added++;
910 else if (line[0] == '-')
911 x->deleted++;
912}
913
698ce6f8 914const char mime_boundary_leader[] = "------------";
6973dcae 915
a2540023
JH
916static int scale_linear(int it, int width, int max_change)
917{
918 /*
3ed74e60
JS
919 * make sure that at least one '-' is printed if there were deletions,
920 * and likewise for '+'.
a2540023 921 */
3ed74e60
JS
922 if (max_change < 2)
923 return it;
924 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
a2540023
JH
925}
926
c0c77734 927static void show_name(FILE *file,
a408e0e6 928 const char *prefix, const char *name, int len)
a2540023 929{
a408e0e6 930 fprintf(file, " %s%-*s |", prefix, len, name);
a2540023
JH
931}
932
c0c77734 933static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
a2540023
JH
934{
935 if (cnt <= 0)
936 return;
c0c77734 937 fprintf(file, "%s", set);
a2540023 938 while (cnt--)
c0c77734
DB
939 putc(ch, file);
940 fprintf(file, "%s", reset);
a2540023
JH
941}
942
f604652e
JH
943static void fill_print_name(struct diffstat_file *file)
944{
945 char *pname;
946
947 if (file->print_name)
948 return;
949
950 if (!file->is_renamed) {
f285a2d7 951 struct strbuf buf = STRBUF_INIT;
f604652e
JH
952 if (quote_c_style(file->name, &buf, NULL, 0)) {
953 pname = strbuf_detach(&buf, NULL);
954 } else {
955 pname = file->name;
956 strbuf_release(&buf);
957 }
958 } else {
959 pname = pprint_rename(file->from_name, file->name);
960 }
961 file->print_name = pname;
962}
963
4b25d091 964static void show_stats(struct diffstat_t *data, struct diff_options *options)
6973dcae 965{
eb3a9dd3 966 int i, len, add, del, adds = 0, dels = 0;
a2540023 967 int max_change = 0, max_len = 0;
6973dcae 968 int total_files = data->nr;
a2540023 969 int width, name_width;
785f7432 970 const char *reset, *set, *add_c, *del_c;
6973dcae
JH
971
972 if (data->nr == 0)
973 return;
974
a2540023
JH
975 width = options->stat_width ? options->stat_width : 80;
976 name_width = options->stat_name_width ? options->stat_name_width : 50;
977
978 /* Sanity: give at least 5 columns to the graph,
979 * but leave at least 10 columns for the name.
980 */
861d1af3
OM
981 if (width < 25)
982 width = 25;
983 if (name_width < 10)
984 name_width = 10;
985 else if (width < name_width + 15)
986 name_width = width - 15;
a2540023
JH
987
988 /* Find the longest filename and max number of changes */
8f67f8ae
PH
989 reset = diff_get_color_opt(options, DIFF_RESET);
990 set = diff_get_color_opt(options, DIFF_PLAIN);
991 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
992 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
785f7432 993
6973dcae
JH
994 for (i = 0; i < data->nr; i++) {
995 struct diffstat_file *file = data->files[i];
a2540023 996 int change = file->added + file->deleted;
f604652e
JH
997 fill_print_name(file);
998 len = strlen(file->print_name);
6973dcae
JH
999 if (max_len < len)
1000 max_len = len;
1001
1002 if (file->is_binary || file->is_unmerged)
1003 continue;
a2540023
JH
1004 if (max_change < change)
1005 max_change = change;
6973dcae
JH
1006 }
1007
a2540023
JH
1008 /* Compute the width of the graph part;
1009 * 10 is for one blank at the beginning of the line plus
1010 * " | count " between the name and the graph.
1011 *
1012 * From here on, name_width is the width of the name area,
1013 * and width is the width of the graph area.
1014 */
1015 name_width = (name_width < max_len) ? name_width : max_len;
1016 if (width < (name_width + 10) + max_change)
1017 width = width - (name_width + 10);
1018 else
1019 width = max_change;
1020
6973dcae 1021 for (i = 0; i < data->nr; i++) {
d2543b8e 1022 const char *prefix = "";
f604652e 1023 char *name = data->files[i]->print_name;
6973dcae
JH
1024 int added = data->files[i]->added;
1025 int deleted = data->files[i]->deleted;
a2540023 1026 int name_len;
6973dcae
JH
1027
1028 /*
1029 * "scale" the filename
1030 */
a2540023
JH
1031 len = name_width;
1032 name_len = strlen(name);
1033 if (name_width < name_len) {
6973dcae
JH
1034 char *slash;
1035 prefix = "...";
a2540023
JH
1036 len -= 3;
1037 name += name_len - len;
6973dcae
JH
1038 slash = strchr(name, '/');
1039 if (slash)
1040 name = slash;
1041 }
6973dcae
JH
1042
1043 if (data->files[i]->is_binary) {
a408e0e6 1044 show_name(options->file, prefix, name, len);
c0c77734
DB
1045 fprintf(options->file, " Bin ");
1046 fprintf(options->file, "%s%d%s", del_c, deleted, reset);
1047 fprintf(options->file, " -> ");
1048 fprintf(options->file, "%s%d%s", add_c, added, reset);
1049 fprintf(options->file, " bytes");
1050 fprintf(options->file, "\n");
f604652e 1051 continue;
6973dcae
JH
1052 }
1053 else if (data->files[i]->is_unmerged) {
a408e0e6 1054 show_name(options->file, prefix, name, len);
c0c77734 1055 fprintf(options->file, " Unmerged\n");
f604652e 1056 continue;
6973dcae
JH
1057 }
1058 else if (!data->files[i]->is_renamed &&
1059 (added + deleted == 0)) {
1060 total_files--;
f604652e 1061 continue;
6973dcae
JH
1062 }
1063
a2540023
JH
1064 /*
1065 * scale the add/delete
1066 */
6973dcae
JH
1067 add = added;
1068 del = deleted;
6973dcae
JH
1069 adds += add;
1070 dels += del;
1071
a2540023 1072 if (width <= max_change) {
a2540023 1073 add = scale_linear(add, width, max_change);
3ed74e60 1074 del = scale_linear(del, width, max_change);
6973dcae 1075 }
a408e0e6 1076 show_name(options->file, prefix, name, len);
4d9b5359
JK
1077 fprintf(options->file, "%5d%s", added + deleted,
1078 added + deleted ? " " : "");
c0c77734
DB
1079 show_graph(options->file, '+', add, add_c, reset);
1080 show_graph(options->file, '-', del, del_c, reset);
1081 fprintf(options->file, "\n");
1082 }
1083 fprintf(options->file,
a408e0e6
MH
1084 " %d files changed, %d insertions(+), %d deletions(-)\n",
1085 total_files, adds, dels);
6973dcae
JH
1086}
1087
c0c77734 1088static void show_shortstats(struct diffstat_t* data, struct diff_options *options)
ebd124c6
NP
1089{
1090 int i, adds = 0, dels = 0, total_files = data->nr;
1091
1092 if (data->nr == 0)
1093 return;
1094
1095 for (i = 0; i < data->nr; i++) {
1096 if (!data->files[i]->is_binary &&
1097 !data->files[i]->is_unmerged) {
1098 int added = data->files[i]->added;
1099 int deleted= data->files[i]->deleted;
1100 if (!data->files[i]->is_renamed &&
1101 (added + deleted == 0)) {
1102 total_files--;
1103 } else {
1104 adds += added;
1105 dels += deleted;
1106 }
1107 }
ebd124c6 1108 }
c0c77734 1109 fprintf(options->file, " %d files changed, %d insertions(+), %d deletions(-)\n",
ebd124c6
NP
1110 total_files, adds, dels);
1111}
1112
4b25d091 1113static void show_numstat(struct diffstat_t *data, struct diff_options *options)
74e2abe5
JH
1114{
1115 int i;
1116
f604652e
JH
1117 if (data->nr == 0)
1118 return;
1119
74e2abe5
JH
1120 for (i = 0; i < data->nr; i++) {
1121 struct diffstat_file *file = data->files[i];
1122
bfddbc5e 1123 if (file->is_binary)
c0c77734 1124 fprintf(options->file, "-\t-\t");
bfddbc5e 1125 else
c0c77734
DB
1126 fprintf(options->file,
1127 "%d\t%d\t", file->added, file->deleted);
f604652e
JH
1128 if (options->line_termination) {
1129 fill_print_name(file);
1130 if (!file->is_renamed)
c0c77734 1131 write_name_quoted(file->name, options->file,
f604652e
JH
1132 options->line_termination);
1133 else {
c0c77734
DB
1134 fputs(file->print_name, options->file);
1135 putc(options->line_termination, options->file);
f604652e 1136 }
663af342 1137 } else {
f604652e 1138 if (file->is_renamed) {
c0c77734
DB
1139 putc('\0', options->file);
1140 write_name_quoted(file->from_name, options->file, '\0');
f604652e 1141 }
c0c77734 1142 write_name_quoted(file->name, options->file, '\0');
663af342 1143 }
74e2abe5
JH
1144 }
1145}
1146
c04a7155
JH
1147struct dirstat_file {
1148 const char *name;
1149 unsigned long changed;
7df7c019
LT
1150};
1151
c04a7155
JH
1152struct dirstat_dir {
1153 struct dirstat_file *files;
1154 int alloc, nr, percent, cumulative;
1155};
1156
1157static long gather_dirstat(FILE *file, struct dirstat_dir *dir, unsigned long changed, const char *base, int baselen)
7df7c019
LT
1158{
1159 unsigned long this_dir = 0;
1160 unsigned int sources = 0;
1161
1162 while (dir->nr) {
c04a7155 1163 struct dirstat_file *f = dir->files;
7df7c019
LT
1164 int namelen = strlen(f->name);
1165 unsigned long this;
1166 char *slash;
1167
1168 if (namelen < baselen)
1169 break;
1170 if (memcmp(f->name, base, baselen))
1171 break;
1172 slash = strchr(f->name + baselen, '/');
1173 if (slash) {
1174 int newbaselen = slash + 1 - f->name;
c0c77734 1175 this = gather_dirstat(file, dir, changed, f->name, newbaselen);
7df7c019
LT
1176 sources++;
1177 } else {
c04a7155 1178 this = f->changed;
7df7c019
LT
1179 dir->files++;
1180 dir->nr--;
1181 sources += 2;
1182 }
1183 this_dir += this;
1184 }
1185
1186 /*
1187 * We don't report dirstat's for
1188 * - the top level
1189 * - or cases where everything came from a single directory
1190 * under this directory (sources == 1).
1191 */
1192 if (baselen && sources != 1) {
1193 int permille = this_dir * 1000 / changed;
1194 if (permille) {
1195 int percent = permille / 10;
1196 if (percent >= dir->percent) {
c0c77734 1197 fprintf(file, "%4d.%01d%% %.*s\n", percent, permille % 10, baselen, base);
7df7c019
LT
1198 if (!dir->cumulative)
1199 return 0;
1200 }
1201 }
1202 }
1203 return this_dir;
1204}
1205
441bca0b
LT
1206static int dirstat_compare(const void *_a, const void *_b)
1207{
1208 const struct dirstat_file *a = _a;
1209 const struct dirstat_file *b = _b;
1210 return strcmp(a->name, b->name);
1211}
1212
c04a7155 1213static void show_dirstat(struct diff_options *options)
7df7c019
LT
1214{
1215 int i;
1216 unsigned long changed;
c04a7155
JH
1217 struct dirstat_dir dir;
1218 struct diff_queue_struct *q = &diff_queued_diff;
1219
1220 dir.files = NULL;
1221 dir.alloc = 0;
1222 dir.nr = 0;
1223 dir.percent = options->dirstat_percent;
f88d225f 1224 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
7df7c019 1225
7df7c019 1226 changed = 0;
c04a7155
JH
1227 for (i = 0; i < q->nr; i++) {
1228 struct diff_filepair *p = q->queue[i];
1229 const char *name;
1230 unsigned long copied, added, damage;
1231
1232 name = p->one->path ? p->one->path : p->two->path;
1233
1234 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1235 diff_populate_filespec(p->one, 0);
1236 diff_populate_filespec(p->two, 0);
1237 diffcore_count_changes(p->one, p->two, NULL, NULL, 0,
1238 &copied, &added);
1239 diff_free_filespec_data(p->one);
1240 diff_free_filespec_data(p->two);
1241 } else if (DIFF_FILE_VALID(p->one)) {
1242 diff_populate_filespec(p->one, 1);
1243 copied = added = 0;
1244 diff_free_filespec_data(p->one);
1245 } else if (DIFF_FILE_VALID(p->two)) {
1246 diff_populate_filespec(p->two, 1);
1247 copied = 0;
1248 added = p->two->size;
1249 diff_free_filespec_data(p->two);
1250 } else
2b0b551d 1251 continue;
c04a7155
JH
1252
1253 /*
1254 * Original minus copied is the removed material,
1255 * added is the new material. They are both damages
fd33777b
HO
1256 * made to the preimage. In --dirstat-by-file mode, count
1257 * damaged files, not damaged lines. This is done by
1258 * counting only a single damaged line per file.
c04a7155
JH
1259 */
1260 damage = (p->one->size - copied) + added;
fd33777b
HO
1261 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE) && damage > 0)
1262 damage = 1;
c04a7155
JH
1263
1264 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1265 dir.files[dir.nr].name = name;
1266 dir.files[dir.nr].changed = damage;
1267 changed += damage;
1268 dir.nr++;
7df7c019
LT
1269 }
1270
1271 /* This can happen even with many files, if everything was renames */
1272 if (!changed)
1273 return;
1274
1275 /* Show all directories with more than x% of the changes */
441bca0b 1276 qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
c0c77734 1277 gather_dirstat(options->file, &dir, changed, "", 0);
7df7c019
LT
1278}
1279
f604652e
JH
1280static void free_diffstat_info(struct diffstat_t *diffstat)
1281{
1282 int i;
1283 for (i = 0; i < diffstat->nr; i++) {
1284 struct diffstat_file *f = diffstat->files[i];
1285 if (f->name != f->print_name)
1286 free(f->print_name);
1287 free(f->name);
1288 free(f->from_name);
1289 free(f);
1290 }
1291 free(diffstat->files);
1292}
1293
88246898 1294struct checkdiff_t {
88246898 1295 const char *filename;
1ba111d1
JH
1296 int lineno;
1297 struct diff_options *o;
cf1b7869 1298 unsigned ws_rule;
62c64895 1299 unsigned status;
88246898
JS
1300};
1301
04954043
JH
1302static int is_conflict_marker(const char *line, unsigned long len)
1303{
1304 char firstchar;
1305 int cnt;
1306
1307 if (len < 8)
1308 return 0;
1309 firstchar = line[0];
1310 switch (firstchar) {
1311 case '=': case '>': case '<':
1312 break;
1313 default:
1314 return 0;
1315 }
1316 for (cnt = 1; cnt < 7; cnt++)
1317 if (line[cnt] != firstchar)
1318 return 0;
1319 /* line[0] thru line[6] are same as firstchar */
1320 if (firstchar == '=') {
1321 /* divider between ours and theirs? */
1322 if (len != 8 || line[7] != '\n')
1323 return 0;
1324 } else if (len < 8 || !isspace(line[7])) {
1325 /* not divider before ours nor after theirs */
1326 return 0;
1327 }
1328 return 1;
1329}
1330
88246898
JS
1331static void checkdiff_consume(void *priv, char *line, unsigned long len)
1332{
1333 struct checkdiff_t *data = priv;
1ba111d1
JH
1334 int color_diff = DIFF_OPT_TST(data->o, COLOR_DIFF);
1335 const char *ws = diff_get_color(color_diff, DIFF_WHITESPACE);
1336 const char *reset = diff_get_color(color_diff, DIFF_RESET);
1337 const char *set = diff_get_color(color_diff, DIFF_FILE_NEW);
c1795bb0 1338 char *err;
88246898
JS
1339
1340 if (line[0] == '+') {
18374e58 1341 unsigned bad;
0ef617f4 1342 data->lineno++;
04954043
JH
1343 if (is_conflict_marker(line + 1, len - 1)) {
1344 data->status |= 1;
1345 fprintf(data->o->file,
1346 "%s:%d: leftover conflict marker\n",
1347 data->filename, data->lineno);
1348 }
8f8841e9 1349 bad = ws_check(line + 1, len - 1, data->ws_rule);
18374e58 1350 if (!bad)
c1795bb0 1351 return;
18374e58
JH
1352 data->status |= bad;
1353 err = whitespace_error_string(bad);
1ba111d1
JH
1354 fprintf(data->o->file, "%s:%d: %s.\n",
1355 data->filename, data->lineno, err);
c1795bb0 1356 free(err);
1ba111d1 1357 emit_line(data->o->file, set, reset, line, 1);
8f8841e9 1358 ws_check_emit(line + 1, len - 1, data->ws_rule,
1ba111d1 1359 data->o->file, set, reset, ws);
877f23cc 1360 } else if (line[0] == ' ') {
88246898 1361 data->lineno++;
877f23cc 1362 } else if (line[0] == '@') {
88246898
JS
1363 char *plus = strchr(line, '+');
1364 if (plus)
0ef617f4 1365 data->lineno = strtol(plus, NULL, 10) - 1;
88246898
JS
1366 else
1367 die("invalid diff");
1368 }
1369}
1370
0660626c
JH
1371static unsigned char *deflate_it(char *data,
1372 unsigned long size,
1373 unsigned long *result_size)
051308f6 1374{
0660626c
JH
1375 int bound;
1376 unsigned char *deflated;
1377 z_stream stream;
1378
1379 memset(&stream, 0, sizeof(stream));
12f6c308 1380 deflateInit(&stream, zlib_compression_level);
0660626c
JH
1381 bound = deflateBound(&stream, size);
1382 deflated = xmalloc(bound);
1383 stream.next_out = deflated;
1384 stream.avail_out = bound;
1385
1386 stream.next_in = (unsigned char *)data;
1387 stream.avail_in = size;
1388 while (deflate(&stream, Z_FINISH) == Z_OK)
1389 ; /* nothing */
1390 deflateEnd(&stream);
1391 *result_size = stream.total_out;
1392 return deflated;
051308f6
JH
1393}
1394
c0c77734 1395static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two)
051308f6 1396{
0660626c
JH
1397 void *cp;
1398 void *delta;
1399 void *deflated;
1400 void *data;
1401 unsigned long orig_size;
1402 unsigned long delta_size;
1403 unsigned long deflate_size;
1404 unsigned long data_size;
051308f6 1405
0660626c
JH
1406 /* We could do deflated delta, or we could do just deflated two,
1407 * whichever is smaller.
051308f6 1408 */
0660626c
JH
1409 delta = NULL;
1410 deflated = deflate_it(two->ptr, two->size, &deflate_size);
1411 if (one->size && two->size) {
1412 delta = diff_delta(one->ptr, one->size,
1413 two->ptr, two->size,
1414 &delta_size, deflate_size);
1415 if (delta) {
1416 void *to_free = delta;
1417 orig_size = delta_size;
1418 delta = deflate_it(delta, delta_size, &delta_size);
1419 free(to_free);
051308f6
JH
1420 }
1421 }
051308f6 1422
0660626c 1423 if (delta && delta_size < deflate_size) {
c0c77734 1424 fprintf(file, "delta %lu\n", orig_size);
0660626c
JH
1425 free(deflated);
1426 data = delta;
1427 data_size = delta_size;
1428 }
1429 else {
c0c77734 1430 fprintf(file, "literal %lu\n", two->size);
0660626c
JH
1431 free(delta);
1432 data = deflated;
1433 data_size = deflate_size;
1434 }
051308f6 1435
0660626c
JH
1436 /* emit data encoded in base85 */
1437 cp = data;
1438 while (data_size) {
1439 int bytes = (52 < data_size) ? 52 : data_size;
051308f6 1440 char line[70];
0660626c 1441 data_size -= bytes;
051308f6
JH
1442 if (bytes <= 26)
1443 line[0] = bytes + 'A' - 1;
1444 else
1445 line[0] = bytes - 26 + 'a' - 1;
1446 encode_85(line + 1, cp, bytes);
1d7f171c 1447 cp = (char *) cp + bytes;
c0c77734
DB
1448 fputs(line, file);
1449 fputc('\n', file);
051308f6 1450 }
c0c77734 1451 fprintf(file, "\n");
0660626c 1452 free(data);
051308f6
JH
1453}
1454
c0c77734 1455static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two)
d4c452f0 1456{
c0c77734
DB
1457 fprintf(file, "GIT binary patch\n");
1458 emit_binary_diff_body(file, one, two);
1459 emit_binary_diff_body(file, two, one);
d4c452f0
JH
1460}
1461
72cf4841 1462static void diff_filespec_load_driver(struct diff_filespec *one)
6973dcae 1463{
122aa6f9
JK
1464 if (!one->driver)
1465 one->driver = userdiff_find_by_path(one->path);
1466 if (!one->driver)
1467 one->driver = userdiff_find_by_name("default");
29a3eefd
JH
1468}
1469
1470int diff_filespec_is_binary(struct diff_filespec *one)
1471{
122aa6f9
JK
1472 if (one->is_binary == -1) {
1473 diff_filespec_load_driver(one);
1474 if (one->driver->binary != -1)
1475 one->is_binary = one->driver->binary;
1476 else {
1477 if (!one->data && DIFF_FILE_VALID(one))
1478 diff_populate_filespec(one, 0);
1479 if (one->data)
1480 one->is_binary = buffer_is_binary(one->data,
1481 one->size);
1482 if (one->is_binary == -1)
1483 one->is_binary = 0;
1484 }
1485 }
29a3eefd 1486 return one->is_binary;
6973dcae
JH
1487}
1488
be58e70d 1489static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
f258475a 1490{
122aa6f9
JK
1491 diff_filespec_load_driver(one);
1492 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
f258475a
JH
1493}
1494
80c49c3d
TR
1495static const char *userdiff_word_regex(struct diff_filespec *one)
1496{
1497 diff_filespec_load_driver(one);
1498 return one->driver->word_regex;
1499}
1500
a5a818ee
JH
1501void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
1502{
1503 if (!options->a_prefix)
1504 options->a_prefix = a;
1505 if (!options->b_prefix)
1506 options->b_prefix = b;
1507}
1508
04427ac8
JK
1509static const char *get_textconv(struct diff_filespec *one)
1510{
1511 if (!DIFF_FILE_VALID(one))
1512 return NULL;
2675773a
JK
1513 if (!S_ISREG(one->mode))
1514 return NULL;
04427ac8
JK
1515 diff_filespec_load_driver(one);
1516 return one->driver->textconv;
1517}
1518
6973dcae
JH
1519static void builtin_diff(const char *name_a,
1520 const char *name_b,
1521 struct diff_filespec *one,
1522 struct diff_filespec *two,
1523 const char *xfrm_msg,
051308f6 1524 struct diff_options *o,
6973dcae
JH
1525 int complete_rewrite)
1526{
1527 mmfile_t mf1, mf2;
1528 const char *lbl[2];
1529 char *a_one, *b_two;
8f67f8ae
PH
1530 const char *set = diff_get_color_opt(o, DIFF_METAINFO);
1531 const char *reset = diff_get_color_opt(o, DIFF_RESET);
a5a818ee 1532 const char *a_prefix, *b_prefix;
c7534ef4 1533 const char *textconv_one = NULL, *textconv_two = NULL;
a5a818ee 1534
3aa1f7ca
JK
1535 if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
1536 textconv_one = get_textconv(one);
1537 textconv_two = get_textconv(two);
1538 }
1539
a5a818ee
JH
1540 diff_set_mnemonic_prefix(o, "a/", "b/");
1541 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
1542 a_prefix = o->b_prefix;
1543 b_prefix = o->a_prefix;
1544 } else {
1545 a_prefix = o->a_prefix;
1546 b_prefix = o->b_prefix;
1547 }
6973dcae 1548
71b989e7
LT
1549 /* Never use a non-valid filename anywhere if at all possible */
1550 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
1551 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
1552
a5a818ee
JH
1553 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
1554 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
6973dcae
JH
1555 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1556 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
c0c77734 1557 fprintf(o->file, "%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
6973dcae
JH
1558 if (lbl[0][0] == '/') {
1559 /* /dev/null */
c0c77734 1560 fprintf(o->file, "%snew file mode %06o%s\n", set, two->mode, reset);
50f575fc 1561 if (xfrm_msg && xfrm_msg[0])
c0c77734 1562 fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
6973dcae
JH
1563 }
1564 else if (lbl[1][0] == '/') {
c0c77734 1565 fprintf(o->file, "%sdeleted file mode %06o%s\n", set, one->mode, reset);
50f575fc 1566 if (xfrm_msg && xfrm_msg[0])
c0c77734 1567 fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
6973dcae
JH
1568 }
1569 else {
1570 if (one->mode != two->mode) {
c0c77734
DB
1571 fprintf(o->file, "%sold mode %06o%s\n", set, one->mode, reset);
1572 fprintf(o->file, "%snew mode %06o%s\n", set, two->mode, reset);
cd112cef 1573 }
50f575fc 1574 if (xfrm_msg && xfrm_msg[0])
c0c77734 1575 fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
6973dcae
JH
1576 /*
1577 * we do not run diff between different kind
1578 * of objects.
1579 */
1580 if ((one->mode ^ two->mode) & S_IFMT)
1581 goto free_ab_and_return;
0c01857d 1582 if (complete_rewrite &&
3aa1f7ca
JK
1583 (textconv_one || !diff_filespec_is_binary(one)) &&
1584 (textconv_two || !diff_filespec_is_binary(two))) {
1585 emit_rewrite_diff(name_a, name_b, one, two,
1586 textconv_one, textconv_two, o);
34a5e1a2 1587 o->found_changes = 1;
6973dcae
JH
1588 goto free_ab_and_return;
1589 }
1590 }
1591
1592 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1593 die("unable to read files to diff");
1594
8f67f8ae 1595 if (!DIFF_OPT_TST(o, TEXT) &&
04427ac8
JK
1596 ( (diff_filespec_is_binary(one) && !textconv_one) ||
1597 (diff_filespec_is_binary(two) && !textconv_two) )) {
0660626c
JH
1598 /* Quite common confusing case */
1599 if (mf1.size == mf2.size &&
1600 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1601 goto free_ab_and_return;
8f67f8ae 1602 if (DIFF_OPT_TST(o, BINARY))
c0c77734 1603 emit_binary_diff(o->file, &mf1, &mf2);
051308f6 1604 else
c0c77734
DB
1605 fprintf(o->file, "Binary files %s and %s differ\n",
1606 lbl[0], lbl[1]);
34a5e1a2 1607 o->found_changes = 1;
051308f6 1608 }
6973dcae
JH
1609 else {
1610 /* Crazy xdl interfaces.. */
1611 const char *diffopts = getenv("GIT_DIFF_OPTS");
1612 xpparam_t xpp;
1613 xdemitconf_t xecfg;
1614 xdemitcb_t ecb;
1615 struct emit_callback ecbdata;
be58e70d 1616 const struct userdiff_funcname *pe;
f258475a 1617
04427ac8
JK
1618 if (textconv_one) {
1619 size_t size;
1620 mf1.ptr = run_textconv(textconv_one, one, &size);
1621 if (!mf1.ptr)
1622 die("unable to read files to diff");
1623 mf1.size = size;
1624 }
1625 if (textconv_two) {
1626 size_t size;
1627 mf2.ptr = run_textconv(textconv_two, two, &size);
1628 if (!mf2.ptr)
1629 die("unable to read files to diff");
1630 mf2.size = size;
1631 }
1632
45e7ca0f
BC
1633 pe = diff_funcname_pattern(one);
1634 if (!pe)
1635 pe = diff_funcname_pattern(two);
6973dcae 1636
9ccd0a88 1637 memset(&xpp, 0, sizeof(xpp));
30b25010 1638 memset(&xecfg, 0, sizeof(xecfg));
cd112cef 1639 memset(&ecbdata, 0, sizeof(ecbdata));
6973dcae 1640 ecbdata.label_path = lbl;
8f67f8ae 1641 ecbdata.color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
34a5e1a2 1642 ecbdata.found_changesp = &o->found_changes;
cf1b7869 1643 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
690ed843 1644 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
d68fe26f 1645 check_blank_at_eof(&mf1, &mf2, &ecbdata);
c0c77734 1646 ecbdata.file = o->file;
0d21efa5 1647 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
ee1e5412 1648 xecfg.ctxlen = o->context;
6d0e674a 1649 xecfg.interhunkctxlen = o->interhunkcontext;
6973dcae 1650 xecfg.flags = XDL_EMIT_FUNCNAMES;
45e7ca0f 1651 if (pe)
a013585b 1652 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
6973dcae
JH
1653 if (!diffopts)
1654 ;
cc44c765 1655 else if (!prefixcmp(diffopts, "--unified="))
6973dcae 1656 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
cc44c765 1657 else if (!prefixcmp(diffopts, "-u"))
6973dcae 1658 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
c0c77734 1659 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS)) {
f59a59e2
JS
1660 ecbdata.diff_words =
1661 xcalloc(1, sizeof(struct diff_words_data));
c0c77734 1662 ecbdata.diff_words->file = o->file;
80c49c3d
TR
1663 if (!o->word_regex)
1664 o->word_regex = userdiff_word_regex(one);
1665 if (!o->word_regex)
1666 o->word_regex = userdiff_word_regex(two);
98a4d87b
BSSJ
1667 if (!o->word_regex)
1668 o->word_regex = diff_word_regex_cfg;
2b6a5417
JS
1669 if (o->word_regex) {
1670 ecbdata.diff_words->word_regex = (regex_t *)
1671 xmalloc(sizeof(regex_t));
1672 if (regcomp(ecbdata.diff_words->word_regex,
bf82940d
TR
1673 o->word_regex,
1674 REG_EXTENDED | REG_NEWLINE))
2b6a5417
JS
1675 die ("Invalid regular expression: %s",
1676 o->word_regex);
1677 }
c0c77734 1678 }
8a3f524b
JH
1679 xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
1680 &xpp, &xecfg, &ecb);
8f67f8ae 1681 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS))
f59a59e2 1682 free_diff_words_data(&ecbdata);
04427ac8
JK
1683 if (textconv_one)
1684 free(mf1.ptr);
1685 if (textconv_two)
1686 free(mf2.ptr);
8cfe5f1c 1687 xdiff_clear_find_func(&xecfg);
6973dcae
JH
1688 }
1689
1690 free_ab_and_return:
fc3abdf5
JH
1691 diff_free_filespec_data(one);
1692 diff_free_filespec_data(two);
6973dcae
JH
1693 free(a_one);
1694 free(b_two);
1695 return;
1696}
1697
1698static void builtin_diffstat(const char *name_a, const char *name_b,
1699 struct diff_filespec *one,
1700 struct diff_filespec *two,
710158e3 1701 struct diffstat_t *diffstat,
0d21efa5 1702 struct diff_options *o,
710158e3 1703 int complete_rewrite)
6973dcae
JH
1704{
1705 mmfile_t mf1, mf2;
1706 struct diffstat_file *data;
1707
1708 data = diffstat_add(diffstat, name_a, name_b);
1709
1710 if (!one || !two) {
1711 data->is_unmerged = 1;
1712 return;
1713 }
710158e3
JH
1714 if (complete_rewrite) {
1715 diff_populate_filespec(one, 0);
1716 diff_populate_filespec(two, 0);
1717 data->deleted = count_lines(one->data, one->size);
1718 data->added = count_lines(two->data, two->size);
fc3abdf5 1719 goto free_and_return;
710158e3 1720 }
6973dcae
JH
1721 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1722 die("unable to read files to diff");
1723
29a3eefd 1724 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
6973dcae 1725 data->is_binary = 1;
b1882587
AP
1726 data->added = mf2.size;
1727 data->deleted = mf1.size;
1728 } else {
6973dcae
JH
1729 /* Crazy xdl interfaces.. */
1730 xpparam_t xpp;
1731 xdemitconf_t xecfg;
1732 xdemitcb_t ecb;
1733
9ccd0a88 1734 memset(&xpp, 0, sizeof(xpp));
30b25010 1735 memset(&xecfg, 0, sizeof(xecfg));
0d21efa5 1736 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
8a3f524b
JH
1737 xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
1738 &xpp, &xecfg, &ecb);
6973dcae 1739 }
fc3abdf5
JH
1740
1741 free_and_return:
1742 diff_free_filespec_data(one);
1743 diff_free_filespec_data(two);
6973dcae
JH
1744}
1745
88246898 1746static void builtin_checkdiff(const char *name_a, const char *name_b,
cd676a51 1747 const char *attr_path,
5ff10dd6
JH
1748 struct diff_filespec *one,
1749 struct diff_filespec *two,
1750 struct diff_options *o)
88246898
JS
1751{
1752 mmfile_t mf1, mf2;
1753 struct checkdiff_t data;
1754
1755 if (!two)
1756 return;
1757
1758 memset(&data, 0, sizeof(data));
88246898
JS
1759 data.filename = name_b ? name_b : name_a;
1760 data.lineno = 0;
1ba111d1 1761 data.o = o;
cd676a51 1762 data.ws_rule = whitespace_rule(attr_path);
88246898
JS
1763
1764 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1765 die("unable to read files to diff");
1766
5ff10dd6
JH
1767 /*
1768 * All the other codepaths check both sides, but not checking
1769 * the "old" side here is deliberate. We are checking the newly
1770 * introduced changes, and as long as the "new" side is text, we
1771 * can and should check what it introduces.
1772 */
29a3eefd 1773 if (diff_filespec_is_binary(two))
fc3abdf5 1774 goto free_and_return;
88246898
JS
1775 else {
1776 /* Crazy xdl interfaces.. */
1777 xpparam_t xpp;
1778 xdemitconf_t xecfg;
1779 xdemitcb_t ecb;
1780
9ccd0a88 1781 memset(&xpp, 0, sizeof(xpp));
30b25010 1782 memset(&xecfg, 0, sizeof(xecfg));
c35539eb 1783 xecfg.ctxlen = 1; /* at least one context line */
88246898 1784 xpp.flags = XDF_NEED_MINIMAL;
8a3f524b
JH
1785 xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
1786 &xpp, &xecfg, &ecb);
877f23cc 1787
467babf8 1788 if (data.ws_rule & WS_BLANK_AT_EOF) {
d68fe26f
JH
1789 struct emit_callback ecbdata;
1790 int blank_at_eof;
1791
1792 ecbdata.ws_rule = data.ws_rule;
1793 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1794 blank_at_eof = ecbdata.blank_at_eof_in_preimage;
1795
467babf8
JH
1796 if (blank_at_eof) {
1797 static char *err;
1798 if (!err)
1799 err = whitespace_error_string(WS_BLANK_AT_EOF);
1800 fprintf(o->file, "%s:%d: %s.\n",
1801 data.filename, blank_at_eof, err);
1802 data.status = 1; /* report errors */
1803 }
877f23cc 1804 }
88246898 1805 }
fc3abdf5
JH
1806 free_and_return:
1807 diff_free_filespec_data(one);
1808 diff_free_filespec_data(two);
62c64895
WC
1809 if (data.status)
1810 DIFF_OPT_SET(o, CHECK_FAILED);
88246898
JS
1811}
1812
6973dcae
JH
1813struct diff_filespec *alloc_filespec(const char *path)
1814{
1815 int namelen = strlen(path);
1816 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1817
1818 memset(spec, 0, sizeof(*spec));
1819 spec->path = (char *)(spec + 1);
1820 memcpy(spec->path, path, namelen+1);
9fb88419 1821 spec->count = 1;
122aa6f9 1822 spec->is_binary = -1;
6973dcae
JH
1823 return spec;
1824}
1825
9fb88419
LT
1826void free_filespec(struct diff_filespec *spec)
1827{
1828 if (!--spec->count) {
1829 diff_free_filespec_data(spec);
1830 free(spec);
1831 }
1832}
1833
6973dcae
JH
1834void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1835 unsigned short mode)
1836{
1837 if (mode) {
1838 spec->mode = canon_mode(mode);
e702496e 1839 hashcpy(spec->sha1, sha1);
0bef57ee 1840 spec->sha1_valid = !is_null_sha1(sha1);
6973dcae
JH
1841 }
1842}
1843
1844/*
5adf317b 1845 * Given a name and sha1 pair, if the index tells us the file in
6973dcae
JH
1846 * the work tree has that object contents, return true, so that
1847 * prepare_temp_file() does not have to inflate and extract.
1848 */
1510fea7 1849static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
6973dcae
JH
1850{
1851 struct cache_entry *ce;
1852 struct stat st;
1853 int pos, len;
1854
150115ad
JH
1855 /*
1856 * We do not read the cache ourselves here, because the
6973dcae
JH
1857 * benchmark with my previous version that always reads cache
1858 * shows that it makes things worse for diff-tree comparing
1859 * two linux-2.6 kernel trees in an already checked out work
1860 * tree. This is because most diff-tree comparisons deal with
1861 * only a small number of files, while reading the cache is
1862 * expensive for a large project, and its cost outweighs the
1863 * savings we get by not inflating the object to a temporary
1864 * file. Practically, this code only helps when we are used
1865 * by diff-cache --cached, which does read the cache before
1866 * calling us.
1867 */
1868 if (!active_cache)
1869 return 0;
1870
1510fea7
SP
1871 /* We want to avoid the working directory if our caller
1872 * doesn't need the data in a normal file, this system
1873 * is rather slow with its stat/open/mmap/close syscalls,
1874 * and the object is contained in a pack file. The pack
1875 * is probably already open and will be faster to obtain
1876 * the data through than the working directory. Loose
1877 * objects however would tend to be slower as they need
1878 * to be individually opened and inflated.
1879 */
cd673c1f 1880 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1))
1510fea7
SP
1881 return 0;
1882
6973dcae
JH
1883 len = strlen(name);
1884 pos = cache_name_pos(name, len);
1885 if (pos < 0)
1886 return 0;
1887 ce = active_cache[pos];
eadb5831
JH
1888
1889 /*
1890 * This is not the sha1 we are looking for, or
1891 * unreusable because it is not a regular file.
1892 */
1893 if (hashcmp(sha1, ce->sha1) || !S_ISREG(ce->ce_mode))
6973dcae 1894 return 0;
eadb5831 1895
150115ad
JH
1896 /*
1897 * If ce is marked as "assume unchanged", there is no
1898 * guarantee that work tree matches what we are looking for.
1899 */
1900 if (ce->ce_flags & CE_VALID)
1901 return 0;
1902
eadb5831
JH
1903 /*
1904 * If ce matches the file in the work tree, we can reuse it.
6973dcae 1905 */
eadb5831
JH
1906 if (ce_uptodate(ce) ||
1907 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
1908 return 1;
1909
1910 return 0;
6973dcae
JH
1911}
1912
3afaa72d
JH
1913static int populate_from_stdin(struct diff_filespec *s)
1914{
f285a2d7 1915 struct strbuf buf = STRBUF_INIT;
c32f749f 1916 size_t size = 0;
af6eb822 1917
f1696ee3 1918 if (strbuf_read(&buf, 0, 0) < 0)
af6eb822 1919 return error("error while reading from stdin %s",
3afaa72d 1920 strerror(errno));
af6eb822 1921
3afaa72d 1922 s->should_munmap = 0;
c32f749f
RS
1923 s->data = strbuf_detach(&buf, &size);
1924 s->size = size;
3afaa72d
JH
1925 s->should_free = 1;
1926 return 0;
1927}
1928
04786756
LT
1929static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
1930{
1931 int len;
1932 char *data = xmalloc(100);
1933 len = snprintf(data, 100,
1934 "Subproject commit %s\n", sha1_to_hex(s->sha1));
1935 s->data = data;
1936 s->size = len;
1937 s->should_free = 1;
1938 if (size_only) {
1939 s->data = NULL;
1940 free(data);
1941 }
1942 return 0;
1943}
1944
6973dcae
JH
1945/*
1946 * While doing rename detection and pickaxe operation, we may need to
1947 * grab the data for the blob (or file) for our own in-core comparison.
1948 * diff_filespec has data and size fields for this purpose.
1949 */
1950int diff_populate_filespec(struct diff_filespec *s, int size_only)
1951{
1952 int err = 0;
1953 if (!DIFF_FILE_VALID(s))
1954 die("internal error: asking to populate invalid file.");
1955 if (S_ISDIR(s->mode))
1956 return -1;
1957
6973dcae 1958 if (s->data)
fc3abdf5 1959 return 0;
04786756 1960
6e0b8ed6
JH
1961 if (size_only && 0 < s->size)
1962 return 0;
1963
302b9282 1964 if (S_ISGITLINK(s->mode))
04786756
LT
1965 return diff_populate_gitlink(s, size_only);
1966
6973dcae 1967 if (!s->sha1_valid ||
1510fea7 1968 reuse_worktree_file(s->path, s->sha1, 0)) {
f285a2d7 1969 struct strbuf buf = STRBUF_INIT;
6973dcae
JH
1970 struct stat st;
1971 int fd;
6c510bee 1972
3afaa72d
JH
1973 if (!strcmp(s->path, "-"))
1974 return populate_from_stdin(s);
1975
6973dcae
JH
1976 if (lstat(s->path, &st) < 0) {
1977 if (errno == ENOENT) {
1978 err_empty:
1979 err = -1;
1980 empty:
d2543b8e 1981 s->data = (char *)"";
6973dcae
JH
1982 s->size = 0;
1983 return err;
1984 }
1985 }
dc49cd76 1986 s->size = xsize_t(st.st_size);
6973dcae
JH
1987 if (!s->size)
1988 goto empty;
6973dcae 1989 if (S_ISLNK(st.st_mode)) {
cf219d8c
LT
1990 struct strbuf sb = STRBUF_INIT;
1991
1992 if (strbuf_readlink(&sb, s->path, s->size))
6973dcae 1993 goto err_empty;
0956a6db
RS
1994 s->size = sb.len;
1995 s->data = strbuf_detach(&sb, NULL);
cf219d8c 1996 s->should_free = 1;
6973dcae
JH
1997 return 0;
1998 }
cf219d8c
LT
1999 if (size_only)
2000 return 0;
6973dcae
JH
2001 fd = open(s->path, O_RDONLY);
2002 if (fd < 0)
2003 goto err_empty;
c4712e45 2004 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
6973dcae 2005 close(fd);
6973dcae 2006 s->should_munmap = 1;
6c510bee
LT
2007
2008 /*
2009 * Convert from working tree format to canonical git format
2010 */
21e5ad50 2011 if (convert_to_git(s->path, s->data, s->size, &buf, safe_crlf)) {
c32f749f 2012 size_t size = 0;
6c510bee
LT
2013 munmap(s->data, s->size);
2014 s->should_munmap = 0;
c32f749f
RS
2015 s->data = strbuf_detach(&buf, &size);
2016 s->size = size;
6c510bee
LT
2017 s->should_free = 1;
2018 }
6973dcae
JH
2019 }
2020 else {
21666f1a 2021 enum object_type type;
6e0b8ed6 2022 if (size_only)
21666f1a 2023 type = sha1_object_info(s->sha1, &s->size);
6973dcae 2024 else {
21666f1a 2025 s->data = read_sha1_file(s->sha1, &type, &s->size);
6973dcae
JH
2026 s->should_free = 1;
2027 }
2028 }
2029 return 0;
2030}
2031
8ae92e63 2032void diff_free_filespec_blob(struct diff_filespec *s)
6973dcae
JH
2033{
2034 if (s->should_free)
2035 free(s->data);
2036 else if (s->should_munmap)
2037 munmap(s->data, s->size);
fc3abdf5
JH
2038
2039 if (s->should_free || s->should_munmap) {
2040 s->should_free = s->should_munmap = 0;
2041 s->data = NULL;
2042 }
eede7b7d
JK
2043}
2044
2045void diff_free_filespec_data(struct diff_filespec *s)
2046{
8ae92e63 2047 diff_free_filespec_blob(s);
6973dcae
JH
2048 free(s->cnt_data);
2049 s->cnt_data = NULL;
2050}
2051
4e218f54 2052static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
6973dcae
JH
2053 void *blob,
2054 unsigned long size,
2055 const unsigned char *sha1,
2056 int mode)
2057{
2058 int fd;
4e218f54 2059 struct strbuf buf = STRBUF_INIT;
003b33a8
DA
2060 struct strbuf template = STRBUF_INIT;
2061 char *path_dup = xstrdup(path);
2062 const char *base = basename(path_dup);
6973dcae 2063
003b33a8
DA
2064 /* Generate "XXXXXX_basename.ext" */
2065 strbuf_addstr(&template, "XXXXXX_");
2066 strbuf_addstr(&template, base);
2067
2068 fd = git_mkstemps(temp->tmp_path, PATH_MAX, template.buf,
2069 strlen(base) + 1);
6973dcae 2070 if (fd < 0)
d824cbba 2071 die_errno("unable to create temp-file");
4e218f54
JS
2072 if (convert_to_working_tree(path,
2073 (const char *)blob, (size_t)size, &buf)) {
2074 blob = buf.buf;
2075 size = buf.len;
2076 }
93822c22 2077 if (write_in_full(fd, blob, size) != size)
0721c314 2078 die_errno("unable to write temp-file");
6973dcae
JH
2079 close(fd);
2080 temp->name = temp->tmp_path;
2081 strcpy(temp->hex, sha1_to_hex(sha1));
2082 temp->hex[40] = 0;
2083 sprintf(temp->mode, "%06o", mode);
4e218f54 2084 strbuf_release(&buf);
003b33a8
DA
2085 strbuf_release(&template);
2086 free(path_dup);
6973dcae
JH
2087}
2088
479b0ae8
JK
2089static struct diff_tempfile *prepare_temp_file(const char *name,
2090 struct diff_filespec *one)
6973dcae 2091{
479b0ae8
JK
2092 struct diff_tempfile *temp = claim_diff_tempfile();
2093
6973dcae
JH
2094 if (!DIFF_FILE_VALID(one)) {
2095 not_a_valid_file:
2096 /* A '-' entry produces this for file-2, and
2097 * a '+' entry produces this for file-1.
2098 */
2099 temp->name = "/dev/null";
2100 strcpy(temp->hex, ".");
2101 strcpy(temp->mode, ".");
479b0ae8
JK
2102 return temp;
2103 }
2104
2105 if (!remove_tempfile_installed) {
2106 atexit(remove_tempfile);
57b235a4 2107 sigchain_push_common(remove_tempfile_on_signal);
479b0ae8 2108 remove_tempfile_installed = 1;
6973dcae
JH
2109 }
2110
2111 if (!one->sha1_valid ||
1510fea7 2112 reuse_worktree_file(name, one->sha1, 1)) {
6973dcae
JH
2113 struct stat st;
2114 if (lstat(name, &st) < 0) {
2115 if (errno == ENOENT)
2116 goto not_a_valid_file;
d824cbba 2117 die_errno("stat(%s)", name);
6973dcae
JH
2118 }
2119 if (S_ISLNK(st.st_mode)) {
3cd7388d
JK
2120 struct strbuf sb = STRBUF_INIT;
2121 if (strbuf_readlink(&sb, name, st.st_size) < 0)
0721c314 2122 die_errno("readlink(%s)", name);
3cd7388d 2123 prep_temp_blob(name, temp, sb.buf, sb.len,
6973dcae
JH
2124 (one->sha1_valid ?
2125 one->sha1 : null_sha1),
2126 (one->sha1_valid ?
2127 one->mode : S_IFLNK));
3cd7388d 2128 strbuf_release(&sb);
6973dcae
JH
2129 }
2130 else {
2131 /* we can borrow from the file in the work tree */
2132 temp->name = name;
2133 if (!one->sha1_valid)
2134 strcpy(temp->hex, sha1_to_hex(null_sha1));
2135 else
2136 strcpy(temp->hex, sha1_to_hex(one->sha1));
2137 /* Even though we may sometimes borrow the
2138 * contents from the work tree, we always want
2139 * one->mode. mode is trustworthy even when
2140 * !(one->sha1_valid), as long as
2141 * DIFF_FILE_VALID(one).
2142 */
2143 sprintf(temp->mode, "%06o", one->mode);
2144 }
479b0ae8 2145 return temp;
6973dcae
JH
2146 }
2147 else {
2148 if (diff_populate_filespec(one, 0))
2149 die("cannot read data blob for %s", one->path);
4e218f54 2150 prep_temp_blob(name, temp, one->data, one->size,
6973dcae
JH
2151 one->sha1, one->mode);
2152 }
479b0ae8 2153 return temp;
6973dcae
JH
2154}
2155
6973dcae
JH
2156/* An external diff command takes:
2157 *
2158 * diff-cmd name infile1 infile1-sha1 infile1-mode \
2159 * infile2 infile2-sha1 infile2-mode [ rename-to ]
2160 *
2161 */
2162static void run_external_diff(const char *pgm,
2163 const char *name,
2164 const char *other,
2165 struct diff_filespec *one,
2166 struct diff_filespec *two,
2167 const char *xfrm_msg,
2168 int complete_rewrite)
2169{
2170 const char *spawn_arg[10];
6973dcae 2171 int retval;
6973dcae
JH
2172 const char **arg = &spawn_arg[0];
2173
6973dcae 2174 if (one && two) {
479b0ae8
JK
2175 struct diff_tempfile *temp_one, *temp_two;
2176 const char *othername = (other ? other : name);
2177 temp_one = prepare_temp_file(name, one);
2178 temp_two = prepare_temp_file(othername, two);
6973dcae
JH
2179 *arg++ = pgm;
2180 *arg++ = name;
479b0ae8
JK
2181 *arg++ = temp_one->name;
2182 *arg++ = temp_one->hex;
2183 *arg++ = temp_one->mode;
2184 *arg++ = temp_two->name;
2185 *arg++ = temp_two->hex;
2186 *arg++ = temp_two->mode;
6973dcae
JH
2187 if (other) {
2188 *arg++ = other;
2189 *arg++ = xfrm_msg;
2190 }
2191 } else {
2192 *arg++ = pgm;
2193 *arg++ = name;
2194 }
2195 *arg = NULL;
d5535ec7
JS
2196 fflush(NULL);
2197 retval = run_command_v_opt(spawn_arg, 0);
6973dcae
JH
2198 remove_tempfile();
2199 if (retval) {
2200 fprintf(stderr, "external diff died, stopping at %s.\n", name);
2201 exit(1);
2202 }
2203}
2204
b67b9612
JH
2205static int similarity_index(struct diff_filepair *p)
2206{
2207 return p->score * 100 / MAX_SCORE;
2208}
2209
2210static void fill_metainfo(struct strbuf *msg,
2211 const char *name,
2212 const char *other,
2213 struct diff_filespec *one,
2214 struct diff_filespec *two,
2215 struct diff_options *o,
2216 struct diff_filepair *p)
2217{
2218 strbuf_init(msg, PATH_MAX * 2 + 300);
2219 switch (p->status) {
2220 case DIFF_STATUS_COPIED:
2221 strbuf_addf(msg, "similarity index %d%%", similarity_index(p));
2222 strbuf_addstr(msg, "\ncopy from ");
2223 quote_c_style(name, msg, NULL, 0);
2224 strbuf_addstr(msg, "\ncopy to ");
2225 quote_c_style(other, msg, NULL, 0);
2226 strbuf_addch(msg, '\n');
2227 break;
2228 case DIFF_STATUS_RENAMED:
2229 strbuf_addf(msg, "similarity index %d%%", similarity_index(p));
2230 strbuf_addstr(msg, "\nrename from ");
2231 quote_c_style(name, msg, NULL, 0);
2232 strbuf_addstr(msg, "\nrename to ");
2233 quote_c_style(other, msg, NULL, 0);
2234 strbuf_addch(msg, '\n');
2235 break;
2236 case DIFF_STATUS_MODIFIED:
2237 if (p->score) {
2238 strbuf_addf(msg, "dissimilarity index %d%%\n",
2239 similarity_index(p));
2240 break;
2241 }
2242 /* fallthru */
2243 default:
2244 /* nothing */
2245 ;
2246 }
2247 if (one && two && hashcmp(one->sha1, two->sha1)) {
2248 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
2249
2250 if (DIFF_OPT_TST(o, BINARY)) {
2251 mmfile_t mf;
2252 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
2253 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
2254 abbrev = 40;
2255 }
2256 strbuf_addf(msg, "index %.*s..%.*s",
2257 abbrev, sha1_to_hex(one->sha1),
2258 abbrev, sha1_to_hex(two->sha1));
2259 if (one->mode == two->mode)
2260 strbuf_addf(msg, " %06o", one->mode);
2261 strbuf_addch(msg, '\n');
2262 }
2263 if (msg->len)
2264 strbuf_setlen(msg, msg->len - 1);
2265}
2266
6973dcae
JH
2267static void run_diff_cmd(const char *pgm,
2268 const char *name,
2269 const char *other,
cd676a51 2270 const char *attr_path,
6973dcae
JH
2271 struct diff_filespec *one,
2272 struct diff_filespec *two,
b67b9612 2273 struct strbuf *msg,
051308f6 2274 struct diff_options *o,
b67b9612 2275 struct diff_filepair *p)
6973dcae 2276{
b67b9612
JH
2277 const char *xfrm_msg = NULL;
2278 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
2279
2280 if (msg) {
2281 fill_metainfo(msg, name, other, one, two, o, p);
2282 xfrm_msg = msg->len ? msg->buf : NULL;
2283 }
2284
8f67f8ae 2285 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
f1af60bd
JH
2286 pgm = NULL;
2287 else {
be58e70d
JK
2288 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
2289 if (drv && drv->external)
2290 pgm = drv->external;
f1af60bd
JH
2291 }
2292
6973dcae
JH
2293 if (pgm) {
2294 run_external_diff(pgm, name, other, one, two, xfrm_msg,
2295 complete_rewrite);
2296 return;
2297 }
2298 if (one && two)
2299 builtin_diff(name, other ? other : name,
051308f6 2300 one, two, xfrm_msg, o, complete_rewrite);
6973dcae 2301 else
c0c77734 2302 fprintf(o->file, "* Unmerged path %s\n", name);
6973dcae
JH
2303}
2304
2305static void diff_fill_sha1_info(struct diff_filespec *one)
2306{
2307 if (DIFF_FILE_VALID(one)) {
2308 if (!one->sha1_valid) {
2309 struct stat st;
5332b2af
JS
2310 if (!strcmp(one->path, "-")) {
2311 hashcpy(one->sha1, null_sha1);
2312 return;
2313 }
6973dcae 2314 if (lstat(one->path, &st) < 0)
0721c314 2315 die_errno("stat '%s'", one->path);
6973dcae 2316 if (index_path(one->sha1, one->path, &st, 0))
d7530708 2317 die("cannot hash %s", one->path);
6973dcae
JH
2318 }
2319 }
2320 else
e702496e 2321 hashclr(one->sha1);
6973dcae
JH
2322}
2323
cd676a51
JH
2324static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
2325{
2326 /* Strip the prefix but do not molest /dev/null and absolute paths */
2327 if (*namep && **namep != '/')
2328 *namep += prefix_length;
2329 if (*otherp && **otherp != '/')
2330 *otherp += prefix_length;
2331}
2332
6973dcae
JH
2333static void run_diff(struct diff_filepair *p, struct diff_options *o)
2334{
2335 const char *pgm = external_diff();
663af342 2336 struct strbuf msg;
663af342
PH
2337 struct diff_filespec *one = p->one;
2338 struct diff_filespec *two = p->two;
6973dcae
JH
2339 const char *name;
2340 const char *other;
cd676a51 2341 const char *attr_path;
663af342 2342
cd676a51
JH
2343 name = p->one->path;
2344 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2345 attr_path = name;
2346 if (o->prefix_length)
2347 strip_prefix(o->prefix_length, &name, &other);
6973dcae
JH
2348
2349 if (DIFF_PAIR_UNMERGED(p)) {
cd676a51 2350 run_diff_cmd(pgm, name, NULL, attr_path,
b67b9612 2351 NULL, NULL, NULL, o, p);
6973dcae
JH
2352 return;
2353 }
2354
6973dcae
JH
2355 diff_fill_sha1_info(one);
2356 diff_fill_sha1_info(two);
2357
6973dcae
JH
2358 if (!pgm &&
2359 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
2360 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
b67b9612
JH
2361 /*
2362 * a filepair that changes between file and symlink
6973dcae
JH
2363 * needs to be split into deletion and creation.
2364 */
2365 struct diff_filespec *null = alloc_filespec(two->path);
cd676a51 2366 run_diff_cmd(NULL, name, other, attr_path,
b67b9612 2367 one, null, &msg, o, p);
6973dcae 2368 free(null);
b67b9612
JH
2369 strbuf_release(&msg);
2370
6973dcae 2371 null = alloc_filespec(one->path);
cd676a51 2372 run_diff_cmd(NULL, name, other, attr_path,
b67b9612 2373 null, two, &msg, o, p);
6973dcae
JH
2374 free(null);
2375 }
2376 else
cd676a51 2377 run_diff_cmd(pgm, name, other, attr_path,
b67b9612 2378 one, two, &msg, o, p);
6973dcae 2379
663af342 2380 strbuf_release(&msg);
6973dcae
JH
2381}
2382
2383static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
2384 struct diffstat_t *diffstat)
2385{
2386 const char *name;
2387 const char *other;
710158e3 2388 int complete_rewrite = 0;
6973dcae
JH
2389
2390 if (DIFF_PAIR_UNMERGED(p)) {
2391 /* unmerged */
0d21efa5 2392 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
6973dcae
JH
2393 return;
2394 }
2395
2396 name = p->one->path;
2397 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2398
cd676a51
JH
2399 if (o->prefix_length)
2400 strip_prefix(o->prefix_length, &name, &other);
2401
6973dcae
JH
2402 diff_fill_sha1_info(p->one);
2403 diff_fill_sha1_info(p->two);
2404
710158e3
JH
2405 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2406 complete_rewrite = 1;
0d21efa5 2407 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
6973dcae
JH
2408}
2409
88246898
JS
2410static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
2411{
2412 const char *name;
2413 const char *other;
cd676a51 2414 const char *attr_path;
88246898
JS
2415
2416 if (DIFF_PAIR_UNMERGED(p)) {
2417 /* unmerged */
2418 return;
2419 }
2420
2421 name = p->one->path;
2422 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
cd676a51
JH
2423 attr_path = other ? other : name;
2424
2425 if (o->prefix_length)
2426 strip_prefix(o->prefix_length, &name, &other);
88246898
JS
2427
2428 diff_fill_sha1_info(p->one);
2429 diff_fill_sha1_info(p->two);
2430
cd676a51 2431 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
88246898
JS
2432}
2433
6973dcae
JH
2434void diff_setup(struct diff_options *options)
2435{
2436 memset(options, 0, sizeof(*options));
c0c77734
DB
2437
2438 options->file = stdout;
2439
6973dcae
JH
2440 options->line_termination = '\n';
2441 options->break_opt = -1;
2442 options->rename_limit = -1;
7df7c019 2443 options->dirstat_percent = 3;
ee1e5412 2444 options->context = 3;
6973dcae
JH
2445
2446 options->change = diff_change;
2447 options->add_remove = diff_addremove;
6b2f2d98 2448 if (diff_use_color_default > 0)
8f67f8ae 2449 DIFF_OPT_SET(options, COLOR_DIFF);
b68ea12e 2450 options->detect_rename = diff_detect_rename_default;
eab9a40b 2451
a5a818ee
JH
2452 if (!diff_mnemonic_prefix) {
2453 options->a_prefix = "a/";
2454 options->b_prefix = "b/";
2455 }
6973dcae
JH
2456}
2457
2458int diff_setup_done(struct diff_options *options)
2459{
d7de00f7
TH
2460 int count = 0;
2461
2462 if (options->output_format & DIFF_FORMAT_NAME)
2463 count++;
2464 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
2465 count++;
2466 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
2467 count++;
2468 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
2469 count++;
2470 if (count > 1)
2471 die("--name-only, --name-status, --check and -s are mutually exclusive");
2472
8f67f8ae 2473 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
03b9d560
JH
2474 options->detect_rename = DIFF_DETECT_COPY;
2475
cd676a51
JH
2476 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
2477 options->prefix = NULL;
2478 if (options->prefix)
2479 options->prefix_length = strlen(options->prefix);
2480 else
2481 options->prefix_length = 0;
2482
c6744349
TH
2483 if (options->output_format & (DIFF_FORMAT_NAME |
2484 DIFF_FORMAT_NAME_STATUS |
2485 DIFF_FORMAT_CHECKDIFF |
2486 DIFF_FORMAT_NO_OUTPUT))
2487 options->output_format &= ~(DIFF_FORMAT_RAW |
74e2abe5 2488 DIFF_FORMAT_NUMSTAT |
c6744349 2489 DIFF_FORMAT_DIFFSTAT |
ebd124c6 2490 DIFF_FORMAT_SHORTSTAT |
7df7c019 2491 DIFF_FORMAT_DIRSTAT |
c6744349
TH
2492 DIFF_FORMAT_SUMMARY |
2493 DIFF_FORMAT_PATCH);
2494
6973dcae
JH
2495 /*
2496 * These cases always need recursive; we do not drop caller-supplied
2497 * recursive bits for other formats here.
2498 */
c6744349 2499 if (options->output_format & (DIFF_FORMAT_PATCH |
74e2abe5 2500 DIFF_FORMAT_NUMSTAT |
c6744349 2501 DIFF_FORMAT_DIFFSTAT |
ebd124c6 2502 DIFF_FORMAT_SHORTSTAT |
7df7c019 2503 DIFF_FORMAT_DIRSTAT |
d7014dc0 2504 DIFF_FORMAT_SUMMARY |
c6744349 2505 DIFF_FORMAT_CHECKDIFF))
8f67f8ae 2506 DIFF_OPT_SET(options, RECURSIVE);
5e363541 2507 /*
3969cf7d 2508 * Also pickaxe would not work very well if you do not say recursive
5e363541 2509 */
3969cf7d 2510 if (options->pickaxe)
8f67f8ae 2511 DIFF_OPT_SET(options, RECURSIVE);
5e363541 2512
6973dcae
JH
2513 if (options->detect_rename && options->rename_limit < 0)
2514 options->rename_limit = diff_rename_limit_default;
2515 if (options->setup & DIFF_SETUP_USE_CACHE) {
2516 if (!active_cache)
2517 /* read-cache does not die even when it fails
2518 * so it is safe for us to do this here. Also
2519 * it does not smudge active_cache or active_nr
2520 * when it fails, so we do not have to worry about
2521 * cleaning it up ourselves either.
2522 */
2523 read_cache();
2524 }
6973dcae
JH
2525 if (options->abbrev <= 0 || 40 < options->abbrev)
2526 options->abbrev = 40; /* full */
2527
68aacb2f
JH
2528 /*
2529 * It does not make sense to show the first hit we happened
2530 * to have found. It does not make sense not to return with
2531 * exit code in such a case either.
2532 */
8f67f8ae 2533 if (DIFF_OPT_TST(options, QUIET)) {
68aacb2f 2534 options->output_format = DIFF_FORMAT_NO_OUTPUT;
8f67f8ae 2535 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
68aacb2f
JH
2536 }
2537
6973dcae
JH
2538 return 0;
2539}
2540
d2543b8e 2541static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
ee1e5412
LT
2542{
2543 char c, *eq;
2544 int len;
2545
2546 if (*arg != '-')
2547 return 0;
2548 c = *++arg;
2549 if (!c)
2550 return 0;
2551 if (c == arg_short) {
2552 c = *++arg;
2553 if (!c)
2554 return 1;
2555 if (val && isdigit(c)) {
2556 char *end;
2557 int n = strtoul(arg, &end, 10);
2558 if (*end)
2559 return 0;
2560 *val = n;
2561 return 1;
2562 }
2563 return 0;
2564 }
2565 if (c != '-')
2566 return 0;
2567 arg++;
2568 eq = strchr(arg, '=');
2569 if (eq)
2570 len = eq - arg;
2571 else
2572 len = strlen(arg);
2573 if (!len || strncmp(arg, arg_long, len))
2574 return 0;
2575 if (eq) {
2576 int n;
2577 char *end;
2578 if (!isdigit(*++eq))
2579 return 0;
2580 n = strtoul(eq, &end, 10);
2581 if (*end)
2582 return 0;
2583 *val = n;
2584 }
2585 return 1;
2586}
2587
16befb8b
JH
2588static int diff_scoreopt_parse(const char *opt);
2589
6973dcae
JH
2590int diff_opt_parse(struct diff_options *options, const char **av, int ac)
2591{
2592 const char *arg = av[0];
d054680c
PH
2593
2594 /* Output format options */
6973dcae 2595 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
c6744349 2596 options->output_format |= DIFF_FORMAT_PATCH;
ee1e5412 2597 else if (opt_arg(arg, 'U', "unified", &options->context))
c6744349 2598 options->output_format |= DIFF_FORMAT_PATCH;
a610786f
TH
2599 else if (!strcmp(arg, "--raw"))
2600 options->output_format |= DIFF_FORMAT_RAW;
8f67f8ae 2601 else if (!strcmp(arg, "--patch-with-raw"))
c6744349 2602 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
8f67f8ae 2603 else if (!strcmp(arg, "--numstat"))
74e2abe5 2604 options->output_format |= DIFF_FORMAT_NUMSTAT;
8f67f8ae 2605 else if (!strcmp(arg, "--shortstat"))
ebd124c6 2606 options->output_format |= DIFF_FORMAT_SHORTSTAT;
7df7c019
LT
2607 else if (opt_arg(arg, 'X', "dirstat", &options->dirstat_percent))
2608 options->output_format |= DIFF_FORMAT_DIRSTAT;
f88d225f
JH
2609 else if (!strcmp(arg, "--cumulative")) {
2610 options->output_format |= DIFF_FORMAT_DIRSTAT;
2611 DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
fd33777b
HO
2612 } else if (opt_arg(arg, 0, "dirstat-by-file",
2613 &options->dirstat_percent)) {
2614 options->output_format |= DIFF_FORMAT_DIRSTAT;
2615 DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
f88d225f 2616 }
d054680c
PH
2617 else if (!strcmp(arg, "--check"))
2618 options->output_format |= DIFF_FORMAT_CHECKDIFF;
2619 else if (!strcmp(arg, "--summary"))
2620 options->output_format |= DIFF_FORMAT_SUMMARY;
2621 else if (!strcmp(arg, "--patch-with-stat"))
2622 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2623 else if (!strcmp(arg, "--name-only"))
2624 options->output_format |= DIFF_FORMAT_NAME;
2625 else if (!strcmp(arg, "--name-status"))
2626 options->output_format |= DIFF_FORMAT_NAME_STATUS;
2627 else if (!strcmp(arg, "-s"))
2628 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
cc44c765 2629 else if (!prefixcmp(arg, "--stat")) {
5c5b2ea9
LT
2630 char *end;
2631 int width = options->stat_width;
2632 int name_width = options->stat_name_width;
2633 arg += 6;
2634 end = (char *)arg;
2635
2636 switch (*arg) {
2637 case '-':
cc44c765 2638 if (!prefixcmp(arg, "-width="))
5c5b2ea9 2639 width = strtoul(arg + 7, &end, 10);
cc44c765 2640 else if (!prefixcmp(arg, "-name-width="))
5c5b2ea9
LT
2641 name_width = strtoul(arg + 12, &end, 10);
2642 break;
2643 case '=':
2644 width = strtoul(arg+1, &end, 10);
2645 if (*end == ',')
2646 name_width = strtoul(end+1, &end, 10);
2647 }
2648
2649 /* Important! This checks all the error cases! */
2650 if (*end)
2651 return 0;
c6744349 2652 options->output_format |= DIFF_FORMAT_DIFFSTAT;
5c5b2ea9
LT
2653 options->stat_name_width = name_width;
2654 options->stat_width = width;
a2540023 2655 }
d054680c
PH
2656
2657 /* renames options */
cc44c765 2658 else if (!prefixcmp(arg, "-B")) {
8f67f8ae 2659 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
6973dcae
JH
2660 return -1;
2661 }
cc44c765 2662 else if (!prefixcmp(arg, "-M")) {
8f67f8ae 2663 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
6973dcae
JH
2664 return -1;
2665 options->detect_rename = DIFF_DETECT_RENAME;
2666 }
cc44c765 2667 else if (!prefixcmp(arg, "-C")) {
ca6c0970 2668 if (options->detect_rename == DIFF_DETECT_COPY)
8f67f8ae
PH
2669 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2670 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
6973dcae
JH
2671 return -1;
2672 options->detect_rename = DIFF_DETECT_COPY;
2673 }
d054680c
PH
2674 else if (!strcmp(arg, "--no-renames"))
2675 options->detect_rename = 0;
cd676a51
JH
2676 else if (!strcmp(arg, "--relative"))
2677 DIFF_OPT_SET(options, RELATIVE_NAME);
c0cb4a06
JH
2678 else if (!prefixcmp(arg, "--relative=")) {
2679 DIFF_OPT_SET(options, RELATIVE_NAME);
2680 options->prefix = arg + 11;
2681 }
d054680c
PH
2682
2683 /* xdiff options */
2684 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
628d5c2b 2685 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
d054680c 2686 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
628d5c2b 2687 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
d054680c 2688 else if (!strcmp(arg, "--ignore-space-at-eol"))
628d5c2b 2689 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
34292bdd 2690 else if (!strcmp(arg, "--patience"))
628d5c2b 2691 DIFF_XDL_SET(options, PATIENCE_DIFF);
d054680c
PH
2692
2693 /* flags options */
2694 else if (!strcmp(arg, "--binary")) {
2695 options->output_format |= DIFF_FORMAT_PATCH;
2696 DIFF_OPT_SET(options, BINARY);
2697 }
2698 else if (!strcmp(arg, "--full-index"))
2699 DIFF_OPT_SET(options, FULL_INDEX);
2700 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
2701 DIFF_OPT_SET(options, TEXT);
2702 else if (!strcmp(arg, "-R"))
2703 DIFF_OPT_SET(options, REVERSE_DIFF);
6973dcae 2704 else if (!strcmp(arg, "--find-copies-harder"))
8f67f8ae 2705 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
750f7b66 2706 else if (!strcmp(arg, "--follow"))
8f67f8ae 2707 DIFF_OPT_SET(options, FOLLOW_RENAMES);
cd112cef 2708 else if (!strcmp(arg, "--color"))
8f67f8ae 2709 DIFF_OPT_SET(options, COLOR_DIFF);
fef88bb0 2710 else if (!strcmp(arg, "--no-color"))
8f67f8ae 2711 DIFF_OPT_CLR(options, COLOR_DIFF);
628d5c2b
KC
2712 else if (!strcmp(arg, "--color-words")) {
2713 DIFF_OPT_SET(options, COLOR_DIFF);
2714 DIFF_OPT_SET(options, COLOR_DIFF_WORDS);
2715 }
2b6a5417 2716 else if (!prefixcmp(arg, "--color-words=")) {
628d5c2b
KC
2717 DIFF_OPT_SET(options, COLOR_DIFF);
2718 DIFF_OPT_SET(options, COLOR_DIFF_WORDS);
2b6a5417
JS
2719 options->word_regex = arg + 14;
2720 }
41bbf9d5 2721 else if (!strcmp(arg, "--exit-code"))
8f67f8ae 2722 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
68aacb2f 2723 else if (!strcmp(arg, "--quiet"))
8f67f8ae 2724 DIFF_OPT_SET(options, QUIET);
72909bef 2725 else if (!strcmp(arg, "--ext-diff"))
8f67f8ae 2726 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
72909bef 2727 else if (!strcmp(arg, "--no-ext-diff"))
8f67f8ae 2728 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
e10ea812
JK
2729 else if (!strcmp(arg, "--textconv"))
2730 DIFF_OPT_SET(options, ALLOW_TEXTCONV);
2731 else if (!strcmp(arg, "--no-textconv"))
2732 DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
50fd9bd8
JS
2733 else if (!strcmp(arg, "--ignore-submodules"))
2734 DIFF_OPT_SET(options, IGNORE_SUBMODULES);
d054680c
PH
2735
2736 /* misc options */
2737 else if (!strcmp(arg, "-z"))
2738 options->line_termination = 0;
2739 else if (!prefixcmp(arg, "-l"))
2740 options->rename_limit = strtoul(arg+2, NULL, 10);
2741 else if (!prefixcmp(arg, "-S"))
2742 options->pickaxe = arg + 2;
2743 else if (!strcmp(arg, "--pickaxe-all"))
2744 options->pickaxe_opts = DIFF_PICKAXE_ALL;
2745 else if (!strcmp(arg, "--pickaxe-regex"))
2746 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2747 else if (!prefixcmp(arg, "-O"))
2748 options->orderfile = arg + 2;
2749 else if (!prefixcmp(arg, "--diff-filter="))
2750 options->filter = arg + 14;
2751 else if (!strcmp(arg, "--abbrev"))
2752 options->abbrev = DEFAULT_ABBREV;
2753 else if (!prefixcmp(arg, "--abbrev=")) {
2754 options->abbrev = strtoul(arg + 9, NULL, 10);
2755 if (options->abbrev < MINIMUM_ABBREV)
2756 options->abbrev = MINIMUM_ABBREV;
2757 else if (40 < options->abbrev)
2758 options->abbrev = 40;
2759 }
eab9a40b
JS
2760 else if (!prefixcmp(arg, "--src-prefix="))
2761 options->a_prefix = arg + 13;
2762 else if (!prefixcmp(arg, "--dst-prefix="))
2763 options->b_prefix = arg + 13;
2764 else if (!strcmp(arg, "--no-prefix"))
2765 options->a_prefix = options->b_prefix = "";
6d0e674a
RS
2766 else if (opt_arg(arg, '\0', "inter-hunk-context",
2767 &options->interhunkcontext))
2768 ;
c0c77734
DB
2769 else if (!prefixcmp(arg, "--output=")) {
2770 options->file = fopen(arg + strlen("--output="), "w");
2771 options->close_file = 1;
2772 } else
6973dcae
JH
2773 return 0;
2774 return 1;
2775}
2776
2777static int parse_num(const char **cp_p)
2778{
2779 unsigned long num, scale;
2780 int ch, dot;
2781 const char *cp = *cp_p;
2782
2783 num = 0;
2784 scale = 1;
2785 dot = 0;
2786 for(;;) {
2787 ch = *cp;
2788 if ( !dot && ch == '.' ) {
2789 scale = 1;
2790 dot = 1;
2791 } else if ( ch == '%' ) {
2792 scale = dot ? scale*100 : 100;
2793 cp++; /* % is always at the end */
2794 break;
2795 } else if ( ch >= '0' && ch <= '9' ) {
2796 if ( scale < 100000 ) {
2797 scale *= 10;
2798 num = (num*10) + (ch-'0');
2799 }
2800 } else {
2801 break;
2802 }
2803 cp++;
2804 }
2805 *cp_p = cp;
2806
2807 /* user says num divided by scale and we say internally that
2808 * is MAX_SCORE * num / scale.
2809 */
dc49cd76 2810 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
6973dcae
JH
2811}
2812
16befb8b 2813static int diff_scoreopt_parse(const char *opt)
6973dcae
JH
2814{
2815 int opt1, opt2, cmd;
2816
2817 if (*opt++ != '-')
2818 return -1;
2819 cmd = *opt++;
2820 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2821 return -1; /* that is not a -M, -C nor -B option */
2822
2823 opt1 = parse_num(&opt);
2824 if (cmd != 'B')
2825 opt2 = 0;
2826 else {
2827 if (*opt == 0)
2828 opt2 = 0;
2829 else if (*opt != '/')
2830 return -1; /* we expect -B80/99 or -B80 */
2831 else {
2832 opt++;
2833 opt2 = parse_num(&opt);
2834 }
2835 }
2836 if (*opt != 0)
2837 return -1;
2838 return opt1 | (opt2 << 16);
2839}
2840
2841struct diff_queue_struct diff_queued_diff;
2842
2843void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2844{
2845 if (queue->alloc <= queue->nr) {
2846 queue->alloc = alloc_nr(queue->alloc);
2847 queue->queue = xrealloc(queue->queue,
2848 sizeof(dp) * queue->alloc);
2849 }
2850 queue->queue[queue->nr++] = dp;
2851}
2852
2853struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2854 struct diff_filespec *one,
2855 struct diff_filespec *two)
2856{
ef677686 2857 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
6973dcae
JH
2858 dp->one = one;
2859 dp->two = two;
6973dcae
JH
2860 if (queue)
2861 diff_q(queue, dp);
2862 return dp;
2863}
2864
2865void diff_free_filepair(struct diff_filepair *p)
2866{
9fb88419
LT
2867 free_filespec(p->one);
2868 free_filespec(p->two);
6973dcae
JH
2869 free(p);
2870}
2871
2872/* This is different from find_unique_abbrev() in that
2873 * it stuffs the result with dots for alignment.
2874 */
2875const char *diff_unique_abbrev(const unsigned char *sha1, int len)
2876{
2877 int abblen;
2878 const char *abbrev;
2879 if (len == 40)
2880 return sha1_to_hex(sha1);
2881
2882 abbrev = find_unique_abbrev(sha1, len);
6973dcae
JH
2883 abblen = strlen(abbrev);
2884 if (abblen < 37) {
2885 static char hex[41];
2886 if (len < abblen && abblen <= len + 2)
2887 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
2888 else
2889 sprintf(hex, "%s...", abbrev);
2890 return hex;
2891 }
2892 return sha1_to_hex(sha1);
2893}
2894
663af342 2895static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
6973dcae 2896{
663af342
PH
2897 int line_termination = opt->line_termination;
2898 int inter_name_termination = line_termination ? '\t' : '\0';
6973dcae 2899
663af342 2900 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
c0c77734
DB
2901 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
2902 diff_unique_abbrev(p->one->sha1, opt->abbrev));
2903 fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
6973dcae 2904 }
663af342 2905 if (p->score) {
c0c77734
DB
2906 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
2907 inter_name_termination);
663af342 2908 } else {
c0c77734 2909 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
6973dcae 2910 }
6973dcae 2911
cd676a51
JH
2912 if (p->status == DIFF_STATUS_COPIED ||
2913 p->status == DIFF_STATUS_RENAMED) {
2914 const char *name_a, *name_b;
2915 name_a = p->one->path;
2916 name_b = p->two->path;
2917 strip_prefix(opt->prefix_length, &name_a, &name_b);
c0c77734
DB
2918 write_name_quoted(name_a, opt->file, inter_name_termination);
2919 write_name_quoted(name_b, opt->file, line_termination);
663af342 2920 } else {
cd676a51
JH
2921 const char *name_a, *name_b;
2922 name_a = p->one->mode ? p->one->path : p->two->path;
2923 name_b = NULL;
2924 strip_prefix(opt->prefix_length, &name_a, &name_b);
c0c77734 2925 write_name_quoted(name_a, opt->file, line_termination);
663af342 2926 }
6973dcae
JH
2927}
2928
2929int diff_unmodified_pair(struct diff_filepair *p)
2930{
2931 /* This function is written stricter than necessary to support
2932 * the currently implemented transformers, but the idea is to
2933 * let transformers to produce diff_filepairs any way they want,
2934 * and filter and clean them up here before producing the output.
2935 */
663af342 2936 struct diff_filespec *one = p->one, *two = p->two;
6973dcae
JH
2937
2938 if (DIFF_PAIR_UNMERGED(p))
2939 return 0; /* unmerged is interesting */
2940
6973dcae
JH
2941 /* deletion, addition, mode or type change
2942 * and rename are all interesting.
2943 */
2944 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
2945 DIFF_PAIR_MODE_CHANGED(p) ||
2946 strcmp(one->path, two->path))
2947 return 0;
2948
2949 /* both are valid and point at the same path. that is, we are
2950 * dealing with a change.
2951 */
2952 if (one->sha1_valid && two->sha1_valid &&
a89fccd2 2953 !hashcmp(one->sha1, two->sha1))
6973dcae
JH
2954 return 1; /* no change */
2955 if (!one->sha1_valid && !two->sha1_valid)
2956 return 1; /* both look at the same file on the filesystem. */
2957 return 0;
2958}
2959
2960static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
2961{
2962 if (diff_unmodified_pair(p))
2963 return;
2964
2965 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2966 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2967 return; /* no tree diffs in patch format */
2968
2969 run_diff(p, o);
2970}
2971
2972static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
2973 struct diffstat_t *diffstat)
2974{
2975 if (diff_unmodified_pair(p))
2976 return;
2977
2978 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2979 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2980 return; /* no tree diffs in patch format */
2981
2982 run_diffstat(p, o, diffstat);
2983}
2984
88246898
JS
2985static void diff_flush_checkdiff(struct diff_filepair *p,
2986 struct diff_options *o)
2987{
2988 if (diff_unmodified_pair(p))
2989 return;
2990
2991 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2992 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2993 return; /* no tree diffs in patch format */
2994
2995 run_checkdiff(p, o);
2996}
2997
6973dcae
JH
2998int diff_queue_is_empty(void)
2999{
3000 struct diff_queue_struct *q = &diff_queued_diff;
3001 int i;
3002 for (i = 0; i < q->nr; i++)
3003 if (!diff_unmodified_pair(q->queue[i]))
3004 return 0;
3005 return 1;
3006}
3007
3008#if DIFF_DEBUG
3009void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
3010{
3011 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
3012 x, one ? one : "",
3013 s->path,
3014 DIFF_FILE_VALID(s) ? "valid" : "invalid",
3015 s->mode,
3016 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
3017 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
3018 x, one ? one : "",
3019 s->size, s->xfrm_flags);
3020}
3021
3022void diff_debug_filepair(const struct diff_filepair *p, int i)
3023{
3024 diff_debug_filespec(p->one, i, "one");
3025 diff_debug_filespec(p->two, i, "two");
64479711 3026 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
6973dcae 3027 p->score, p->status ? p->status : '?',
64479711 3028 p->one->rename_used, p->broken_pair);
6973dcae
JH
3029}
3030
3031void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
3032{
3033 int i;
3034 if (msg)
3035 fprintf(stderr, "%s\n", msg);
3036 fprintf(stderr, "q->nr = %d\n", q->nr);
3037 for (i = 0; i < q->nr; i++) {
3038 struct diff_filepair *p = q->queue[i];
3039 diff_debug_filepair(p, i);
3040 }
3041}
3042#endif
3043
3044static void diff_resolve_rename_copy(void)
3045{
64479711
LT
3046 int i;
3047 struct diff_filepair *p;
6973dcae
JH
3048 struct diff_queue_struct *q = &diff_queued_diff;
3049
3050 diff_debug_queue("resolve-rename-copy", q);
3051
3052 for (i = 0; i < q->nr; i++) {
3053 p = q->queue[i];
3054 p->status = 0; /* undecided */
3055 if (DIFF_PAIR_UNMERGED(p))
3056 p->status = DIFF_STATUS_UNMERGED;
3057 else if (!DIFF_FILE_VALID(p->one))
3058 p->status = DIFF_STATUS_ADDED;
3059 else if (!DIFF_FILE_VALID(p->two))
3060 p->status = DIFF_STATUS_DELETED;
3061 else if (DIFF_PAIR_TYPE_CHANGED(p))
3062 p->status = DIFF_STATUS_TYPE_CHANGED;
3063
3064 /* from this point on, we are dealing with a pair
3065 * whose both sides are valid and of the same type, i.e.
3066 * either in-place edit or rename/copy edit.
3067 */
3068 else if (DIFF_PAIR_RENAME(p)) {
64479711
LT
3069 /*
3070 * A rename might have re-connected a broken
3071 * pair up, causing the pathnames to be the
3072 * same again. If so, that's not a rename at
3073 * all, just a modification..
3074 *
3075 * Otherwise, see if this source was used for
3076 * multiple renames, in which case we decrement
3077 * the count, and call it a copy.
6973dcae 3078 */
64479711
LT
3079 if (!strcmp(p->one->path, p->two->path))
3080 p->status = DIFF_STATUS_MODIFIED;
3081 else if (--p->one->rename_used > 0)
6973dcae 3082 p->status = DIFF_STATUS_COPIED;
64479711 3083 else
6973dcae
JH
3084 p->status = DIFF_STATUS_RENAMED;
3085 }
a89fccd2 3086 else if (hashcmp(p->one->sha1, p->two->sha1) ||
d516c2d1
JS
3087 p->one->mode != p->two->mode ||
3088 is_null_sha1(p->one->sha1))
6973dcae
JH
3089 p->status = DIFF_STATUS_MODIFIED;
3090 else {
3091 /* This is a "no-change" entry and should not
3092 * happen anymore, but prepare for broken callers.
3093 */
3094 error("feeding unmodified %s to diffcore",
3095 p->one->path);
3096 p->status = DIFF_STATUS_UNKNOWN;
3097 }
3098 }
3099 diff_debug_queue("resolve-rename-copy done", q);
3100}
3101
c6744349 3102static int check_pair_status(struct diff_filepair *p)
6973dcae 3103{
6973dcae
JH
3104 switch (p->status) {
3105 case DIFF_STATUS_UNKNOWN:
c6744349 3106 return 0;
6973dcae
JH
3107 case 0:
3108 die("internal error in diff-resolve-rename-copy");
6973dcae 3109 default:
c6744349 3110 return 1;
6973dcae
JH
3111 }
3112}
3113
c6744349
TH
3114static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
3115{
3116 int fmt = opt->output_format;
3117
3118 if (fmt & DIFF_FORMAT_CHECKDIFF)
3119 diff_flush_checkdiff(p, opt);
3120 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
3121 diff_flush_raw(p, opt);
cd676a51
JH
3122 else if (fmt & DIFF_FORMAT_NAME) {
3123 const char *name_a, *name_b;
3124 name_a = p->two->path;
3125 name_b = NULL;
3126 strip_prefix(opt->prefix_length, &name_a, &name_b);
c0c77734 3127 write_name_quoted(name_a, opt->file, opt->line_termination);
cd676a51 3128 }
c6744349
TH
3129}
3130
c0c77734 3131static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
4bbd261b
SE
3132{
3133 if (fs->mode)
c0c77734 3134 fprintf(file, " %s mode %06o ", newdelete, fs->mode);
4bbd261b 3135 else
c0c77734
DB
3136 fprintf(file, " %s ", newdelete);
3137 write_name_quoted(fs->path, file, '\n');
4bbd261b
SE
3138}
3139
3140
c0c77734 3141static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name)
4bbd261b
SE
3142{
3143 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
c0c77734 3144 fprintf(file, " mode change %06o => %06o%c", p->one->mode, p->two->mode,
663af342 3145 show_name ? ' ' : '\n');
0d26a64e 3146 if (show_name) {
c0c77734 3147 write_name_quoted(p->two->path, file, '\n');
0d26a64e 3148 }
4bbd261b
SE
3149 }
3150}
3151
c0c77734 3152static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p)
4bbd261b 3153{
b9f44164 3154 char *names = pprint_rename(p->one->path, p->two->path);
4bbd261b 3155
c0c77734 3156 fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
b9f44164 3157 free(names);
c0c77734 3158 show_mode_change(file, p, 0);
4bbd261b
SE
3159}
3160
c0c77734 3161static void diff_summary(FILE *file, struct diff_filepair *p)
4bbd261b
SE
3162{
3163 switch(p->status) {
3164 case DIFF_STATUS_DELETED:
c0c77734 3165 show_file_mode_name(file, "delete", p->one);
4bbd261b
SE
3166 break;
3167 case DIFF_STATUS_ADDED:
c0c77734 3168 show_file_mode_name(file, "create", p->two);
4bbd261b
SE
3169 break;
3170 case DIFF_STATUS_COPIED:
c0c77734 3171 show_rename_copy(file, "copy", p);
4bbd261b
SE
3172 break;
3173 case DIFF_STATUS_RENAMED:
c0c77734 3174 show_rename_copy(file, "rename", p);
4bbd261b
SE
3175 break;
3176 default:
3177 if (p->score) {
c0c77734
DB
3178 fputs(" rewrite ", file);
3179 write_name_quoted(p->two->path, file, ' ');
3180 fprintf(file, "(%d%%)\n", similarity_index(p));
663af342 3181 }
c0c77734 3182 show_mode_change(file, p, !p->score);
4bbd261b
SE
3183 break;
3184 }
3185}
3186
fcb3d0ad 3187struct patch_id_t {
9126f009 3188 git_SHA_CTX *ctx;
fcb3d0ad
JS
3189 int patchlen;
3190};
3191
3192static int remove_space(char *line, int len)
3193{
3194 int i;
663af342
PH
3195 char *dst = line;
3196 unsigned char c;
fcb3d0ad 3197
663af342
PH
3198 for (i = 0; i < len; i++)
3199 if (!isspace((c = line[i])))
3200 *dst++ = c;
fcb3d0ad 3201
663af342 3202 return dst - line;
fcb3d0ad
JS
3203}
3204
3205static void patch_id_consume(void *priv, char *line, unsigned long len)
3206{
3207 struct patch_id_t *data = priv;
3208 int new_len;
3209
3210 /* Ignore line numbers when computing the SHA1 of the patch */
cc44c765 3211 if (!prefixcmp(line, "@@ -"))
fcb3d0ad
JS
3212 return;
3213
3214 new_len = remove_space(line, len);
3215
9126f009 3216 git_SHA1_Update(data->ctx, line, new_len);
fcb3d0ad
JS
3217 data->patchlen += new_len;
3218}
3219
3220/* returns 0 upon success, and writes result into sha1 */
3221static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
3222{
3223 struct diff_queue_struct *q = &diff_queued_diff;
3224 int i;
9126f009 3225 git_SHA_CTX ctx;
fcb3d0ad
JS
3226 struct patch_id_t data;
3227 char buffer[PATH_MAX * 4 + 20];
3228
9126f009 3229 git_SHA1_Init(&ctx);
fcb3d0ad
JS
3230 memset(&data, 0, sizeof(struct patch_id_t));
3231 data.ctx = &ctx;
fcb3d0ad
JS
3232
3233 for (i = 0; i < q->nr; i++) {
3234 xpparam_t xpp;
3235 xdemitconf_t xecfg;
3236 xdemitcb_t ecb;
3237 mmfile_t mf1, mf2;
3238 struct diff_filepair *p = q->queue[i];
3239 int len1, len2;
3240
9ccd0a88 3241 memset(&xpp, 0, sizeof(xpp));
30b25010 3242 memset(&xecfg, 0, sizeof(xecfg));
fcb3d0ad
JS
3243 if (p->status == 0)
3244 return error("internal diff status error");
3245 if (p->status == DIFF_STATUS_UNKNOWN)
3246 continue;
3247 if (diff_unmodified_pair(p))
3248 continue;
3249 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3250 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3251 continue;
3252 if (DIFF_PAIR_UNMERGED(p))
3253 continue;
3254
3255 diff_fill_sha1_info(p->one);
3256 diff_fill_sha1_info(p->two);
3257 if (fill_mmfile(&mf1, p->one) < 0 ||
3258 fill_mmfile(&mf2, p->two) < 0)
3259 return error("unable to read files to diff");
3260
fcb3d0ad
JS
3261 len1 = remove_space(p->one->path, strlen(p->one->path));
3262 len2 = remove_space(p->two->path, strlen(p->two->path));
3263 if (p->one->mode == 0)
3264 len1 = snprintf(buffer, sizeof(buffer),
3265 "diff--gita/%.*sb/%.*s"
3266 "newfilemode%06o"
3267 "---/dev/null"
3268 "+++b/%.*s",
3269 len1, p->one->path,
3270 len2, p->two->path,
3271 p->two->mode,
3272 len2, p->two->path);
3273 else if (p->two->mode == 0)
3274 len1 = snprintf(buffer, sizeof(buffer),
3275 "diff--gita/%.*sb/%.*s"
3276 "deletedfilemode%06o"
3277 "---a/%.*s"
3278 "+++/dev/null",
3279 len1, p->one->path,
3280 len2, p->two->path,
3281 p->one->mode,
3282 len1, p->one->path);
3283 else
3284 len1 = snprintf(buffer, sizeof(buffer),
3285 "diff--gita/%.*sb/%.*s"
3286 "---a/%.*s"
3287 "+++b/%.*s",
3288 len1, p->one->path,
3289 len2, p->two->path,
3290 len1, p->one->path,
3291 len2, p->two->path);
9126f009 3292 git_SHA1_Update(&ctx, buffer, len1);
fcb3d0ad
JS
3293
3294 xpp.flags = XDF_NEED_MINIMAL;
3295 xecfg.ctxlen = 3;
9fdc3bb5 3296 xecfg.flags = XDL_EMIT_FUNCNAMES;
8a3f524b
JH
3297 xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
3298 &xpp, &xecfg, &ecb);
fcb3d0ad
JS
3299 }
3300
9126f009 3301 git_SHA1_Final(sha1, &ctx);
fcb3d0ad
JS
3302 return 0;
3303}
3304
3305int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
3306{
3307 struct diff_queue_struct *q = &diff_queued_diff;
3308 int i;
3309 int result = diff_get_patch_id(options, sha1);
3310
3311 for (i = 0; i < q->nr; i++)
3312 diff_free_filepair(q->queue[i]);
3313
3314 free(q->queue);
3315 q->queue = NULL;
3316 q->nr = q->alloc = 0;
3317
3318 return result;
3319}
3320
946c3784 3321static int is_summary_empty(const struct diff_queue_struct *q)
6973dcae 3322{
6973dcae 3323 int i;
6973dcae 3324
946c3784
TH
3325 for (i = 0; i < q->nr; i++) {
3326 const struct diff_filepair *p = q->queue[i];
3327
3328 switch (p->status) {
3329 case DIFF_STATUS_DELETED:
3330 case DIFF_STATUS_ADDED:
3331 case DIFF_STATUS_COPIED:
3332 case DIFF_STATUS_RENAMED:
3333 return 0;
3334 default:
3335 if (p->score)
3336 return 0;
3337 if (p->one->mode && p->two->mode &&
3338 p->one->mode != p->two->mode)
3339 return 0;
3340 break;
3341 }
6973dcae 3342 }
946c3784
TH
3343 return 1;
3344}
3345
6973dcae
JH
3346void diff_flush(struct diff_options *options)
3347{
3348 struct diff_queue_struct *q = &diff_queued_diff;
c6744349 3349 int i, output_format = options->output_format;
946c3784 3350 int separator = 0;
6973dcae 3351
c6744349
TH
3352 /*
3353 * Order: raw, stat, summary, patch
3354 * or: name/name-status/checkdiff (other bits clear)
3355 */
946c3784
TH
3356 if (!q->nr)
3357 goto free_queue;
6973dcae 3358
c6744349
TH
3359 if (output_format & (DIFF_FORMAT_RAW |
3360 DIFF_FORMAT_NAME |
3361 DIFF_FORMAT_NAME_STATUS |
3362 DIFF_FORMAT_CHECKDIFF)) {
6973dcae
JH
3363 for (i = 0; i < q->nr; i++) {
3364 struct diff_filepair *p = q->queue[i];
c6744349
TH
3365 if (check_pair_status(p))
3366 flush_one_pair(p, options);
6973dcae 3367 }
946c3784 3368 separator++;
6973dcae 3369 }
c6744349 3370
c04a7155 3371 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
5e2b0636 3372 struct diffstat_t diffstat;
c6744349 3373
5e2b0636 3374 memset(&diffstat, 0, sizeof(struct diffstat_t));
6973dcae
JH
3375 for (i = 0; i < q->nr; i++) {
3376 struct diff_filepair *p = q->queue[i];
c6744349 3377 if (check_pair_status(p))
5e2b0636 3378 diff_flush_stat(p, options, &diffstat);
6973dcae 3379 }
74e2abe5
JH
3380 if (output_format & DIFF_FORMAT_NUMSTAT)
3381 show_numstat(&diffstat, options);
3382 if (output_format & DIFF_FORMAT_DIFFSTAT)
3383 show_stats(&diffstat, options);
f604652e 3384 if (output_format & DIFF_FORMAT_SHORTSTAT)
c0c77734 3385 show_shortstats(&diffstat, options);
f604652e 3386 free_diffstat_info(&diffstat);
3969cf7d 3387 separator++;
6973dcae 3388 }
c04a7155
JH
3389 if (output_format & DIFF_FORMAT_DIRSTAT)
3390 show_dirstat(options);
6973dcae 3391
946c3784 3392 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
c6744349 3393 for (i = 0; i < q->nr; i++)
c0c77734 3394 diff_summary(options->file, q->queue[i]);
3969cf7d 3395 separator++;
6973dcae
JH
3396 }
3397
c6744349 3398 if (output_format & DIFF_FORMAT_PATCH) {
946c3784 3399 if (separator) {
6b2fbaaf 3400 putc(options->line_termination, options->file);
946c3784
TH
3401 if (options->stat_sep) {
3402 /* attach patch instead of inline */
c0c77734 3403 fputs(options->stat_sep, options->file);
946c3784 3404 }
c6744349
TH
3405 }
3406
3407 for (i = 0; i < q->nr; i++) {
3408 struct diff_filepair *p = q->queue[i];
3409 if (check_pair_status(p))
3410 diff_flush_patch(p, options);
3411 }
4bbd261b
SE
3412 }
3413
04245581
JK
3414 if (output_format & DIFF_FORMAT_CALLBACK)
3415 options->format_callback(q, options, options->format_callback_data);
3416
c6744349
TH
3417 for (i = 0; i < q->nr; i++)
3418 diff_free_filepair(q->queue[i]);
946c3784 3419free_queue:
6973dcae
JH
3420 free(q->queue);
3421 q->queue = NULL;
3422 q->nr = q->alloc = 0;
c0c77734
DB
3423 if (options->close_file)
3424 fclose(options->file);
6973dcae
JH
3425}
3426
3427static void diffcore_apply_filter(const char *filter)
3428{
3429 int i;
3430 struct diff_queue_struct *q = &diff_queued_diff;
3431 struct diff_queue_struct outq;
3432 outq.queue = NULL;
3433 outq.nr = outq.alloc = 0;
3434
3435 if (!filter)
3436 return;
3437
3438 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
3439 int found;
3440 for (i = found = 0; !found && i < q->nr; i++) {
3441 struct diff_filepair *p = q->queue[i];
3442 if (((p->status == DIFF_STATUS_MODIFIED) &&
3443 ((p->score &&
3444 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3445 (!p->score &&
3446 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3447 ((p->status != DIFF_STATUS_MODIFIED) &&
3448 strchr(filter, p->status)))
3449 found++;
3450 }
3451 if (found)
3452 return;
3453
3454 /* otherwise we will clear the whole queue
3455 * by copying the empty outq at the end of this
3456 * function, but first clear the current entries
3457 * in the queue.
3458 */
3459 for (i = 0; i < q->nr; i++)
3460 diff_free_filepair(q->queue[i]);
3461 }
3462 else {
3463 /* Only the matching ones */
3464 for (i = 0; i < q->nr; i++) {
3465 struct diff_filepair *p = q->queue[i];
3466
3467 if (((p->status == DIFF_STATUS_MODIFIED) &&
3468 ((p->score &&
3469 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3470 (!p->score &&
3471 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3472 ((p->status != DIFF_STATUS_MODIFIED) &&
3473 strchr(filter, p->status)))
3474 diff_q(&outq, p);
3475 else
3476 diff_free_filepair(p);
3477 }
3478 }
3479 free(q->queue);
3480 *q = outq;
3481}
3482
5701115a
SV
3483/* Check whether two filespecs with the same mode and size are identical */
3484static int diff_filespec_is_identical(struct diff_filespec *one,
3485 struct diff_filespec *two)
3486{
2b459b48
JH
3487 if (S_ISGITLINK(one->mode))
3488 return 0;
5701115a
SV
3489 if (diff_populate_filespec(one, 0))
3490 return 0;
3491 if (diff_populate_filespec(two, 0))
3492 return 0;
3493 return !memcmp(one->data, two->data, one->size);
3494}
3495
fb13227e
JH
3496static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
3497{
3498 int i;
3499 struct diff_queue_struct *q = &diff_queued_diff;
3500 struct diff_queue_struct outq;
3501 outq.queue = NULL;
3502 outq.nr = outq.alloc = 0;
3503
3504 for (i = 0; i < q->nr; i++) {
3505 struct diff_filepair *p = q->queue[i];
3506
3507 /*
3508 * 1. Entries that come from stat info dirtyness
3509 * always have both sides (iow, not create/delete),
3510 * one side of the object name is unknown, with
3511 * the same mode and size. Keep the ones that
3512 * do not match these criteria. They have real
3513 * differences.
3514 *
3515 * 2. At this point, the file is known to be modified,
3516 * with the same mode and size, and the object
3517 * name of one side is unknown. Need to inspect
3518 * the identical contents.
3519 */
3520 if (!DIFF_FILE_VALID(p->one) || /* (1) */
3521 !DIFF_FILE_VALID(p->two) ||
3522 (p->one->sha1_valid && p->two->sha1_valid) ||
3523 (p->one->mode != p->two->mode) ||
3524 diff_populate_filespec(p->one, 1) ||
3525 diff_populate_filespec(p->two, 1) ||
3526 (p->one->size != p->two->size) ||
5701115a 3527 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
fb13227e
JH
3528 diff_q(&outq, p);
3529 else {
3530 /*
3531 * The caller can subtract 1 from skip_stat_unmatch
3532 * to determine how many paths were dirty only
3533 * due to stat info mismatch.
3534 */
8f67f8ae 3535 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
6d2d9e86 3536 diffopt->skip_stat_unmatch++;
fb13227e
JH
3537 diff_free_filepair(p);
3538 }
3539 }
3540 free(q->queue);
3541 *q = outq;
3542}
3543
6973dcae
JH
3544void diffcore_std(struct diff_options *options)
3545{
9d865356 3546 if (options->skip_stat_unmatch)
fb13227e 3547 diffcore_skip_stat_unmatch(options);
6973dcae
JH
3548 if (options->break_opt != -1)
3549 diffcore_break(options->break_opt);
3550 if (options->detect_rename)
3551 diffcore_rename(options);
3552 if (options->break_opt != -1)
3553 diffcore_merge_broken();
3554 if (options->pickaxe)
3555 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
3556 if (options->orderfile)
3557 diffcore_order(options->orderfile);
3558 diff_resolve_rename_copy();
3559 diffcore_apply_filter(options->filter);
68aacb2f 3560
8f67f8ae
PH
3561 if (diff_queued_diff.nr)
3562 DIFF_OPT_SET(options, HAS_CHANGES);
3563 else
3564 DIFF_OPT_CLR(options, HAS_CHANGES);
6973dcae
JH
3565}
3566
da31b358
JH
3567int diff_result_code(struct diff_options *opt, int status)
3568{
3569 int result = 0;
3570 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3571 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
3572 return status;
3573 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3574 DIFF_OPT_TST(opt, HAS_CHANGES))
3575 result |= 01;
3576 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
3577 DIFF_OPT_TST(opt, CHECK_FAILED))
3578 result |= 02;
3579 return result;
3580}
6973dcae 3581
6973dcae
JH
3582void diff_addremove(struct diff_options *options,
3583 int addremove, unsigned mode,
3584 const unsigned char *sha1,
fd55a19e 3585 const char *concatpath)
6973dcae 3586{
6973dcae
JH
3587 struct diff_filespec *one, *two;
3588
50fd9bd8
JS
3589 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(mode))
3590 return;
3591
6973dcae
JH
3592 /* This may look odd, but it is a preparation for
3593 * feeding "there are unchanged files which should
3594 * not produce diffs, but when you are doing copy
3595 * detection you would need them, so here they are"
3596 * entries to the diff-core. They will be prefixed
3597 * with something like '=' or '*' (I haven't decided
3598 * which but should not make any difference).
a6080a0a 3599 * Feeding the same new and old to diff_change()
6973dcae
JH
3600 * also has the same effect.
3601 * Before the final output happens, they are pruned after
3602 * merged into rename/copy pairs as appropriate.
3603 */
8f67f8ae 3604 if (DIFF_OPT_TST(options, REVERSE_DIFF))
6973dcae
JH
3605 addremove = (addremove == '+' ? '-' :
3606 addremove == '-' ? '+' : addremove);
3607
cd676a51
JH
3608 if (options->prefix &&
3609 strncmp(concatpath, options->prefix, options->prefix_length))
3610 return;
3611
6973dcae
JH
3612 one = alloc_filespec(concatpath);
3613 two = alloc_filespec(concatpath);
3614
3615 if (addremove != '+')
3616 fill_filespec(one, sha1, mode);
3617 if (addremove != '-')
3618 fill_filespec(two, sha1, mode);
3619
3620 diff_queue(&diff_queued_diff, one, two);
8f67f8ae 3621 DIFF_OPT_SET(options, HAS_CHANGES);
6973dcae
JH
3622}
3623
3624void diff_change(struct diff_options *options,
3625 unsigned old_mode, unsigned new_mode,
3626 const unsigned char *old_sha1,
3627 const unsigned char *new_sha1,
fd55a19e 3628 const char *concatpath)
6973dcae 3629{
6973dcae
JH
3630 struct diff_filespec *one, *two;
3631
50fd9bd8
JS
3632 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(old_mode)
3633 && S_ISGITLINK(new_mode))
3634 return;
3635
8f67f8ae 3636 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
6973dcae
JH
3637 unsigned tmp;
3638 const unsigned char *tmp_c;
3639 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
3640 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
3641 }
cd676a51
JH
3642
3643 if (options->prefix &&
3644 strncmp(concatpath, options->prefix, options->prefix_length))
3645 return;
3646
6973dcae
JH
3647 one = alloc_filespec(concatpath);
3648 two = alloc_filespec(concatpath);
3649 fill_filespec(one, old_sha1, old_mode);
3650 fill_filespec(two, new_sha1, new_mode);
3651
3652 diff_queue(&diff_queued_diff, one, two);
8f67f8ae 3653 DIFF_OPT_SET(options, HAS_CHANGES);
6973dcae
JH
3654}
3655
3656void diff_unmerge(struct diff_options *options,
e9c84099
JH
3657 const char *path,
3658 unsigned mode, const unsigned char *sha1)
6973dcae
JH
3659{
3660 struct diff_filespec *one, *two;
cd676a51
JH
3661
3662 if (options->prefix &&
3663 strncmp(path, options->prefix, options->prefix_length))
3664 return;
3665
6973dcae
JH
3666 one = alloc_filespec(path);
3667 two = alloc_filespec(path);
e9c84099
JH
3668 fill_filespec(one, sha1, mode);
3669 diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;
6973dcae 3670}
9cb92c39
JK
3671
3672static char *run_textconv(const char *pgm, struct diff_filespec *spec,
3673 size_t *outsize)
3674{
479b0ae8 3675 struct diff_tempfile *temp;
9cb92c39
JK
3676 const char *argv[3];
3677 const char **arg = argv;