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