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