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