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