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