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