Fix memory leak in --submodule-summary
[git/dscho.git] / diff.c
blobcdef322b2effbba2ae83a4839630e17f1caf42f1
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"
18 #ifdef NO_FAST_WORKING_DIRECTORY
19 #define FAST_WORKING_DIRECTORY 0
20 #else
21 #define FAST_WORKING_DIRECTORY 1
22 #endif
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;
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 */
44 static void diff_filespec_load_driver(struct diff_filespec *one);
45 static char *run_textconv(const char *, struct diff_filespec *, size_t *);
47 static int parse_diff_color_slot(const char *var, int ofs)
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);
66 static int git_config_rename(const char *var, const char *value)
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;
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.
81 int git_diff_ui_config(const char *var, const char *value, void *cb)
83 if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
84 diff_use_color_default = git_config_colorbool(var, value, -1);
85 return 0;
87 if (!strcmp(var, "diff.renames")) {
88 diff_detect_rename_default = git_config_rename(var, value);
89 return 0;
91 if (!strcmp(var, "diff.autorefreshindex")) {
92 diff_auto_refresh_index = git_config_bool(var, value);
93 return 0;
95 if (!strcmp(var, "diff.mnemonicprefix")) {
96 diff_mnemonic_prefix = git_config_bool(var, value);
97 return 0;
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);
104 return git_diff_basic_config(var, value, cb);
107 int git_diff_basic_config(const char *var, const char *value, void *cb)
109 if (!strcmp(var, "diff.renamelimit")) {
110 diff_rename_limit_default = git_config_int(var, value);
111 return 0;
114 switch (userdiff_config(var, value)) {
115 case 0: break;
116 case -1: return -1;
117 default: return 0;
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;
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;
136 return git_color_default_config(var, value, cb);
139 static char *quote_two(const char *one, const char *two)
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;
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);
154 return strbuf_detach(&res, NULL);
157 static const char *external_diff(void)
159 static const char *external_diff_cmd = NULL;
160 static int done_preparing = 0;
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;
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];
178 typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
180 struct emit_callback {
181 int color_diff;
182 unsigned ws_rule;
183 int blank_at_eof_in_preimage;
184 int blank_at_eof_in_postimage;
185 int lno_in_preimage;
186 int lno_in_postimage;
187 sane_truncate_fn truncate;
188 const char **label_path;
189 struct diff_words_data *diff_words;
190 int *found_changesp;
191 FILE *file;
194 static int count_lines(const char *data, int size)
196 int count, ch, completely_empty = 1, nl_just_seen = 0;
197 count = 0;
198 while (0 < size--) {
199 ch = *data++;
200 if (ch == '\n') {
201 count++;
202 nl_just_seen = 1;
203 completely_empty = 0;
205 else {
206 nl_just_seen = 0;
207 completely_empty = 0;
210 if (completely_empty)
211 return 0;
212 if (!nl_just_seen)
213 count++; /* no trailing newline */
214 return count;
217 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
219 if (!DIFF_FILE_VALID(one)) {
220 mf->ptr = (char *)""; /* does not matter */
221 mf->size = 0;
222 return 0;
224 else if (diff_populate_filespec(one, 0))
225 return -1;
227 mf->ptr = one->data;
228 mf->size = one->size;
229 return 0;
232 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
234 char *ptr = mf->ptr;
235 long size = mf->size;
236 int cnt = 0;
238 if (!size)
239 return cnt;
240 ptr += size - 1; /* pointing at the very end */
241 if (*ptr != '\n')
242 ; /* incomplete line */
243 else
244 ptr--; /* skip the last LF */
245 while (mf->ptr < ptr) {
246 char *prev_eol;
247 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
248 if (*prev_eol == '\n')
249 break;
250 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
251 break;
252 cnt++;
253 ptr = prev_eol - 1;
255 return cnt;
258 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
259 struct emit_callback *ecbdata)
261 int l1, l2, at;
262 unsigned ws_rule = ecbdata->ws_rule;
263 l1 = count_trailing_blank(mf1, ws_rule);
264 l2 = count_trailing_blank(mf2, ws_rule);
265 if (l2 <= l1) {
266 ecbdata->blank_at_eof_in_preimage = 0;
267 ecbdata->blank_at_eof_in_postimage = 0;
268 return;
270 at = count_lines(mf1->ptr, mf1->size);
271 ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
273 at = count_lines(mf2->ptr, mf2->size);
274 ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
277 static void emit_line_0(FILE *file, const char *set, const char *reset,
278 int first, const char *line, int len)
280 int has_trailing_newline, has_trailing_carriage_return;
281 int nofirst;
283 if (len == 0) {
284 has_trailing_newline = (first == '\n');
285 has_trailing_carriage_return = (!has_trailing_newline &&
286 (first == '\r'));
287 nofirst = has_trailing_newline || has_trailing_carriage_return;
288 } else {
289 has_trailing_newline = (len > 0 && line[len-1] == '\n');
290 if (has_trailing_newline)
291 len--;
292 has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
293 if (has_trailing_carriage_return)
294 len--;
295 nofirst = 0;
298 fputs(set, file);
300 if (!nofirst)
301 fputc(first, file);
302 fwrite(line, len, 1, file);
303 fputs(reset, file);
304 if (has_trailing_carriage_return)
305 fputc('\r', file);
306 if (has_trailing_newline)
307 fputc('\n', file);
310 static void emit_line(FILE *file, const char *set, const char *reset,
311 const char *line, int len)
313 emit_line_0(file, set, reset, line[0], line+1, len-1);
316 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
318 if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
319 ecbdata->blank_at_eof_in_preimage &&
320 ecbdata->blank_at_eof_in_postimage &&
321 ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
322 ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
323 return 0;
324 return ws_blank_line(line, len, ecbdata->ws_rule);
327 static void emit_add_line(const char *reset,
328 struct emit_callback *ecbdata,
329 const char *line, int len)
331 const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
332 const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
334 if (!*ws)
335 emit_line_0(ecbdata->file, set, reset, '+', line, len);
336 else if (new_blank_line_at_eof(ecbdata, line, len))
337 /* Blank line at EOF - paint '+' as well */
338 emit_line_0(ecbdata->file, ws, reset, '+', line, len);
339 else {
340 /* Emit just the prefix, then the rest. */
341 emit_line_0(ecbdata->file, set, reset, '+', "", 0);
342 ws_check_emit(line, len, ecbdata->ws_rule,
343 ecbdata->file, set, reset, ws);
347 static struct diff_tempfile *claim_diff_tempfile(void) {
348 int i;
349 for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
350 if (!diff_temp[i].name)
351 return diff_temp + i;
352 die("BUG: diff is failing to clean up its tempfiles");
355 static int remove_tempfile_installed;
357 static void remove_tempfile(void)
359 int i;
360 for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
361 if (diff_temp[i].name == diff_temp[i].tmp_path)
362 unlink_or_warn(diff_temp[i].name);
363 diff_temp[i].name = NULL;
367 static void remove_tempfile_on_signal(int signo)
369 remove_tempfile();
370 sigchain_pop(signo);
371 raise(signo);
374 static void print_line_count(FILE *file, int count)
376 switch (count) {
377 case 0:
378 fprintf(file, "0,0");
379 break;
380 case 1:
381 fprintf(file, "1");
382 break;
383 default:
384 fprintf(file, "1,%d", count);
385 break;
389 static void emit_rewrite_lines(struct emit_callback *ecb,
390 int prefix, const char *data, int size)
392 const char *endp = NULL;
393 static const char *nneof = " No newline at end of file\n";
394 const char *old = diff_get_color(ecb->color_diff, DIFF_FILE_OLD);
395 const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
397 while (0 < size) {
398 int len;
400 endp = memchr(data, '\n', size);
401 len = endp ? (endp - data + 1) : size;
402 if (prefix != '+') {
403 ecb->lno_in_preimage++;
404 emit_line_0(ecb->file, old, reset, '-',
405 data, len);
406 } else {
407 ecb->lno_in_postimage++;
408 emit_add_line(reset, ecb, data, len);
410 size -= len;
411 data += len;
413 if (!endp) {
414 const char *plain = diff_get_color(ecb->color_diff,
415 DIFF_PLAIN);
416 emit_line_0(ecb->file, plain, reset, '\\',
417 nneof, strlen(nneof));
421 static void emit_rewrite_diff(const char *name_a,
422 const char *name_b,
423 struct diff_filespec *one,
424 struct diff_filespec *two,
425 const char *textconv_one,
426 const char *textconv_two,
427 struct diff_options *o)
429 int lc_a, lc_b;
430 int color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
431 const char *name_a_tab, *name_b_tab;
432 const char *metainfo = diff_get_color(color_diff, DIFF_METAINFO);
433 const char *fraginfo = diff_get_color(color_diff, DIFF_FRAGINFO);
434 const char *reset = diff_get_color(color_diff, DIFF_RESET);
435 static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
436 const char *a_prefix, *b_prefix;
437 const char *data_one, *data_two;
438 size_t size_one, size_two;
439 struct emit_callback ecbdata;
441 if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
442 a_prefix = o->b_prefix;
443 b_prefix = o->a_prefix;
444 } else {
445 a_prefix = o->a_prefix;
446 b_prefix = o->b_prefix;
449 name_a += (*name_a == '/');
450 name_b += (*name_b == '/');
451 name_a_tab = strchr(name_a, ' ') ? "\t" : "";
452 name_b_tab = strchr(name_b, ' ') ? "\t" : "";
454 strbuf_reset(&a_name);
455 strbuf_reset(&b_name);
456 quote_two_c_style(&a_name, a_prefix, name_a, 0);
457 quote_two_c_style(&b_name, b_prefix, name_b, 0);
459 diff_populate_filespec(one, 0);
460 diff_populate_filespec(two, 0);
461 if (textconv_one) {
462 data_one = run_textconv(textconv_one, one, &size_one);
463 if (!data_one)
464 die("unable to read files to diff");
466 else {
467 data_one = one->data;
468 size_one = one->size;
470 if (textconv_two) {
471 data_two = run_textconv(textconv_two, two, &size_two);
472 if (!data_two)
473 die("unable to read files to diff");
475 else {
476 data_two = two->data;
477 size_two = two->size;
480 memset(&ecbdata, 0, sizeof(ecbdata));
481 ecbdata.color_diff = color_diff;
482 ecbdata.found_changesp = &o->found_changes;
483 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
484 ecbdata.file = o->file;
485 if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
486 mmfile_t mf1, mf2;
487 mf1.ptr = (char *)data_one;
488 mf2.ptr = (char *)data_two;
489 mf1.size = size_one;
490 mf2.size = size_two;
491 check_blank_at_eof(&mf1, &mf2, &ecbdata);
493 ecbdata.lno_in_preimage = 1;
494 ecbdata.lno_in_postimage = 1;
496 lc_a = count_lines(data_one, size_one);
497 lc_b = count_lines(data_two, size_two);
498 fprintf(o->file,
499 "%s--- %s%s%s\n%s+++ %s%s%s\n%s@@ -",
500 metainfo, a_name.buf, name_a_tab, reset,
501 metainfo, b_name.buf, name_b_tab, reset, fraginfo);
502 print_line_count(o->file, lc_a);
503 fprintf(o->file, " +");
504 print_line_count(o->file, lc_b);
505 fprintf(o->file, " @@%s\n", reset);
506 if (lc_a)
507 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
508 if (lc_b)
509 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
512 struct diff_words_buffer {
513 mmfile_t text;
514 long alloc;
515 struct diff_words_orig {
516 const char *begin, *end;
517 } *orig;
518 int orig_nr, orig_alloc;
521 static void diff_words_append(char *line, unsigned long len,
522 struct diff_words_buffer *buffer)
524 ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
525 line++;
526 len--;
527 memcpy(buffer->text.ptr + buffer->text.size, line, len);
528 buffer->text.size += len;
529 buffer->text.ptr[buffer->text.size] = '\0';
532 struct diff_words_data {
533 struct diff_words_buffer minus, plus;
534 const char *current_plus;
535 FILE *file;
536 regex_t *word_regex;
539 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
541 struct diff_words_data *diff_words = priv;
542 int minus_first, minus_len, plus_first, plus_len;
543 const char *minus_begin, *minus_end, *plus_begin, *plus_end;
545 if (line[0] != '@' || parse_hunk_header(line, len,
546 &minus_first, &minus_len, &plus_first, &plus_len))
547 return;
549 /* POSIX requires that first be decremented by one if len == 0... */
550 if (minus_len) {
551 minus_begin = diff_words->minus.orig[minus_first].begin;
552 minus_end =
553 diff_words->minus.orig[minus_first + minus_len - 1].end;
554 } else
555 minus_begin = minus_end =
556 diff_words->minus.orig[minus_first].end;
558 if (plus_len) {
559 plus_begin = diff_words->plus.orig[plus_first].begin;
560 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
561 } else
562 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
564 if (diff_words->current_plus != plus_begin)
565 fwrite(diff_words->current_plus,
566 plus_begin - diff_words->current_plus, 1,
567 diff_words->file);
568 if (minus_begin != minus_end)
569 color_fwrite_lines(diff_words->file,
570 diff_get_color(1, DIFF_FILE_OLD),
571 minus_end - minus_begin, minus_begin);
572 if (plus_begin != plus_end)
573 color_fwrite_lines(diff_words->file,
574 diff_get_color(1, DIFF_FILE_NEW),
575 plus_end - plus_begin, plus_begin);
577 diff_words->current_plus = plus_end;
580 /* This function starts looking at *begin, and returns 0 iff a word was found. */
581 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
582 int *begin, int *end)
584 if (word_regex && *begin < buffer->size) {
585 regmatch_t match[1];
586 if (!regexec(word_regex, buffer->ptr + *begin, 1, match, 0)) {
587 char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
588 '\n', match[0].rm_eo - match[0].rm_so);
589 *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
590 *begin += match[0].rm_so;
591 return *begin >= *end;
593 return -1;
596 /* find the next word */
597 while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
598 (*begin)++;
599 if (*begin >= buffer->size)
600 return -1;
602 /* find the end of the word */
603 *end = *begin + 1;
604 while (*end < buffer->size && !isspace(buffer->ptr[*end]))
605 (*end)++;
607 return 0;
611 * This function splits the words in buffer->text, stores the list with
612 * newline separator into out, and saves the offsets of the original words
613 * in buffer->orig.
615 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
616 regex_t *word_regex)
618 int i, j;
619 long alloc = 0;
621 out->size = 0;
622 out->ptr = NULL;
624 /* fake an empty "0th" word */
625 ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
626 buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
627 buffer->orig_nr = 1;
629 for (i = 0; i < buffer->text.size; i++) {
630 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
631 return;
633 /* store original boundaries */
634 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
635 buffer->orig_alloc);
636 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
637 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
638 buffer->orig_nr++;
640 /* store one word */
641 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
642 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
643 out->ptr[out->size + j - i] = '\n';
644 out->size += j - i + 1;
646 i = j - 1;
650 /* this executes the word diff on the accumulated buffers */
651 static void diff_words_show(struct diff_words_data *diff_words)
653 xpparam_t xpp;
654 xdemitconf_t xecfg;
655 xdemitcb_t ecb;
656 mmfile_t minus, plus;
658 /* special case: only removal */
659 if (!diff_words->plus.text.size) {
660 color_fwrite_lines(diff_words->file,
661 diff_get_color(1, DIFF_FILE_OLD),
662 diff_words->minus.text.size, diff_words->minus.text.ptr);
663 diff_words->minus.text.size = 0;
664 return;
667 diff_words->current_plus = diff_words->plus.text.ptr;
669 memset(&xpp, 0, sizeof(xpp));
670 memset(&xecfg, 0, sizeof(xecfg));
671 diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
672 diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
673 xpp.flags = XDF_NEED_MINIMAL;
674 /* as only the hunk header will be parsed, we need a 0-context */
675 xecfg.ctxlen = 0;
676 xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
677 &xpp, &xecfg, &ecb);
678 free(minus.ptr);
679 free(plus.ptr);
680 if (diff_words->current_plus != diff_words->plus.text.ptr +
681 diff_words->plus.text.size)
682 fwrite(diff_words->current_plus,
683 diff_words->plus.text.ptr + diff_words->plus.text.size
684 - diff_words->current_plus, 1,
685 diff_words->file);
686 diff_words->minus.text.size = diff_words->plus.text.size = 0;
689 static void free_diff_words_data(struct emit_callback *ecbdata)
691 if (ecbdata->diff_words) {
692 /* flush buffers */
693 if (ecbdata->diff_words->minus.text.size ||
694 ecbdata->diff_words->plus.text.size)
695 diff_words_show(ecbdata->diff_words);
697 free (ecbdata->diff_words->minus.text.ptr);
698 free (ecbdata->diff_words->minus.orig);
699 free (ecbdata->diff_words->plus.text.ptr);
700 free (ecbdata->diff_words->plus.orig);
701 free(ecbdata->diff_words->word_regex);
702 free(ecbdata->diff_words);
703 ecbdata->diff_words = NULL;
707 const char *diff_get_color(int diff_use_color, enum color_diff ix)
709 if (diff_use_color)
710 return diff_colors[ix];
711 return "";
714 static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
716 const char *cp;
717 unsigned long allot;
718 size_t l = len;
720 if (ecb->truncate)
721 return ecb->truncate(line, len);
722 cp = line;
723 allot = l;
724 while (0 < l) {
725 (void) utf8_width(&cp, &l);
726 if (!cp)
727 break; /* truncated in the middle? */
729 return allot - l;
732 static void find_lno(const char *line, struct emit_callback *ecbdata)
734 const char *p;
735 ecbdata->lno_in_preimage = 0;
736 ecbdata->lno_in_postimage = 0;
737 p = strchr(line, '-');
738 if (!p)
739 return; /* cannot happen */
740 ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
741 p = strchr(p, '+');
742 if (!p)
743 return; /* cannot happen */
744 ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
747 static void fn_out_consume(void *priv, char *line, unsigned long len)
749 struct emit_callback *ecbdata = priv;
750 const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
751 const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
752 const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
754 *(ecbdata->found_changesp) = 1;
756 if (ecbdata->label_path[0]) {
757 const char *name_a_tab, *name_b_tab;
759 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
760 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
762 fprintf(ecbdata->file, "%s--- %s%s%s\n",
763 meta, ecbdata->label_path[0], reset, name_a_tab);
764 fprintf(ecbdata->file, "%s+++ %s%s%s\n",
765 meta, ecbdata->label_path[1], reset, name_b_tab);
766 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
769 if (diff_suppress_blank_empty
770 && len == 2 && line[0] == ' ' && line[1] == '\n') {
771 line[0] = '\n';
772 len = 1;
775 if (line[0] == '@') {
776 len = sane_truncate_line(ecbdata, line, len);
777 find_lno(line, ecbdata);
778 emit_line(ecbdata->file,
779 diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO),
780 reset, line, len);
781 if (line[len-1] != '\n')
782 putc('\n', ecbdata->file);
783 return;
786 if (len < 1) {
787 emit_line(ecbdata->file, reset, reset, line, len);
788 return;
791 if (ecbdata->diff_words) {
792 if (line[0] == '-') {
793 diff_words_append(line, len,
794 &ecbdata->diff_words->minus);
795 return;
796 } else if (line[0] == '+') {
797 diff_words_append(line, len,
798 &ecbdata->diff_words->plus);
799 return;
801 if (ecbdata->diff_words->minus.text.size ||
802 ecbdata->diff_words->plus.text.size)
803 diff_words_show(ecbdata->diff_words);
804 line++;
805 len--;
806 emit_line(ecbdata->file, plain, reset, line, len);
807 return;
810 if (line[0] != '+') {
811 const char *color =
812 diff_get_color(ecbdata->color_diff,
813 line[0] == '-' ? DIFF_FILE_OLD : DIFF_PLAIN);
814 ecbdata->lno_in_preimage++;
815 if (line[0] == ' ')
816 ecbdata->lno_in_postimage++;
817 emit_line(ecbdata->file, color, reset, line, len);
818 } else {
819 ecbdata->lno_in_postimage++;
820 emit_add_line(reset, ecbdata, line + 1, len - 1);
824 static char *pprint_rename(const char *a, const char *b)
826 const char *old = a;
827 const char *new = b;
828 struct strbuf name = STRBUF_INIT;
829 int pfx_length, sfx_length;
830 int len_a = strlen(a);
831 int len_b = strlen(b);
832 int a_midlen, b_midlen;
833 int qlen_a = quote_c_style(a, NULL, NULL, 0);
834 int qlen_b = quote_c_style(b, NULL, NULL, 0);
836 if (qlen_a || qlen_b) {
837 quote_c_style(a, &name, NULL, 0);
838 strbuf_addstr(&name, " => ");
839 quote_c_style(b, &name, NULL, 0);
840 return strbuf_detach(&name, NULL);
843 /* Find common prefix */
844 pfx_length = 0;
845 while (*old && *new && *old == *new) {
846 if (*old == '/')
847 pfx_length = old - a + 1;
848 old++;
849 new++;
852 /* Find common suffix */
853 old = a + len_a;
854 new = b + len_b;
855 sfx_length = 0;
856 while (a <= old && b <= new && *old == *new) {
857 if (*old == '/')
858 sfx_length = len_a - (old - a);
859 old--;
860 new--;
864 * pfx{mid-a => mid-b}sfx
865 * {pfx-a => pfx-b}sfx
866 * pfx{sfx-a => sfx-b}
867 * name-a => name-b
869 a_midlen = len_a - pfx_length - sfx_length;
870 b_midlen = len_b - pfx_length - sfx_length;
871 if (a_midlen < 0)
872 a_midlen = 0;
873 if (b_midlen < 0)
874 b_midlen = 0;
876 strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
877 if (pfx_length + sfx_length) {
878 strbuf_add(&name, a, pfx_length);
879 strbuf_addch(&name, '{');
881 strbuf_add(&name, a + pfx_length, a_midlen);
882 strbuf_addstr(&name, " => ");
883 strbuf_add(&name, b + pfx_length, b_midlen);
884 if (pfx_length + sfx_length) {
885 strbuf_addch(&name, '}');
886 strbuf_add(&name, a + len_a - sfx_length, sfx_length);
888 return strbuf_detach(&name, NULL);
891 struct diffstat_t {
892 int nr;
893 int alloc;
894 struct diffstat_file {
895 char *from_name;
896 char *name;
897 char *print_name;
898 unsigned is_unmerged:1;
899 unsigned is_binary:1;
900 unsigned is_renamed:1;
901 unsigned int added, deleted;
902 } **files;
905 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
906 const char *name_a,
907 const char *name_b)
909 struct diffstat_file *x;
910 x = xcalloc(sizeof (*x), 1);
911 if (diffstat->nr == diffstat->alloc) {
912 diffstat->alloc = alloc_nr(diffstat->alloc);
913 diffstat->files = xrealloc(diffstat->files,
914 diffstat->alloc * sizeof(x));
916 diffstat->files[diffstat->nr++] = x;
917 if (name_b) {
918 x->from_name = xstrdup(name_a);
919 x->name = xstrdup(name_b);
920 x->is_renamed = 1;
922 else {
923 x->from_name = NULL;
924 x->name = xstrdup(name_a);
926 return x;
929 static void diffstat_consume(void *priv, char *line, unsigned long len)
931 struct diffstat_t *diffstat = priv;
932 struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
934 if (line[0] == '+')
935 x->added++;
936 else if (line[0] == '-')
937 x->deleted++;
940 const char mime_boundary_leader[] = "------------";
942 static int scale_linear(int it, int width, int max_change)
945 * make sure that at least one '-' is printed if there were deletions,
946 * and likewise for '+'.
948 if (max_change < 2)
949 return it;
950 return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
953 static void show_name(FILE *file,
954 const char *prefix, const char *name, int len)
956 fprintf(file, " %s%-*s |", prefix, len, name);
959 static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
961 if (cnt <= 0)
962 return;
963 fprintf(file, "%s", set);
964 while (cnt--)
965 putc(ch, file);
966 fprintf(file, "%s", reset);
969 static void fill_print_name(struct diffstat_file *file)
971 char *pname;
973 if (file->print_name)
974 return;
976 if (!file->is_renamed) {
977 struct strbuf buf = STRBUF_INIT;
978 if (quote_c_style(file->name, &buf, NULL, 0)) {
979 pname = strbuf_detach(&buf, NULL);
980 } else {
981 pname = file->name;
982 strbuf_release(&buf);
984 } else {
985 pname = pprint_rename(file->from_name, file->name);
987 file->print_name = pname;
990 static void show_stats(struct diffstat_t *data, struct diff_options *options)
992 int i, len, add, del, adds = 0, dels = 0;
993 int max_change = 0, max_len = 0;
994 int total_files = data->nr;
995 int width, name_width;
996 const char *reset, *set, *add_c, *del_c;
998 if (data->nr == 0)
999 return;
1001 width = options->stat_width ? options->stat_width : 80;
1002 name_width = options->stat_name_width ? options->stat_name_width : 50;
1004 /* Sanity: give at least 5 columns to the graph,
1005 * but leave at least 10 columns for the name.
1007 if (width < 25)
1008 width = 25;
1009 if (name_width < 10)
1010 name_width = 10;
1011 else if (width < name_width + 15)
1012 name_width = width - 15;
1014 /* Find the longest filename and max number of changes */
1015 reset = diff_get_color_opt(options, DIFF_RESET);
1016 set = diff_get_color_opt(options, DIFF_PLAIN);
1017 add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
1018 del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
1020 for (i = 0; i < data->nr; i++) {
1021 struct diffstat_file *file = data->files[i];
1022 int change = file->added + file->deleted;
1023 fill_print_name(file);
1024 len = strlen(file->print_name);
1025 if (max_len < len)
1026 max_len = len;
1028 if (file->is_binary || file->is_unmerged)
1029 continue;
1030 if (max_change < change)
1031 max_change = change;
1034 /* Compute the width of the graph part;
1035 * 10 is for one blank at the beginning of the line plus
1036 * " | count " between the name and the graph.
1038 * From here on, name_width is the width of the name area,
1039 * and width is the width of the graph area.
1041 name_width = (name_width < max_len) ? name_width : max_len;
1042 if (width < (name_width + 10) + max_change)
1043 width = width - (name_width + 10);
1044 else
1045 width = max_change;
1047 for (i = 0; i < data->nr; i++) {
1048 const char *prefix = "";
1049 char *name = data->files[i]->print_name;
1050 int added = data->files[i]->added;
1051 int deleted = data->files[i]->deleted;
1052 int name_len;
1055 * "scale" the filename
1057 len = name_width;
1058 name_len = strlen(name);
1059 if (name_width < name_len) {
1060 char *slash;
1061 prefix = "...";
1062 len -= 3;
1063 name += name_len - len;
1064 slash = strchr(name, '/');
1065 if (slash)
1066 name = slash;
1069 if (data->files[i]->is_binary) {
1070 show_name(options->file, prefix, name, len);
1071 fprintf(options->file, " Bin ");
1072 fprintf(options->file, "%s%d%s", del_c, deleted, reset);
1073 fprintf(options->file, " -> ");
1074 fprintf(options->file, "%s%d%s", add_c, added, reset);
1075 fprintf(options->file, " bytes");
1076 fprintf(options->file, "\n");
1077 continue;
1079 else if (data->files[i]->is_unmerged) {
1080 show_name(options->file, prefix, name, len);
1081 fprintf(options->file, " Unmerged\n");
1082 continue;
1084 else if (!data->files[i]->is_renamed &&
1085 (added + deleted == 0)) {
1086 total_files--;
1087 continue;
1091 * scale the add/delete
1093 add = added;
1094 del = deleted;
1095 adds += add;
1096 dels += del;
1098 if (width <= max_change) {
1099 add = scale_linear(add, width, max_change);
1100 del = scale_linear(del, width, max_change);
1102 show_name(options->file, prefix, name, len);
1103 fprintf(options->file, "%5d%s", added + deleted,
1104 added + deleted ? " " : "");
1105 show_graph(options->file, '+', add, add_c, reset);
1106 show_graph(options->file, '-', del, del_c, reset);
1107 fprintf(options->file, "\n");
1109 fprintf(options->file,
1110 " %d files changed, %d insertions(+), %d deletions(-)\n",
1111 total_files, adds, dels);
1114 static void show_shortstats(struct diffstat_t* data, struct diff_options *options)
1116 int i, adds = 0, dels = 0, total_files = data->nr;
1118 if (data->nr == 0)
1119 return;
1121 for (i = 0; i < data->nr; i++) {
1122 if (!data->files[i]->is_binary &&
1123 !data->files[i]->is_unmerged) {
1124 int added = data->files[i]->added;
1125 int deleted= data->files[i]->deleted;
1126 if (!data->files[i]->is_renamed &&
1127 (added + deleted == 0)) {
1128 total_files--;
1129 } else {
1130 adds += added;
1131 dels += deleted;
1135 fprintf(options->file, " %d files changed, %d insertions(+), %d deletions(-)\n",
1136 total_files, adds, dels);
1139 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
1141 int i;
1143 if (data->nr == 0)
1144 return;
1146 for (i = 0; i < data->nr; i++) {
1147 struct diffstat_file *file = data->files[i];
1149 if (file->is_binary)
1150 fprintf(options->file, "-\t-\t");
1151 else
1152 fprintf(options->file,
1153 "%d\t%d\t", file->added, file->deleted);
1154 if (options->line_termination) {
1155 fill_print_name(file);
1156 if (!file->is_renamed)
1157 write_name_quoted(file->name, options->file,
1158 options->line_termination);
1159 else {
1160 fputs(file->print_name, options->file);
1161 putc(options->line_termination, options->file);
1163 } else {
1164 if (file->is_renamed) {
1165 putc('\0', options->file);
1166 write_name_quoted(file->from_name, options->file, '\0');
1168 write_name_quoted(file->name, options->file, '\0');
1173 struct dirstat_file {
1174 const char *name;
1175 unsigned long changed;
1178 struct dirstat_dir {
1179 struct dirstat_file *files;
1180 int alloc, nr, percent, cumulative;
1183 static long gather_dirstat(FILE *file, struct dirstat_dir *dir, unsigned long changed, const char *base, int baselen)
1185 unsigned long this_dir = 0;
1186 unsigned int sources = 0;
1188 while (dir->nr) {
1189 struct dirstat_file *f = dir->files;
1190 int namelen = strlen(f->name);
1191 unsigned long this;
1192 char *slash;
1194 if (namelen < baselen)
1195 break;
1196 if (memcmp(f->name, base, baselen))
1197 break;
1198 slash = strchr(f->name + baselen, '/');
1199 if (slash) {
1200 int newbaselen = slash + 1 - f->name;
1201 this = gather_dirstat(file, dir, changed, f->name, newbaselen);
1202 sources++;
1203 } else {
1204 this = f->changed;
1205 dir->files++;
1206 dir->nr--;
1207 sources += 2;
1209 this_dir += this;
1213 * We don't report dirstat's for
1214 * - the top level
1215 * - or cases where everything came from a single directory
1216 * under this directory (sources == 1).
1218 if (baselen && sources != 1) {
1219 int permille = this_dir * 1000 / changed;
1220 if (permille) {
1221 int percent = permille / 10;
1222 if (percent >= dir->percent) {
1223 fprintf(file, "%4d.%01d%% %.*s\n", percent, permille % 10, baselen, base);
1224 if (!dir->cumulative)
1225 return 0;
1229 return this_dir;
1232 static int dirstat_compare(const void *_a, const void *_b)
1234 const struct dirstat_file *a = _a;
1235 const struct dirstat_file *b = _b;
1236 return strcmp(a->name, b->name);
1239 static void show_dirstat(struct diff_options *options)
1241 int i;
1242 unsigned long changed;
1243 struct dirstat_dir dir;
1244 struct diff_queue_struct *q = &diff_queued_diff;
1246 dir.files = NULL;
1247 dir.alloc = 0;
1248 dir.nr = 0;
1249 dir.percent = options->dirstat_percent;
1250 dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
1252 changed = 0;
1253 for (i = 0; i < q->nr; i++) {
1254 struct diff_filepair *p = q->queue[i];
1255 const char *name;
1256 unsigned long copied, added, damage;
1258 name = p->one->path ? p->one->path : p->two->path;
1260 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1261 diff_populate_filespec(p->one, 0);
1262 diff_populate_filespec(p->two, 0);
1263 diffcore_count_changes(p->one, p->two, NULL, NULL, 0,
1264 &copied, &added);
1265 diff_free_filespec_data(p->one);
1266 diff_free_filespec_data(p->two);
1267 } else if (DIFF_FILE_VALID(p->one)) {
1268 diff_populate_filespec(p->one, 1);
1269 copied = added = 0;
1270 diff_free_filespec_data(p->one);
1271 } else if (DIFF_FILE_VALID(p->two)) {
1272 diff_populate_filespec(p->two, 1);
1273 copied = 0;
1274 added = p->two->size;
1275 diff_free_filespec_data(p->two);
1276 } else
1277 continue;
1280 * Original minus copied is the removed material,
1281 * added is the new material. They are both damages
1282 * made to the preimage. In --dirstat-by-file mode, count
1283 * damaged files, not damaged lines. This is done by
1284 * counting only a single damaged line per file.
1286 damage = (p->one->size - copied) + added;
1287 if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE) && damage > 0)
1288 damage = 1;
1290 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1291 dir.files[dir.nr].name = name;
1292 dir.files[dir.nr].changed = damage;
1293 changed += damage;
1294 dir.nr++;
1297 /* This can happen even with many files, if everything was renames */
1298 if (!changed)
1299 return;
1301 /* Show all directories with more than x% of the changes */
1302 qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
1303 gather_dirstat(options->file, &dir, changed, "", 0);
1306 static void free_diffstat_info(struct diffstat_t *diffstat)
1308 int i;
1309 for (i = 0; i < diffstat->nr; i++) {
1310 struct diffstat_file *f = diffstat->files[i];
1311 if (f->name != f->print_name)
1312 free(f->print_name);
1313 free(f->name);
1314 free(f->from_name);
1315 free(f);
1317 free(diffstat->files);
1320 struct checkdiff_t {
1321 const char *filename;
1322 int lineno;
1323 struct diff_options *o;
1324 unsigned ws_rule;
1325 unsigned status;
1328 static int is_conflict_marker(const char *line, unsigned long len)
1330 char firstchar;
1331 int cnt;
1333 if (len < 8)
1334 return 0;
1335 firstchar = line[0];
1336 switch (firstchar) {
1337 case '=': case '>': case '<':
1338 break;
1339 default:
1340 return 0;
1342 for (cnt = 1; cnt < 7; cnt++)
1343 if (line[cnt] != firstchar)
1344 return 0;
1345 /* line[0] thru line[6] are same as firstchar */
1346 if (firstchar == '=') {
1347 /* divider between ours and theirs? */
1348 if (len != 8 || line[7] != '\n')
1349 return 0;
1350 } else if (len < 8 || !isspace(line[7])) {
1351 /* not divider before ours nor after theirs */
1352 return 0;
1354 return 1;
1357 static void checkdiff_consume(void *priv, char *line, unsigned long len)
1359 struct checkdiff_t *data = priv;
1360 int color_diff = DIFF_OPT_TST(data->o, COLOR_DIFF);
1361 const char *ws = diff_get_color(color_diff, DIFF_WHITESPACE);
1362 const char *reset = diff_get_color(color_diff, DIFF_RESET);
1363 const char *set = diff_get_color(color_diff, DIFF_FILE_NEW);
1364 char *err;
1366 if (line[0] == '+') {
1367 unsigned bad;
1368 data->lineno++;
1369 if (is_conflict_marker(line + 1, len - 1)) {
1370 data->status |= 1;
1371 fprintf(data->o->file,
1372 "%s:%d: leftover conflict marker\n",
1373 data->filename, data->lineno);
1375 bad = ws_check(line + 1, len - 1, data->ws_rule);
1376 if (!bad)
1377 return;
1378 data->status |= bad;
1379 err = whitespace_error_string(bad);
1380 fprintf(data->o->file, "%s:%d: %s.\n",
1381 data->filename, data->lineno, err);
1382 free(err);
1383 emit_line(data->o->file, set, reset, line, 1);
1384 ws_check_emit(line + 1, len - 1, data->ws_rule,
1385 data->o->file, set, reset, ws);
1386 } else if (line[0] == ' ') {
1387 data->lineno++;
1388 } else if (line[0] == '@') {
1389 char *plus = strchr(line, '+');
1390 if (plus)
1391 data->lineno = strtol(plus, NULL, 10) - 1;
1392 else
1393 die("invalid diff");
1397 static unsigned char *deflate_it(char *data,
1398 unsigned long size,
1399 unsigned long *result_size)
1401 int bound;
1402 unsigned char *deflated;
1403 z_stream stream;
1405 memset(&stream, 0, sizeof(stream));
1406 deflateInit(&stream, zlib_compression_level);
1407 bound = deflateBound(&stream, size);
1408 deflated = xmalloc(bound);
1409 stream.next_out = deflated;
1410 stream.avail_out = bound;
1412 stream.next_in = (unsigned char *)data;
1413 stream.avail_in = size;
1414 while (deflate(&stream, Z_FINISH) == Z_OK)
1415 ; /* nothing */
1416 deflateEnd(&stream);
1417 *result_size = stream.total_out;
1418 return deflated;
1421 static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two)
1423 void *cp;
1424 void *delta;
1425 void *deflated;
1426 void *data;
1427 unsigned long orig_size;
1428 unsigned long delta_size;
1429 unsigned long deflate_size;
1430 unsigned long data_size;
1432 /* We could do deflated delta, or we could do just deflated two,
1433 * whichever is smaller.
1435 delta = NULL;
1436 deflated = deflate_it(two->ptr, two->size, &deflate_size);
1437 if (one->size && two->size) {
1438 delta = diff_delta(one->ptr, one->size,
1439 two->ptr, two->size,
1440 &delta_size, deflate_size);
1441 if (delta) {
1442 void *to_free = delta;
1443 orig_size = delta_size;
1444 delta = deflate_it(delta, delta_size, &delta_size);
1445 free(to_free);
1449 if (delta && delta_size < deflate_size) {
1450 fprintf(file, "delta %lu\n", orig_size);
1451 free(deflated);
1452 data = delta;
1453 data_size = delta_size;
1455 else {
1456 fprintf(file, "literal %lu\n", two->size);
1457 free(delta);
1458 data = deflated;
1459 data_size = deflate_size;
1462 /* emit data encoded in base85 */
1463 cp = data;
1464 while (data_size) {
1465 int bytes = (52 < data_size) ? 52 : data_size;
1466 char line[70];
1467 data_size -= bytes;
1468 if (bytes <= 26)
1469 line[0] = bytes + 'A' - 1;
1470 else
1471 line[0] = bytes - 26 + 'a' - 1;
1472 encode_85(line + 1, cp, bytes);
1473 cp = (char *) cp + bytes;
1474 fputs(line, file);
1475 fputc('\n', file);
1477 fprintf(file, "\n");
1478 free(data);
1481 static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two)
1483 fprintf(file, "GIT binary patch\n");
1484 emit_binary_diff_body(file, one, two);
1485 emit_binary_diff_body(file, two, one);
1488 static void diff_filespec_load_driver(struct diff_filespec *one)
1490 if (!one->driver)
1491 one->driver = userdiff_find_by_path(one->path);
1492 if (!one->driver)
1493 one->driver = userdiff_find_by_name("default");
1496 int diff_filespec_is_binary(struct diff_filespec *one)
1498 if (one->is_binary == -1) {
1499 diff_filespec_load_driver(one);
1500 if (one->driver->binary != -1)
1501 one->is_binary = one->driver->binary;
1502 else {
1503 if (!one->data && DIFF_FILE_VALID(one))
1504 diff_populate_filespec(one, 0);
1505 if (one->data)
1506 one->is_binary = buffer_is_binary(one->data,
1507 one->size);
1508 if (one->is_binary == -1)
1509 one->is_binary = 0;
1512 return one->is_binary;
1515 static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
1517 diff_filespec_load_driver(one);
1518 return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
1521 static const char *userdiff_word_regex(struct diff_filespec *one)
1523 diff_filespec_load_driver(one);
1524 return one->driver->word_regex;
1527 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
1529 if (!options->a_prefix)
1530 options->a_prefix = a;
1531 if (!options->b_prefix)
1532 options->b_prefix = b;
1535 static const char *get_textconv(struct diff_filespec *one)
1537 if (!DIFF_FILE_VALID(one))
1538 return NULL;
1539 if (!S_ISREG(one->mode))
1540 return NULL;
1541 diff_filespec_load_driver(one);
1542 return one->driver->textconv;
1545 static void builtin_diff(const char *name_a,
1546 const char *name_b,
1547 struct diff_filespec *one,
1548 struct diff_filespec *two,
1549 const char *xfrm_msg,
1550 struct diff_options *o,
1551 int complete_rewrite)
1553 mmfile_t mf1, mf2;
1554 const char *lbl[2];
1555 char *a_one, *b_two;
1556 const char *set = diff_get_color_opt(o, DIFF_METAINFO);
1557 const char *reset = diff_get_color_opt(o, DIFF_RESET);
1558 const char *a_prefix, *b_prefix;
1559 const char *textconv_one = NULL, *textconv_two = NULL;
1561 if (DIFF_OPT_TST(o, SUMMARIZE_SUBMODULES) &&
1562 (!one->mode || S_ISGITLINK(one->mode)) &&
1563 (!two->mode || S_ISGITLINK(two->mode))) {
1564 const char *del = diff_get_color_opt(o, DIFF_FILE_OLD);
1565 const char *add = diff_get_color_opt(o, DIFF_FILE_NEW);
1566 show_submodule_summary(o->file, one ? one->path : two->path,
1567 one->sha1, two->sha1,
1568 del, add, reset);
1569 return;
1572 if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
1573 textconv_one = get_textconv(one);
1574 textconv_two = get_textconv(two);
1577 diff_set_mnemonic_prefix(o, "a/", "b/");
1578 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
1579 a_prefix = o->b_prefix;
1580 b_prefix = o->a_prefix;
1581 } else {
1582 a_prefix = o->a_prefix;
1583 b_prefix = o->b_prefix;
1586 /* Never use a non-valid filename anywhere if at all possible */
1587 name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
1588 name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
1590 a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
1591 b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
1592 lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1593 lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1594 fprintf(o->file, "%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
1595 if (lbl[0][0] == '/') {
1596 /* /dev/null */
1597 fprintf(o->file, "%snew file mode %06o%s\n", set, two->mode, reset);
1598 if (xfrm_msg && xfrm_msg[0])
1599 fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1601 else if (lbl[1][0] == '/') {
1602 fprintf(o->file, "%sdeleted file mode %06o%s\n", set, one->mode, reset);
1603 if (xfrm_msg && xfrm_msg[0])
1604 fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1606 else {
1607 if (one->mode != two->mode) {
1608 fprintf(o->file, "%sold mode %06o%s\n", set, one->mode, reset);
1609 fprintf(o->file, "%snew mode %06o%s\n", set, two->mode, reset);
1611 if (xfrm_msg && xfrm_msg[0])
1612 fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
1614 * we do not run diff between different kind
1615 * of objects.
1617 if ((one->mode ^ two->mode) & S_IFMT)
1618 goto free_ab_and_return;
1619 if (complete_rewrite &&
1620 (textconv_one || !diff_filespec_is_binary(one)) &&
1621 (textconv_two || !diff_filespec_is_binary(two))) {
1622 emit_rewrite_diff(name_a, name_b, one, two,
1623 textconv_one, textconv_two, o);
1624 o->found_changes = 1;
1625 goto free_ab_and_return;
1629 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1630 die("unable to read files to diff");
1632 if (!DIFF_OPT_TST(o, TEXT) &&
1633 ( (diff_filespec_is_binary(one) && !textconv_one) ||
1634 (diff_filespec_is_binary(two) && !textconv_two) )) {
1635 /* Quite common confusing case */
1636 if (mf1.size == mf2.size &&
1637 !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1638 goto free_ab_and_return;
1639 if (DIFF_OPT_TST(o, BINARY))
1640 emit_binary_diff(o->file, &mf1, &mf2);
1641 else
1642 fprintf(o->file, "Binary files %s and %s differ\n",
1643 lbl[0], lbl[1]);
1644 o->found_changes = 1;
1646 else {
1647 /* Crazy xdl interfaces.. */
1648 const char *diffopts = getenv("GIT_DIFF_OPTS");
1649 xpparam_t xpp;
1650 xdemitconf_t xecfg;
1651 xdemitcb_t ecb;
1652 struct emit_callback ecbdata;
1653 const struct userdiff_funcname *pe;
1655 if (textconv_one) {
1656 size_t size;
1657 mf1.ptr = run_textconv(textconv_one, one, &size);
1658 if (!mf1.ptr)
1659 die("unable to read files to diff");
1660 mf1.size = size;
1662 if (textconv_two) {
1663 size_t size;
1664 mf2.ptr = run_textconv(textconv_two, two, &size);
1665 if (!mf2.ptr)
1666 die("unable to read files to diff");
1667 mf2.size = size;
1670 pe = diff_funcname_pattern(one);
1671 if (!pe)
1672 pe = diff_funcname_pattern(two);
1674 memset(&xpp, 0, sizeof(xpp));
1675 memset(&xecfg, 0, sizeof(xecfg));
1676 memset(&ecbdata, 0, sizeof(ecbdata));
1677 ecbdata.label_path = lbl;
1678 ecbdata.color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
1679 ecbdata.found_changesp = &o->found_changes;
1680 ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
1681 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
1682 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1683 ecbdata.file = o->file;
1684 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1685 xecfg.ctxlen = o->context;
1686 xecfg.interhunkctxlen = o->interhunkcontext;
1687 xecfg.flags = XDL_EMIT_FUNCNAMES;
1688 if (pe)
1689 xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
1690 if (!diffopts)
1692 else if (!prefixcmp(diffopts, "--unified="))
1693 xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1694 else if (!prefixcmp(diffopts, "-u"))
1695 xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1696 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS)) {
1697 ecbdata.diff_words =
1698 xcalloc(1, sizeof(struct diff_words_data));
1699 ecbdata.diff_words->file = o->file;
1700 if (!o->word_regex)
1701 o->word_regex = userdiff_word_regex(one);
1702 if (!o->word_regex)
1703 o->word_regex = userdiff_word_regex(two);
1704 if (!o->word_regex)
1705 o->word_regex = diff_word_regex_cfg;
1706 if (o->word_regex) {
1707 ecbdata.diff_words->word_regex = (regex_t *)
1708 xmalloc(sizeof(regex_t));
1709 if (regcomp(ecbdata.diff_words->word_regex,
1710 o->word_regex,
1711 REG_EXTENDED | REG_NEWLINE))
1712 die ("Invalid regular expression: %s",
1713 o->word_regex);
1716 xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
1717 &xpp, &xecfg, &ecb);
1718 if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS))
1719 free_diff_words_data(&ecbdata);
1720 if (textconv_one)
1721 free(mf1.ptr);
1722 if (textconv_two)
1723 free(mf2.ptr);
1724 xdiff_clear_find_func(&xecfg);
1727 free_ab_and_return:
1728 diff_free_filespec_data(one);
1729 diff_free_filespec_data(two);
1730 free(a_one);
1731 free(b_two);
1732 return;
1735 static void builtin_diffstat(const char *name_a, const char *name_b,
1736 struct diff_filespec *one,
1737 struct diff_filespec *two,
1738 struct diffstat_t *diffstat,
1739 struct diff_options *o,
1740 int complete_rewrite)
1742 mmfile_t mf1, mf2;
1743 struct diffstat_file *data;
1745 data = diffstat_add(diffstat, name_a, name_b);
1747 if (!one || !two) {
1748 data->is_unmerged = 1;
1749 return;
1751 if (complete_rewrite) {
1752 diff_populate_filespec(one, 0);
1753 diff_populate_filespec(two, 0);
1754 data->deleted = count_lines(one->data, one->size);
1755 data->added = count_lines(two->data, two->size);
1756 goto free_and_return;
1758 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1759 die("unable to read files to diff");
1761 if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
1762 data->is_binary = 1;
1763 data->added = mf2.size;
1764 data->deleted = mf1.size;
1765 } else {
1766 /* Crazy xdl interfaces.. */
1767 xpparam_t xpp;
1768 xdemitconf_t xecfg;
1769 xdemitcb_t ecb;
1771 memset(&xpp, 0, sizeof(xpp));
1772 memset(&xecfg, 0, sizeof(xecfg));
1773 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1774 xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
1775 &xpp, &xecfg, &ecb);
1778 free_and_return:
1779 diff_free_filespec_data(one);
1780 diff_free_filespec_data(two);
1783 static void builtin_checkdiff(const char *name_a, const char *name_b,
1784 const char *attr_path,
1785 struct diff_filespec *one,
1786 struct diff_filespec *two,
1787 struct diff_options *o)
1789 mmfile_t mf1, mf2;
1790 struct checkdiff_t data;
1792 if (!two)
1793 return;
1795 memset(&data, 0, sizeof(data));
1796 data.filename = name_b ? name_b : name_a;
1797 data.lineno = 0;
1798 data.o = o;
1799 data.ws_rule = whitespace_rule(attr_path);
1801 if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1802 die("unable to read files to diff");
1805 * All the other codepaths check both sides, but not checking
1806 * the "old" side here is deliberate. We are checking the newly
1807 * introduced changes, and as long as the "new" side is text, we
1808 * can and should check what it introduces.
1810 if (diff_filespec_is_binary(two))
1811 goto free_and_return;
1812 else {
1813 /* Crazy xdl interfaces.. */
1814 xpparam_t xpp;
1815 xdemitconf_t xecfg;
1816 xdemitcb_t ecb;
1818 memset(&xpp, 0, sizeof(xpp));
1819 memset(&xecfg, 0, sizeof(xecfg));
1820 xecfg.ctxlen = 1; /* at least one context line */
1821 xpp.flags = XDF_NEED_MINIMAL;
1822 xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
1823 &xpp, &xecfg, &ecb);
1825 if (data.ws_rule & WS_BLANK_AT_EOF) {
1826 struct emit_callback ecbdata;
1827 int blank_at_eof;
1829 ecbdata.ws_rule = data.ws_rule;
1830 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1831 blank_at_eof = ecbdata.blank_at_eof_in_preimage;
1833 if (blank_at_eof) {
1834 static char *err;
1835 if (!err)
1836 err = whitespace_error_string(WS_BLANK_AT_EOF);
1837 fprintf(o->file, "%s:%d: %s.\n",
1838 data.filename, blank_at_eof, err);
1839 data.status = 1; /* report errors */
1843 free_and_return:
1844 diff_free_filespec_data(one);
1845 diff_free_filespec_data(two);
1846 if (data.status)
1847 DIFF_OPT_SET(o, CHECK_FAILED);
1850 struct diff_filespec *alloc_filespec(const char *path)
1852 int namelen = strlen(path);
1853 struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1855 memset(spec, 0, sizeof(*spec));
1856 spec->path = (char *)(spec + 1);
1857 memcpy(spec->path, path, namelen+1);
1858 spec->count = 1;
1859 spec->is_binary = -1;
1860 return spec;
1863 void free_filespec(struct diff_filespec *spec)
1865 if (!--spec->count) {
1866 diff_free_filespec_data(spec);
1867 free(spec);
1871 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1872 unsigned short mode)
1874 if (mode) {
1875 spec->mode = canon_mode(mode);
1876 hashcpy(spec->sha1, sha1);
1877 spec->sha1_valid = !is_null_sha1(sha1);
1882 * Given a name and sha1 pair, if the index tells us the file in
1883 * the work tree has that object contents, return true, so that
1884 * prepare_temp_file() does not have to inflate and extract.
1886 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
1888 struct cache_entry *ce;
1889 struct stat st;
1890 int pos, len;
1893 * We do not read the cache ourselves here, because the
1894 * benchmark with my previous version that always reads cache
1895 * shows that it makes things worse for diff-tree comparing
1896 * two linux-2.6 kernel trees in an already checked out work
1897 * tree. This is because most diff-tree comparisons deal with
1898 * only a small number of files, while reading the cache is
1899 * expensive for a large project, and its cost outweighs the
1900 * savings we get by not inflating the object to a temporary
1901 * file. Practically, this code only helps when we are used
1902 * by diff-cache --cached, which does read the cache before
1903 * calling us.
1905 if (!active_cache)
1906 return 0;
1908 /* We want to avoid the working directory if our caller
1909 * doesn't need the data in a normal file, this system
1910 * is rather slow with its stat/open/mmap/close syscalls,
1911 * and the object is contained in a pack file. The pack
1912 * is probably already open and will be faster to obtain
1913 * the data through than the working directory. Loose
1914 * objects however would tend to be slower as they need
1915 * to be individually opened and inflated.
1917 if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1))
1918 return 0;
1920 len = strlen(name);
1921 pos = cache_name_pos(name, len);
1922 if (pos < 0)
1923 return 0;
1924 ce = active_cache[pos];
1927 * This is not the sha1 we are looking for, or
1928 * unreusable because it is not a regular file.
1930 if (hashcmp(sha1, ce->sha1) || !S_ISREG(ce->ce_mode))
1931 return 0;
1934 * If ce is marked as "assume unchanged", there is no
1935 * guarantee that work tree matches what we are looking for.
1937 if (ce->ce_flags & CE_VALID)
1938 return 0;
1941 * If ce matches the file in the work tree, we can reuse it.
1943 if (ce_uptodate(ce) ||
1944 (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
1945 return 1;
1947 return 0;
1950 static int populate_from_stdin(struct diff_filespec *s)
1952 struct strbuf buf = STRBUF_INIT;
1953 size_t size = 0;
1955 if (strbuf_read(&buf, 0, 0) < 0)
1956 return error("error while reading from stdin %s",
1957 strerror(errno));
1959 s->should_munmap = 0;
1960 s->data = strbuf_detach(&buf, &size);
1961 s->size = size;
1962 s->should_free = 1;
1963 return 0;
1966 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
1968 int len;
1969 char *data = xmalloc(100);
1970 len = snprintf(data, 100,
1971 "Subproject commit %s\n", sha1_to_hex(s->sha1));
1972 s->data = data;
1973 s->size = len;
1974 s->should_free = 1;
1975 if (size_only) {
1976 s->data = NULL;
1977 free(data);
1979 return 0;
1983 * While doing rename detection and pickaxe operation, we may need to
1984 * grab the data for the blob (or file) for our own in-core comparison.
1985 * diff_filespec has data and size fields for this purpose.
1987 int diff_populate_filespec(struct diff_filespec *s, int size_only)
1989 int err = 0;
1990 if (!DIFF_FILE_VALID(s))
1991 die("internal error: asking to populate invalid file.");
1992 if (S_ISDIR(s->mode))
1993 return -1;
1995 if (s->data)
1996 return 0;
1998 if (size_only && 0 < s->size)
1999 return 0;
2001 if (S_ISGITLINK(s->mode))
2002 return diff_populate_gitlink(s, size_only);
2004 if (!s->sha1_valid ||
2005 reuse_worktree_file(s->path, s->sha1, 0)) {
2006 struct strbuf buf = STRBUF_INIT;
2007 struct stat st;
2008 int fd;
2010 if (!strcmp(s->path, "-"))
2011 return populate_from_stdin(s);
2013 if (lstat(s->path, &st) < 0) {
2014 if (errno == ENOENT) {
2015 err_empty:
2016 err = -1;
2017 empty:
2018 s->data = (char *)"";
2019 s->size = 0;
2020 return err;
2023 s->size = xsize_t(st.st_size);
2024 if (!s->size)
2025 goto empty;
2026 if (S_ISLNK(st.st_mode)) {
2027 struct strbuf sb = STRBUF_INIT;
2029 if (strbuf_readlink(&sb, s->path, s->size))
2030 goto err_empty;
2031 s->size = sb.len;
2032 s->data = strbuf_detach(&sb, NULL);
2033 s->should_free = 1;
2034 return 0;
2036 if (size_only)
2037 return 0;
2038 fd = open(s->path, O_RDONLY);
2039 if (fd < 0)
2040 goto err_empty;
2041 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
2042 close(fd);
2043 s->should_munmap = 1;
2046 * Convert from working tree format to canonical git format
2048 if (convert_to_git(s->path, s->data, s->size, &buf, safe_crlf)) {
2049 size_t size = 0;
2050 munmap(s->data, s->size);
2051 s->should_munmap = 0;
2052 s->data = strbuf_detach(&buf, &size);
2053 s->size = size;
2054 s->should_free = 1;
2057 else {
2058 enum object_type type;
2059 if (size_only)
2060 type = sha1_object_info(s->sha1, &s->size);
2061 else {
2062 s->data = read_sha1_file(s->sha1, &type, &s->size);
2063 s->should_free = 1;
2066 return 0;
2069 void diff_free_filespec_blob(struct diff_filespec *s)
2071 if (s->should_free)
2072 free(s->data);
2073 else if (s->should_munmap)
2074 munmap(s->data, s->size);
2076 if (s->should_free || s->should_munmap) {
2077 s->should_free = s->should_munmap = 0;
2078 s->data = NULL;
2082 void diff_free_filespec_data(struct diff_filespec *s)
2084 diff_free_filespec_blob(s);
2085 free(s->cnt_data);
2086 s->cnt_data = NULL;
2089 static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
2090 void *blob,
2091 unsigned long size,
2092 const unsigned char *sha1,
2093 int mode)
2095 int fd;
2096 struct strbuf buf = STRBUF_INIT;
2097 struct strbuf template = STRBUF_INIT;
2098 char *path_dup = xstrdup(path);
2099 const char *base = basename(path_dup);
2101 /* Generate "XXXXXX_basename.ext" */
2102 strbuf_addstr(&template, "XXXXXX_");
2103 strbuf_addstr(&template, base);
2105 fd = git_mkstemps(temp->tmp_path, PATH_MAX, template.buf,
2106 strlen(base) + 1);
2107 if (fd < 0)
2108 die_errno("unable to create temp-file");
2109 if (convert_to_working_tree(path,
2110 (const char *)blob, (size_t)size, &buf)) {
2111 blob = buf.buf;
2112 size = buf.len;
2114 if (write_in_full(fd, blob, size) != size)
2115 die_errno("unable to write temp-file");
2116 close(fd);
2117 temp->name = temp->tmp_path;
2118 strcpy(temp->hex, sha1_to_hex(sha1));
2119 temp->hex[40] = 0;
2120 sprintf(temp->mode, "%06o", mode);
2121 strbuf_release(&buf);
2122 strbuf_release(&template);
2123 free(path_dup);
2126 static struct diff_tempfile *prepare_temp_file(const char *name,
2127 struct diff_filespec *one)
2129 struct diff_tempfile *temp = claim_diff_tempfile();
2131 if (!DIFF_FILE_VALID(one)) {
2132 not_a_valid_file:
2133 /* A '-' entry produces this for file-2, and
2134 * a '+' entry produces this for file-1.
2136 temp->name = "/dev/null";
2137 strcpy(temp->hex, ".");
2138 strcpy(temp->mode, ".");
2139 return temp;
2142 if (!remove_tempfile_installed) {
2143 atexit(remove_tempfile);
2144 sigchain_push_common(remove_tempfile_on_signal);
2145 remove_tempfile_installed = 1;
2148 if (!one->sha1_valid ||
2149 reuse_worktree_file(name, one->sha1, 1)) {
2150 struct stat st;
2151 if (lstat(name, &st) < 0) {
2152 if (errno == ENOENT)
2153 goto not_a_valid_file;
2154 die_errno("stat(%s)", name);
2156 if (S_ISLNK(st.st_mode)) {
2157 struct strbuf sb = STRBUF_INIT;
2158 if (strbuf_readlink(&sb, name, st.st_size) < 0)
2159 die_errno("readlink(%s)", name);
2160 prep_temp_blob(name, temp, sb.buf, sb.len,
2161 (one->sha1_valid ?
2162 one->sha1 : null_sha1),
2163 (one->sha1_valid ?
2164 one->mode : S_IFLNK));
2165 strbuf_release(&sb);
2167 else {
2168 /* we can borrow from the file in the work tree */
2169 temp->name = name;
2170 if (!one->sha1_valid)
2171 strcpy(temp->hex, sha1_to_hex(null_sha1));
2172 else
2173 strcpy(temp->hex, sha1_to_hex(one->sha1));
2174 /* Even though we may sometimes borrow the
2175 * contents from the work tree, we always want
2176 * one->mode. mode is trustworthy even when
2177 * !(one->sha1_valid), as long as
2178 * DIFF_FILE_VALID(one).
2180 sprintf(temp->mode, "%06o", one->mode);
2182 return temp;
2184 else {
2185 if (diff_populate_filespec(one, 0))
2186 die("cannot read data blob for %s", one->path);
2187 prep_temp_blob(name, temp, one->data, one->size,
2188 one->sha1, one->mode);
2190 return temp;
2193 /* An external diff command takes:
2195 * diff-cmd name infile1 infile1-sha1 infile1-mode \
2196 * infile2 infile2-sha1 infile2-mode [ rename-to ]
2199 static void run_external_diff(const char *pgm,
2200 const char *name,
2201 const char *other,
2202 struct diff_filespec *one,
2203 struct diff_filespec *two,
2204 const char *xfrm_msg,
2205 int complete_rewrite)
2207 const char *spawn_arg[10];
2208 int retval;
2209 const char **arg = &spawn_arg[0];
2211 if (one && two) {
2212 struct diff_tempfile *temp_one, *temp_two;
2213 const char *othername = (other ? other : name);
2214 temp_one = prepare_temp_file(name, one);
2215 temp_two = prepare_temp_file(othername, two);
2216 *arg++ = pgm;
2217 *arg++ = name;
2218 *arg++ = temp_one->name;
2219 *arg++ = temp_one->hex;
2220 *arg++ = temp_one->mode;
2221 *arg++ = temp_two->name;
2222 *arg++ = temp_two->hex;
2223 *arg++ = temp_two->mode;
2224 if (other) {
2225 *arg++ = other;
2226 *arg++ = xfrm_msg;
2228 } else {
2229 *arg++ = pgm;
2230 *arg++ = name;
2232 *arg = NULL;
2233 fflush(NULL);
2234 retval = run_command_v_opt(spawn_arg, 0);
2235 remove_tempfile();
2236 if (retval) {
2237 fprintf(stderr, "external diff died, stopping at %s.\n", name);
2238 exit(1);
2242 static int similarity_index(struct diff_filepair *p)
2244 return p->score * 100 / MAX_SCORE;
2247 static void fill_metainfo(struct strbuf *msg,
2248 const char *name,
2249 const char *other,
2250 struct diff_filespec *one,
2251 struct diff_filespec *two,
2252 struct diff_options *o,
2253 struct diff_filepair *p)
2255 strbuf_init(msg, PATH_MAX * 2 + 300);
2256 switch (p->status) {
2257 case DIFF_STATUS_COPIED:
2258 strbuf_addf(msg, "similarity index %d%%", similarity_index(p));
2259 strbuf_addstr(msg, "\ncopy from ");
2260 quote_c_style(name, msg, NULL, 0);
2261 strbuf_addstr(msg, "\ncopy to ");
2262 quote_c_style(other, msg, NULL, 0);
2263 strbuf_addch(msg, '\n');
2264 break;
2265 case DIFF_STATUS_RENAMED:
2266 strbuf_addf(msg, "similarity index %d%%", similarity_index(p));
2267 strbuf_addstr(msg, "\nrename from ");
2268 quote_c_style(name, msg, NULL, 0);
2269 strbuf_addstr(msg, "\nrename to ");
2270 quote_c_style(other, msg, NULL, 0);
2271 strbuf_addch(msg, '\n');
2272 break;
2273 case DIFF_STATUS_MODIFIED:
2274 if (p->score) {
2275 strbuf_addf(msg, "dissimilarity index %d%%\n",
2276 similarity_index(p));
2277 break;
2279 /* fallthru */
2280 default:
2281 /* nothing */
2284 if (one && two && hashcmp(one->sha1, two->sha1)) {
2285 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
2287 if (DIFF_OPT_TST(o, BINARY)) {
2288 mmfile_t mf;
2289 if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
2290 (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
2291 abbrev = 40;
2293 strbuf_addf(msg, "index %.*s..%.*s",
2294 abbrev, sha1_to_hex(one->sha1),
2295 abbrev, sha1_to_hex(two->sha1));
2296 if (one->mode == two->mode)
2297 strbuf_addf(msg, " %06o", one->mode);
2298 strbuf_addch(msg, '\n');
2300 if (msg->len)
2301 strbuf_setlen(msg, msg->len - 1);
2304 static void run_diff_cmd(const char *pgm,
2305 const char *name,
2306 const char *other,
2307 const char *attr_path,
2308 struct diff_filespec *one,
2309 struct diff_filespec *two,
2310 struct strbuf *msg,
2311 struct diff_options *o,
2312 struct diff_filepair *p)
2314 const char *xfrm_msg = NULL;
2315 int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
2317 if (msg) {
2318 fill_metainfo(msg, name, other, one, two, o, p);
2319 xfrm_msg = msg->len ? msg->buf : NULL;
2322 if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
2323 pgm = NULL;
2324 else {
2325 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
2326 if (drv && drv->external)
2327 pgm = drv->external;
2330 if (pgm) {
2331 run_external_diff(pgm, name, other, one, two, xfrm_msg,
2332 complete_rewrite);
2333 return;
2335 if (one && two)
2336 builtin_diff(name, other ? other : name,
2337 one, two, xfrm_msg, o, complete_rewrite);
2338 else
2339 fprintf(o->file, "* Unmerged path %s\n", name);
2342 static void diff_fill_sha1_info(struct diff_filespec *one)
2344 if (DIFF_FILE_VALID(one)) {
2345 if (!one->sha1_valid) {
2346 struct stat st;
2347 if (!strcmp(one->path, "-")) {
2348 hashcpy(one->sha1, null_sha1);
2349 return;
2351 if (lstat(one->path, &st) < 0)
2352 die_errno("stat '%s'", one->path);
2353 if (index_path(one->sha1, one->path, &st, 0))
2354 die("cannot hash %s", one->path);
2357 else
2358 hashclr(one->sha1);
2361 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
2363 /* Strip the prefix but do not molest /dev/null and absolute paths */
2364 if (*namep && **namep != '/')
2365 *namep += prefix_length;
2366 if (*otherp && **otherp != '/')
2367 *otherp += prefix_length;
2370 static void run_diff(struct diff_filepair *p, struct diff_options *o)
2372 const char *pgm = external_diff();
2373 struct strbuf msg;
2374 struct diff_filespec *one = p->one;
2375 struct diff_filespec *two = p->two;
2376 const char *name;
2377 const char *other;
2378 const char *attr_path;
2380 name = p->one->path;
2381 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2382 attr_path = name;
2383 if (o->prefix_length)
2384 strip_prefix(o->prefix_length, &name, &other);
2386 if (DIFF_PAIR_UNMERGED(p)) {
2387 run_diff_cmd(pgm, name, NULL, attr_path,
2388 NULL, NULL, NULL, o, p);
2389 return;
2392 diff_fill_sha1_info(one);
2393 diff_fill_sha1_info(two);
2395 if (!pgm &&
2396 DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
2397 (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
2399 * a filepair that changes between file and symlink
2400 * needs to be split into deletion and creation.
2402 struct diff_filespec *null = alloc_filespec(two->path);
2403 run_diff_cmd(NULL, name, other, attr_path,
2404 one, null, &msg, o, p);
2405 free(null);
2406 strbuf_release(&msg);
2408 null = alloc_filespec(one->path);
2409 run_diff_cmd(NULL, name, other, attr_path,
2410 null, two, &msg, o, p);
2411 free(null);
2413 else
2414 run_diff_cmd(pgm, name, other, attr_path,
2415 one, two, &msg, o, p);
2417 strbuf_release(&msg);
2420 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
2421 struct diffstat_t *diffstat)
2423 const char *name;
2424 const char *other;
2425 int complete_rewrite = 0;
2427 if (DIFF_PAIR_UNMERGED(p)) {
2428 /* unmerged */
2429 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
2430 return;
2433 name = p->one->path;
2434 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2436 if (o->prefix_length)
2437 strip_prefix(o->prefix_length, &name, &other);
2439 diff_fill_sha1_info(p->one);
2440 diff_fill_sha1_info(p->two);
2442 if (p->status == DIFF_STATUS_MODIFIED && p->score)
2443 complete_rewrite = 1;
2444 builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
2447 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
2449 const char *name;
2450 const char *other;
2451 const char *attr_path;
2453 if (DIFF_PAIR_UNMERGED(p)) {
2454 /* unmerged */
2455 return;
2458 name = p->one->path;
2459 other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2460 attr_path = other ? other : name;
2462 if (o->prefix_length)
2463 strip_prefix(o->prefix_length, &name, &other);
2465 diff_fill_sha1_info(p->one);
2466 diff_fill_sha1_info(p->two);
2468 builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
2471 void diff_setup(struct diff_options *options)
2473 memset(options, 0, sizeof(*options));
2475 options->file = stdout;
2477 options->line_termination = '\n';
2478 options->break_opt = -1;
2479 options->rename_limit = -1;
2480 options->dirstat_percent = 3;
2481 options->context = 3;
2483 options->change = diff_change;
2484 options->add_remove = diff_addremove;
2485 if (diff_use_color_default > 0)
2486 DIFF_OPT_SET(options, COLOR_DIFF);
2487 options->detect_rename = diff_detect_rename_default;
2489 if (!diff_mnemonic_prefix) {
2490 options->a_prefix = "a/";
2491 options->b_prefix = "b/";
2495 int diff_setup_done(struct diff_options *options)
2497 int count = 0;
2499 if (options->output_format & DIFF_FORMAT_NAME)
2500 count++;
2501 if (options->output_format & DIFF_FORMAT_NAME_STATUS)
2502 count++;
2503 if (options->output_format & DIFF_FORMAT_CHECKDIFF)
2504 count++;
2505 if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
2506 count++;
2507 if (count > 1)
2508 die("--name-only, --name-status, --check and -s are mutually exclusive");
2511 * Most of the time we can say "there are changes"
2512 * only by checking if there are changed paths, but
2513 * --ignore-whitespace* options force us to look
2514 * inside contents.
2517 if (DIFF_XDL_TST(options, IGNORE_WHITESPACE) ||
2518 DIFF_XDL_TST(options, IGNORE_WHITESPACE_CHANGE) ||
2519 DIFF_XDL_TST(options, IGNORE_WHITESPACE_AT_EOL))
2520 DIFF_OPT_SET(options, DIFF_FROM_CONTENTS);
2521 else
2522 DIFF_OPT_CLR(options, DIFF_FROM_CONTENTS);
2524 if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
2525 options->detect_rename = DIFF_DETECT_COPY;
2527 if (!DIFF_OPT_TST(options, RELATIVE_NAME))
2528 options->prefix = NULL;
2529 if (options->prefix)
2530 options->prefix_length = strlen(options->prefix);
2531 else
2532 options->prefix_length = 0;
2534 if (options->output_format & (DIFF_FORMAT_NAME |
2535 DIFF_FORMAT_NAME_STATUS |
2536 DIFF_FORMAT_CHECKDIFF |
2537 DIFF_FORMAT_NO_OUTPUT))
2538 options->output_format &= ~(DIFF_FORMAT_RAW |
2539 DIFF_FORMAT_NUMSTAT |
2540 DIFF_FORMAT_DIFFSTAT |
2541 DIFF_FORMAT_SHORTSTAT |
2542 DIFF_FORMAT_DIRSTAT |
2543 DIFF_FORMAT_SUMMARY |
2544 DIFF_FORMAT_PATCH);
2547 * These cases always need recursive; we do not drop caller-supplied
2548 * recursive bits for other formats here.
2550 if (options->output_format & (DIFF_FORMAT_PATCH |
2551 DIFF_FORMAT_NUMSTAT |
2552 DIFF_FORMAT_DIFFSTAT |
2553 DIFF_FORMAT_SHORTSTAT |
2554 DIFF_FORMAT_DIRSTAT |
2555 DIFF_FORMAT_SUMMARY |
2556 DIFF_FORMAT_CHECKDIFF))
2557 DIFF_OPT_SET(options, RECURSIVE);
2559 * Also pickaxe would not work very well if you do not say recursive
2561 if (options->pickaxe)
2562 DIFF_OPT_SET(options, RECURSIVE);
2564 if (options->detect_rename && options->rename_limit < 0)
2565 options->rename_limit = diff_rename_limit_default;
2566 if (options->setup & DIFF_SETUP_USE_CACHE) {
2567 if (!active_cache)
2568 /* read-cache does not die even when it fails
2569 * so it is safe for us to do this here. Also
2570 * it does not smudge active_cache or active_nr
2571 * when it fails, so we do not have to worry about
2572 * cleaning it up ourselves either.
2574 read_cache();
2576 if (options->abbrev <= 0 || 40 < options->abbrev)
2577 options->abbrev = 40; /* full */
2580 * It does not make sense to show the first hit we happened
2581 * to have found. It does not make sense not to return with
2582 * exit code in such a case either.
2584 if (DIFF_OPT_TST(options, QUICK)) {
2585 options->output_format = DIFF_FORMAT_NO_OUTPUT;
2586 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2589 return 0;
2592 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
2594 char c, *eq;
2595 int len;
2597 if (*arg != '-')
2598 return 0;
2599 c = *++arg;
2600 if (!c)
2601 return 0;
2602 if (c == arg_short) {
2603 c = *++arg;
2604 if (!c)
2605 return 1;
2606 if (val && isdigit(c)) {
2607 char *end;
2608 int n = strtoul(arg, &end, 10);
2609 if (*end)
2610 return 0;
2611 *val = n;
2612 return 1;
2614 return 0;
2616 if (c != '-')
2617 return 0;
2618 arg++;
2619 eq = strchr(arg, '=');
2620 if (eq)
2621 len = eq - arg;
2622 else
2623 len = strlen(arg);
2624 if (!len || strncmp(arg, arg_long, len))
2625 return 0;
2626 if (eq) {
2627 int n;
2628 char *end;
2629 if (!isdigit(*++eq))
2630 return 0;
2631 n = strtoul(eq, &end, 10);
2632 if (*end)
2633 return 0;
2634 *val = n;
2636 return 1;
2639 static int diff_scoreopt_parse(const char *opt);
2641 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
2643 const char *arg = av[0];
2645 /* Output format options */
2646 if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
2647 options->output_format |= DIFF_FORMAT_PATCH;
2648 else if (opt_arg(arg, 'U', "unified", &options->context))
2649 options->output_format |= DIFF_FORMAT_PATCH;
2650 else if (!strcmp(arg, "--raw"))
2651 options->output_format |= DIFF_FORMAT_RAW;
2652 else if (!strcmp(arg, "--patch-with-raw"))
2653 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
2654 else if (!strcmp(arg, "--numstat"))
2655 options->output_format |= DIFF_FORMAT_NUMSTAT;
2656 else if (!strcmp(arg, "--shortstat"))
2657 options->output_format |= DIFF_FORMAT_SHORTSTAT;
2658 else if (opt_arg(arg, 'X', "dirstat", &options->dirstat_percent))
2659 options->output_format |= DIFF_FORMAT_DIRSTAT;
2660 else if (!strcmp(arg, "--cumulative")) {
2661 options->output_format |= DIFF_FORMAT_DIRSTAT;
2662 DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
2663 } else if (opt_arg(arg, 0, "dirstat-by-file",
2664 &options->dirstat_percent)) {
2665 options->output_format |= DIFF_FORMAT_DIRSTAT;
2666 DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
2668 else if (!strcmp(arg, "--check"))
2669 options->output_format |= DIFF_FORMAT_CHECKDIFF;
2670 else if (!strcmp(arg, "--summary"))
2671 options->output_format |= DIFF_FORMAT_SUMMARY;
2672 else if (!strcmp(arg, "--patch-with-stat"))
2673 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2674 else if (!strcmp(arg, "--name-only"))
2675 options->output_format |= DIFF_FORMAT_NAME;
2676 else if (!strcmp(arg, "--name-status"))
2677 options->output_format |= DIFF_FORMAT_NAME_STATUS;
2678 else if (!strcmp(arg, "-s"))
2679 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
2680 else if (!prefixcmp(arg, "--stat")) {
2681 char *end;
2682 int width = options->stat_width;
2683 int name_width = options->stat_name_width;
2684 arg += 6;
2685 end = (char *)arg;
2687 switch (*arg) {
2688 case '-':
2689 if (!prefixcmp(arg, "-width="))
2690 width = strtoul(arg + 7, &end, 10);
2691 else if (!prefixcmp(arg, "-name-width="))
2692 name_width = strtoul(arg + 12, &end, 10);
2693 break;
2694 case '=':
2695 width = strtoul(arg+1, &end, 10);
2696 if (*end == ',')
2697 name_width = strtoul(end+1, &end, 10);
2700 /* Important! This checks all the error cases! */
2701 if (*end)
2702 return 0;
2703 options->output_format |= DIFF_FORMAT_DIFFSTAT;
2704 options->stat_name_width = name_width;
2705 options->stat_width = width;
2708 /* renames options */
2709 else if (!prefixcmp(arg, "-B")) {
2710 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
2711 return -1;
2713 else if (!prefixcmp(arg, "-M")) {
2714 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2715 return -1;
2716 options->detect_rename = DIFF_DETECT_RENAME;
2718 else if (!prefixcmp(arg, "-C")) {
2719 if (options->detect_rename == DIFF_DETECT_COPY)
2720 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2721 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2722 return -1;
2723 options->detect_rename = DIFF_DETECT_COPY;
2725 else if (!strcmp(arg, "--no-renames"))
2726 options->detect_rename = 0;
2727 else if (!strcmp(arg, "--relative"))
2728 DIFF_OPT_SET(options, RELATIVE_NAME);
2729 else if (!prefixcmp(arg, "--relative=")) {
2730 DIFF_OPT_SET(options, RELATIVE_NAME);
2731 options->prefix = arg + 11;
2734 /* xdiff options */
2735 else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2736 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
2737 else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2738 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
2739 else if (!strcmp(arg, "--ignore-space-at-eol"))
2740 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
2741 else if (!strcmp(arg, "--patience"))
2742 DIFF_XDL_SET(options, PATIENCE_DIFF);
2744 /* flags options */
2745 else if (!strcmp(arg, "--binary")) {
2746 options->output_format |= DIFF_FORMAT_PATCH;
2747 DIFF_OPT_SET(options, BINARY);
2749 else if (!strcmp(arg, "--full-index"))
2750 DIFF_OPT_SET(options, FULL_INDEX);
2751 else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
2752 DIFF_OPT_SET(options, TEXT);
2753 else if (!strcmp(arg, "-R"))
2754 DIFF_OPT_SET(options, REVERSE_DIFF);
2755 else if (!strcmp(arg, "--find-copies-harder"))
2756 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2757 else if (!strcmp(arg, "--follow"))
2758 DIFF_OPT_SET(options, FOLLOW_RENAMES);
2759 else if (!strcmp(arg, "--color"))
2760 DIFF_OPT_SET(options, COLOR_DIFF);
2761 else if (!strcmp(arg, "--no-color"))
2762 DIFF_OPT_CLR(options, COLOR_DIFF);
2763 else if (!strcmp(arg, "--color-words")) {
2764 DIFF_OPT_SET(options, COLOR_DIFF);
2765 DIFF_OPT_SET(options, COLOR_DIFF_WORDS);
2767 else if (!prefixcmp(arg, "--color-words=")) {
2768 DIFF_OPT_SET(options, COLOR_DIFF);
2769 DIFF_OPT_SET(options, COLOR_DIFF_WORDS);
2770 options->word_regex = arg + 14;
2772 else if (!strcmp(arg, "--exit-code"))
2773 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2774 else if (!strcmp(arg, "--quiet"))
2775 DIFF_OPT_SET(options, QUICK);
2776 else if (!strcmp(arg, "--ext-diff"))
2777 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
2778 else if (!strcmp(arg, "--no-ext-diff"))
2779 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
2780 else if (!strcmp(arg, "--textconv"))
2781 DIFF_OPT_SET(options, ALLOW_TEXTCONV);
2782 else if (!strcmp(arg, "--no-textconv"))
2783 DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
2784 else if (!strcmp(arg, "--ignore-submodules"))
2785 DIFF_OPT_SET(options, IGNORE_SUBMODULES);
2786 else if (!strcmp(arg, "--submodule-summary"))
2787 DIFF_OPT_SET(options, SUMMARIZE_SUBMODULES);
2789 /* misc options */
2790 else if (!strcmp(arg, "-z"))
2791 options->line_termination = 0;
2792 else if (!prefixcmp(arg, "-l"))
2793 options->rename_limit = strtoul(arg+2, NULL, 10);
2794 else if (!prefixcmp(arg, "-S"))
2795 options->pickaxe = arg + 2;
2796 else if (!strcmp(arg, "--pickaxe-all"))
2797 options->pickaxe_opts = DIFF_PICKAXE_ALL;
2798 else if (!strcmp(arg, "--pickaxe-regex"))
2799 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2800 else if (!prefixcmp(arg, "-O"))
2801 options->orderfile = arg + 2;
2802 else if (!prefixcmp(arg, "--diff-filter="))
2803 options->filter = arg + 14;
2804 else if (!strcmp(arg, "--abbrev"))
2805 options->abbrev = DEFAULT_ABBREV;
2806 else if (!prefixcmp(arg, "--abbrev=")) {
2807 options->abbrev = strtoul(arg + 9, NULL, 10);
2808 if (options->abbrev < MINIMUM_ABBREV)
2809 options->abbrev = MINIMUM_ABBREV;
2810 else if (40 < options->abbrev)
2811 options->abbrev = 40;
2813 else if (!prefixcmp(arg, "--src-prefix="))
2814 options->a_prefix = arg + 13;
2815 else if (!prefixcmp(arg, "--dst-prefix="))
2816 options->b_prefix = arg + 13;
2817 else if (!strcmp(arg, "--no-prefix"))
2818 options->a_prefix = options->b_prefix = "";
2819 else if (opt_arg(arg, '\0', "inter-hunk-context",
2820 &options->interhunkcontext))
2822 else if (!prefixcmp(arg, "--output=")) {
2823 options->file = fopen(arg + strlen("--output="), "w");
2824 options->close_file = 1;
2825 } else
2826 return 0;
2827 return 1;
2830 static int parse_num(const char **cp_p)
2832 unsigned long num, scale;
2833 int ch, dot;
2834 const char *cp = *cp_p;
2836 num = 0;
2837 scale = 1;
2838 dot = 0;
2839 for (;;) {
2840 ch = *cp;
2841 if ( !dot && ch == '.' ) {
2842 scale = 1;
2843 dot = 1;
2844 } else if ( ch == '%' ) {
2845 scale = dot ? scale*100 : 100;
2846 cp++; /* % is always at the end */
2847 break;
2848 } else if ( ch >= '0' && ch <= '9' ) {
2849 if ( scale < 100000 ) {
2850 scale *= 10;
2851 num = (num*10) + (ch-'0');
2853 } else {
2854 break;
2856 cp++;
2858 *cp_p = cp;
2860 /* user says num divided by scale and we say internally that
2861 * is MAX_SCORE * num / scale.
2863 return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
2866 static int diff_scoreopt_parse(const char *opt)
2868 int opt1, opt2, cmd;
2870 if (*opt++ != '-')
2871 return -1;
2872 cmd = *opt++;
2873 if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2874 return -1; /* that is not a -M, -C nor -B option */
2876 opt1 = parse_num(&opt);
2877 if (cmd != 'B')
2878 opt2 = 0;
2879 else {
2880 if (*opt == 0)
2881 opt2 = 0;
2882 else if (*opt != '/')
2883 return -1; /* we expect -B80/99 or -B80 */
2884 else {
2885 opt++;
2886 opt2 = parse_num(&opt);
2889 if (*opt != 0)
2890 return -1;
2891 return opt1 | (opt2 << 16);
2894 struct diff_queue_struct diff_queued_diff;
2896 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2898 if (queue->alloc <= queue->nr) {
2899 queue->alloc = alloc_nr(queue->alloc);
2900 queue->queue = xrealloc(queue->queue,
2901 sizeof(dp) * queue->alloc);
2903 queue->queue[queue->nr++] = dp;
2906 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2907 struct diff_filespec *one,
2908 struct diff_filespec *two)
2910 struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
2911 dp->one = one;
2912 dp->two = two;
2913 if (queue)
2914 diff_q(queue, dp);
2915 return dp;
2918 void diff_free_filepair(struct diff_filepair *p)
2920 free_filespec(p->one);
2921 free_filespec(p->two);
2922 free(p);
2925 /* This is different from find_unique_abbrev() in that
2926 * it stuffs the result with dots for alignment.
2928 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
2930 int abblen;
2931 const char *abbrev;
2932 if (len == 40)
2933 return sha1_to_hex(sha1);
2935 abbrev = find_unique_abbrev(sha1, len);
2936 abblen = strlen(abbrev);
2937 if (abblen < 37) {
2938 static char hex[41];
2939 if (len < abblen && abblen <= len + 2)
2940 sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
2941 else
2942 sprintf(hex, "%s...", abbrev);
2943 return hex;
2945 return sha1_to_hex(sha1);
2948 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
2950 int line_termination = opt->line_termination;
2951 int inter_name_termination = line_termination ? '\t' : '\0';
2953 if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
2954 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
2955 diff_unique_abbrev(p->one->sha1, opt->abbrev));
2956 fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
2958 if (p->score) {
2959 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
2960 inter_name_termination);
2961 } else {
2962 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
2965 if (p->status == DIFF_STATUS_COPIED ||
2966 p->status == DIFF_STATUS_RENAMED) {
2967 const char *name_a, *name_b;
2968 name_a = p->one->path;
2969 name_b = p->two->path;
2970 strip_prefix(opt->prefix_length, &name_a, &name_b);
2971 write_name_quoted(name_a, opt->file, inter_name_termination);
2972 write_name_quoted(name_b, opt->file, line_termination);
2973 } else {
2974 const char *name_a, *name_b;
2975 name_a = p->one->mode ? p->one->path : p->two->path;
2976 name_b = NULL;
2977 strip_prefix(opt->prefix_length, &name_a, &name_b);
2978 write_name_quoted(name_a, opt->file, line_termination);
2982 int diff_unmodified_pair(struct diff_filepair *p)
2984 /* This function is written stricter than necessary to support
2985 * the currently implemented transformers, but the idea is to
2986 * let transformers to produce diff_filepairs any way they want,
2987 * and filter and clean them up here before producing the output.
2989 struct diff_filespec *one = p->one, *two = p->two;
2991 if (DIFF_PAIR_UNMERGED(p))
2992 return 0; /* unmerged is interesting */
2994 /* deletion, addition, mode or type change
2995 * and rename are all interesting.
2997 if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
2998 DIFF_PAIR_MODE_CHANGED(p) ||
2999 strcmp(one->path, two->path))
3000 return 0;
3002 /* both are valid and point at the same path. that is, we are
3003 * dealing with a change.
3005 if (one->sha1_valid && two->sha1_valid &&
3006 !hashcmp(one->sha1, two->sha1))
3007 return 1; /* no change */
3008 if (!one->sha1_valid && !two->sha1_valid)
3009 return 1; /* both look at the same file on the filesystem. */
3010 return 0;
3013 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
3015 if (diff_unmodified_pair(p))
3016 return;
3018 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3019 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3020 return; /* no tree diffs in patch format */
3022 run_diff(p, o);
3025 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
3026 struct diffstat_t *diffstat)
3028 if (diff_unmodified_pair(p))
3029 return;
3031 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3032 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3033 return; /* no tree diffs in patch format */
3035 run_diffstat(p, o, diffstat);
3038 static void diff_flush_checkdiff(struct diff_filepair *p,
3039 struct diff_options *o)
3041 if (diff_unmodified_pair(p))
3042 return;
3044 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3045 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3046 return; /* no tree diffs in patch format */
3048 run_checkdiff(p, o);
3051 int diff_queue_is_empty(void)
3053 struct diff_queue_struct *q = &diff_queued_diff;
3054 int i;
3055 for (i = 0; i < q->nr; i++)
3056 if (!diff_unmodified_pair(q->queue[i]))
3057 return 0;
3058 return 1;
3061 #if DIFF_DEBUG
3062 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
3064 fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
3065 x, one ? one : "",
3066 s->path,
3067 DIFF_FILE_VALID(s) ? "valid" : "invalid",
3068 s->mode,
3069 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
3070 fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
3071 x, one ? one : "",
3072 s->size, s->xfrm_flags);
3075 void diff_debug_filepair(const struct diff_filepair *p, int i)
3077 diff_debug_filespec(p->one, i, "one");
3078 diff_debug_filespec(p->two, i, "two");
3079 fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
3080 p->score, p->status ? p->status : '?',
3081 p->one->rename_used, p->broken_pair);
3084 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
3086 int i;
3087 if (msg)
3088 fprintf(stderr, "%s\n", msg);
3089 fprintf(stderr, "q->nr = %d\n", q->nr);
3090 for (i = 0; i < q->nr; i++) {
3091 struct diff_filepair *p = q->queue[i];
3092 diff_debug_filepair(p, i);
3095 #endif
3097 static void diff_resolve_rename_copy(void)
3099 int i;
3100 struct diff_filepair *p;
3101 struct diff_queue_struct *q = &diff_queued_diff;
3103 diff_debug_queue("resolve-rename-copy", q);
3105 for (i = 0; i < q->nr; i++) {
3106 p = q->queue[i];
3107 p->status = 0; /* undecided */
3108 if (DIFF_PAIR_UNMERGED(p))
3109 p->status = DIFF_STATUS_UNMERGED;
3110 else if (!DIFF_FILE_VALID(p->one))
3111 p->status = DIFF_STATUS_ADDED;
3112 else if (!DIFF_FILE_VALID(p->two))
3113 p->status = DIFF_STATUS_DELETED;
3114 else if (DIFF_PAIR_TYPE_CHANGED(p))
3115 p->status = DIFF_STATUS_TYPE_CHANGED;
3117 /* from this point on, we are dealing with a pair
3118 * whose both sides are valid and of the same type, i.e.
3119 * either in-place edit or rename/copy edit.
3121 else if (DIFF_PAIR_RENAME(p)) {
3123 * A rename might have re-connected a broken
3124 * pair up, causing the pathnames to be the
3125 * same again. If so, that's not a rename at
3126 * all, just a modification..
3128 * Otherwise, see if this source was used for
3129 * multiple renames, in which case we decrement
3130 * the count, and call it a copy.
3132 if (!strcmp(p->one->path, p->two->path))
3133 p->status = DIFF_STATUS_MODIFIED;
3134 else if (--p->one->rename_used > 0)
3135 p->status = DIFF_STATUS_COPIED;
3136 else
3137 p->status = DIFF_STATUS_RENAMED;
3139 else if (hashcmp(p->one->sha1, p->two->sha1) ||
3140 p->one->mode != p->two->mode ||
3141 is_null_sha1(p->one->sha1))
3142 p->status = DIFF_STATUS_MODIFIED;
3143 else {
3144 /* This is a "no-change" entry and should not
3145 * happen anymore, but prepare for broken callers.
3147 error("feeding unmodified %s to diffcore",
3148 p->one->path);
3149 p->status = DIFF_STATUS_UNKNOWN;
3152 diff_debug_queue("resolve-rename-copy done", q);
3155 static int check_pair_status(struct diff_filepair *p)
3157 switch (p->status) {
3158 case DIFF_STATUS_UNKNOWN:
3159 return 0;
3160 case 0:
3161 die("internal error in diff-resolve-rename-copy");
3162 default:
3163 return 1;
3167 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
3169 int fmt = opt->output_format;
3171 if (fmt & DIFF_FORMAT_CHECKDIFF)
3172 diff_flush_checkdiff(p, opt);
3173 else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
3174 diff_flush_raw(p, opt);
3175 else if (fmt & DIFF_FORMAT_NAME) {
3176 const char *name_a, *name_b;
3177 name_a = p->two->path;
3178 name_b = NULL;
3179 strip_prefix(opt->prefix_length, &name_a, &name_b);
3180 write_name_quoted(name_a, opt->file, opt->line_termination);
3184 static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
3186 if (fs->mode)
3187 fprintf(file, " %s mode %06o ", newdelete, fs->mode);
3188 else
3189 fprintf(file, " %s ", newdelete);
3190 write_name_quoted(fs->path, file, '\n');
3194 static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name)
3196 if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
3197 fprintf(file, " mode change %06o => %06o%c", p->one->mode, p->two->mode,
3198 show_name ? ' ' : '\n');
3199 if (show_name) {
3200 write_name_quoted(p->two->path, file, '\n');
3205 static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p)
3207 char *names = pprint_rename(p->one->path, p->two->path);
3209 fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
3210 free(names);
3211 show_mode_change(file, p, 0);
3214 static void diff_summary(FILE *file, struct diff_filepair *p)
3216 switch(p->status) {
3217 case DIFF_STATUS_DELETED:
3218 show_file_mode_name(file, "delete", p->one);
3219 break;
3220 case DIFF_STATUS_ADDED:
3221 show_file_mode_name(file, "create", p->two);
3222 break;
3223 case DIFF_STATUS_COPIED:
3224 show_rename_copy(file, "copy", p);
3225 break;
3226 case DIFF_STATUS_RENAMED:
3227 show_rename_copy(file, "rename", p);
3228 break;
3229 default:
3230 if (p->score) {
3231 fputs(" rewrite ", file);
3232 write_name_quoted(p->two->path, file, ' ');
3233 fprintf(file, "(%d%%)\n", similarity_index(p));
3235 show_mode_change(file, p, !p->score);
3236 break;
3240 struct patch_id_t {
3241 git_SHA_CTX *ctx;
3242 int patchlen;
3245 static int remove_space(char *line, int len)
3247 int i;
3248 char *dst = line;
3249 unsigned char c;
3251 for (i = 0; i < len; i++)
3252 if (!isspace((c = line[i])))
3253 *dst++ = c;
3255 return dst - line;
3258 static void patch_id_consume(void *priv, char *line, unsigned long len)
3260 struct patch_id_t *data = priv;
3261 int new_len;
3263 /* Ignore line numbers when computing the SHA1 of the patch */
3264 if (!prefixcmp(line, "@@ -"))
3265 return;
3267 new_len = remove_space(line, len);
3269 git_SHA1_Update(data->ctx, line, new_len);
3270 data->patchlen += new_len;
3273 /* returns 0 upon success, and writes result into sha1 */
3274 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
3276 struct diff_queue_struct *q = &diff_queued_diff;
3277 int i;
3278 git_SHA_CTX ctx;
3279 struct patch_id_t data;
3280 char buffer[PATH_MAX * 4 + 20];
3282 git_SHA1_Init(&ctx);
3283 memset(&data, 0, sizeof(struct patch_id_t));
3284 data.ctx = &ctx;
3286 for (i = 0; i < q->nr; i++) {
3287 xpparam_t xpp;
3288 xdemitconf_t xecfg;
3289 xdemitcb_t ecb;
3290 mmfile_t mf1, mf2;
3291 struct diff_filepair *p = q->queue[i];
3292 int len1, len2;
3294 memset(&xpp, 0, sizeof(xpp));
3295 memset(&xecfg, 0, sizeof(xecfg));
3296 if (p->status == 0)
3297 return error("internal diff status error");
3298 if (p->status == DIFF_STATUS_UNKNOWN)
3299 continue;
3300 if (diff_unmodified_pair(p))
3301 continue;
3302 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3303 (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3304 continue;
3305 if (DIFF_PAIR_UNMERGED(p))
3306 continue;
3308 diff_fill_sha1_info(p->one);
3309 diff_fill_sha1_info(p->two);
3310 if (fill_mmfile(&mf1, p->one) < 0 ||
3311 fill_mmfile(&mf2, p->two) < 0)
3312 return error("unable to read files to diff");
3314 len1 = remove_space(p->one->path, strlen(p->one->path));
3315 len2 = remove_space(p->two->path, strlen(p->two->path));
3316 if (p->one->mode == 0)
3317 len1 = snprintf(buffer, sizeof(buffer),
3318 "diff--gita/%.*sb/%.*s"
3319 "newfilemode%06o"
3320 "---/dev/null"
3321 "+++b/%.*s",
3322 len1, p->one->path,
3323 len2, p->two->path,
3324 p->two->mode,
3325 len2, p->two->path);
3326 else if (p->two->mode == 0)
3327 len1 = snprintf(buffer, sizeof(buffer),
3328 "diff--gita/%.*sb/%.*s"
3329 "deletedfilemode%06o"
3330 "---a/%.*s"
3331 "+++/dev/null",
3332 len1, p->one->path,
3333 len2, p->two->path,
3334 p->one->mode,
3335 len1, p->one->path);
3336 else
3337 len1 = snprintf(buffer, sizeof(buffer),
3338 "diff--gita/%.*sb/%.*s"
3339 "---a/%.*s"
3340 "+++b/%.*s",
3341 len1, p->one->path,
3342 len2, p->two->path,
3343 len1, p->one->path,
3344 len2, p->two->path);
3345 git_SHA1_Update(&ctx, buffer, len1);
3347 xpp.flags = XDF_NEED_MINIMAL;
3348 xecfg.ctxlen = 3;
3349 xecfg.flags = XDL_EMIT_FUNCNAMES;
3350 xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
3351 &xpp, &xecfg, &ecb);
3354 git_SHA1_Final(sha1, &ctx);
3355 return 0;
3358 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
3360 struct diff_queue_struct *q = &diff_queued_diff;
3361 int i;
3362 int result = diff_get_patch_id(options, sha1);
3364 for (i = 0; i < q->nr; i++)
3365 diff_free_filepair(q->queue[i]);
3367 free(q->queue);
3368 q->queue = NULL;
3369 q->nr = q->alloc = 0;
3371 return result;
3374 static int is_summary_empty(const struct diff_queue_struct *q)
3376 int i;
3378 for (i = 0; i < q->nr; i++) {
3379 const struct diff_filepair *p = q->queue[i];
3381 switch (p->status) {
3382 case DIFF_STATUS_DELETED:
3383 case DIFF_STATUS_ADDED:
3384 case DIFF_STATUS_COPIED:
3385 case DIFF_STATUS_RENAMED:
3386 return 0;
3387 default:
3388 if (p->score)
3389 return 0;
3390 if (p->one->mode && p->two->mode &&
3391 p->one->mode != p->two->mode)
3392 return 0;
3393 break;
3396 return 1;
3399 void diff_flush(struct diff_options *options)
3401 struct diff_queue_struct *q = &diff_queued_diff;
3402 int i, output_format = options->output_format;
3403 int separator = 0;
3406 * Order: raw, stat, summary, patch
3407 * or: name/name-status/checkdiff (other bits clear)
3409 if (!q->nr)
3410 goto free_queue;
3412 if (output_format & (DIFF_FORMAT_RAW |
3413 DIFF_FORMAT_NAME |
3414 DIFF_FORMAT_NAME_STATUS |
3415 DIFF_FORMAT_CHECKDIFF)) {
3416 for (i = 0; i < q->nr; i++) {
3417 struct diff_filepair *p = q->queue[i];
3418 if (check_pair_status(p))
3419 flush_one_pair(p, options);
3421 separator++;
3424 if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
3425 struct diffstat_t diffstat;
3427 memset(&diffstat, 0, sizeof(struct diffstat_t));
3428 for (i = 0; i < q->nr; i++) {
3429 struct diff_filepair *p = q->queue[i];
3430 if (check_pair_status(p))
3431 diff_flush_stat(p, options, &diffstat);
3433 if (output_format & DIFF_FORMAT_NUMSTAT)
3434 show_numstat(&diffstat, options);
3435 if (output_format & DIFF_FORMAT_DIFFSTAT)
3436 show_stats(&diffstat, options);
3437 if (output_format & DIFF_FORMAT_SHORTSTAT)
3438 show_shortstats(&diffstat, options);
3439 free_diffstat_info(&diffstat);
3440 separator++;
3442 if (output_format & DIFF_FORMAT_DIRSTAT)
3443 show_dirstat(options);
3445 if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
3446 for (i = 0; i < q->nr; i++)
3447 diff_summary(options->file, q->queue[i]);
3448 separator++;
3451 if (output_format & DIFF_FORMAT_PATCH) {
3452 if (separator) {
3453 putc(options->line_termination, options->file);
3454 if (options->stat_sep) {
3455 /* attach patch instead of inline */
3456 fputs(options->stat_sep, options->file);
3460 for (i = 0; i < q->nr; i++) {
3461 struct diff_filepair *p = q->queue[i];
3462 if (check_pair_status(p))
3463 diff_flush_patch(p, options);
3467 if (output_format & DIFF_FORMAT_CALLBACK)
3468 options->format_callback(q, options, options->format_callback_data);
3470 for (i = 0; i < q->nr; i++)
3471 diff_free_filepair(q->queue[i]);
3472 free_queue:
3473 free(q->queue);
3474 q->queue = NULL;
3475 q->nr = q->alloc = 0;
3476 if (options->close_file)
3477 fclose(options->file);
3480 * Report the content-level differences with HAS_CHANGES;
3481 * diff_addremove/diff_change does not set the bit when
3482 * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
3484 if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
3485 if (options->found_changes)
3486 DIFF_OPT_SET(options, HAS_CHANGES);
3487 else
3488 DIFF_OPT_CLR(options, HAS_CHANGES);
3492 static void diffcore_apply_filter(const char *filter)
3494 int i;
3495 struct diff_queue_struct *q = &diff_queued_diff;
3496 struct diff_queue_struct outq;
3497 outq.queue = NULL;
3498 outq.nr = outq.alloc = 0;
3500 if (!filter)
3501 return;
3503 if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
3504 int found;
3505 for (i = found = 0; !found && i < q->nr; i++) {
3506 struct diff_filepair *p = q->queue[i];
3507 if (((p->status == DIFF_STATUS_MODIFIED) &&
3508 ((p->score &&
3509 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3510 (!p->score &&
3511 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3512 ((p->status != DIFF_STATUS_MODIFIED) &&
3513 strchr(filter, p->status)))
3514 found++;
3516 if (found)
3517 return;
3519 /* otherwise we will clear the whole queue
3520 * by copying the empty outq at the end of this
3521 * function, but first clear the current entries
3522 * in the queue.
3524 for (i = 0; i < q->nr; i++)
3525 diff_free_filepair(q->queue[i]);
3527 else {
3528 /* Only the matching ones */
3529 for (i = 0; i < q->nr; i++) {
3530 struct diff_filepair *p = q->queue[i];
3532 if (((p->status == DIFF_STATUS_MODIFIED) &&
3533 ((p->score &&
3534 strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3535 (!p->score &&
3536 strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3537 ((p->status != DIFF_STATUS_MODIFIED) &&
3538 strchr(filter, p->status)))
3539 diff_q(&outq, p);
3540 else
3541 diff_free_filepair(p);
3544 free(q->queue);
3545 *q = outq;
3548 /* Check whether two filespecs with the same mode and size are identical */
3549 static int diff_filespec_is_identical(struct diff_filespec *one,
3550 struct diff_filespec *two)
3552 if (S_ISGITLINK(one->mode))
3553 return 0;
3554 if (diff_populate_filespec(one, 0))
3555 return 0;
3556 if (diff_populate_filespec(two, 0))
3557 return 0;
3558 return !memcmp(one->data, two->data, one->size);
3561 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
3563 int i;
3564 struct diff_queue_struct *q = &diff_queued_diff;
3565 struct diff_queue_struct outq;
3566 outq.queue = NULL;
3567 outq.nr = outq.alloc = 0;
3569 for (i = 0; i < q->nr; i++) {
3570 struct diff_filepair *p = q->queue[i];
3573 * 1. Entries that come from stat info dirtyness
3574 * always have both sides (iow, not create/delete),
3575 * one side of the object name is unknown, with
3576 * the same mode and size. Keep the ones that
3577 * do not match these criteria. They have real
3578 * differences.
3580 * 2. At this point, the file is known to be modified,
3581 * with the same mode and size, and the object
3582 * name of one side is unknown. Need to inspect
3583 * the identical contents.
3585 if (!DIFF_FILE_VALID(p->one) || /* (1) */
3586 !DIFF_FILE_VALID(p->two) ||
3587 (p->one->sha1_valid && p->two->sha1_valid) ||
3588 (p->one->mode != p->two->mode) ||
3589 diff_populate_filespec(p->one, 1) ||
3590 diff_populate_filespec(p->two, 1) ||
3591 (p->one->size != p->two->size) ||
3592 !diff_filespec_is_identical(p->one, p->two)) /* (2) */
3593 diff_q(&outq, p);
3594 else {
3596 * The caller can subtract 1 from skip_stat_unmatch
3597 * to determine how many paths were dirty only
3598 * due to stat info mismatch.
3600 if (!DIFF_OPT_TST(diffopt, NO_INDEX))
3601 diffopt->skip_stat_unmatch++;
3602 diff_free_filepair(p);
3605 free(q->queue);
3606 *q = outq;
3609 void diffcore_std(struct diff_options *options)
3611 if (options->skip_stat_unmatch)
3612 diffcore_skip_stat_unmatch(options);
3613 if (options->break_opt != -1)
3614 diffcore_break(options->break_opt);
3615 if (options->detect_rename)
3616 diffcore_rename(options);
3617 if (options->break_opt != -1)
3618 diffcore_merge_broken();
3619 if (options->pickaxe)
3620 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
3621 if (options->orderfile)
3622 diffcore_order(options->orderfile);
3623 diff_resolve_rename_copy();
3624 diffcore_apply_filter(options->filter);
3626 if (diff_queued_diff.nr && !DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
3627 DIFF_OPT_SET(options, HAS_CHANGES);
3628 else
3629 DIFF_OPT_CLR(options, HAS_CHANGES);
3632 int diff_result_code(struct diff_options *opt, int status)
3634 int result = 0;
3635 if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3636 !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
3637 return status;
3638 if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3639 DIFF_OPT_TST(opt, HAS_CHANGES))
3640 result |= 01;
3641 if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
3642 DIFF_OPT_TST(opt, CHECK_FAILED))
3643 result |= 02;
3644 return result;
3647 void diff_addremove(struct diff_options *options,
3648 int addremove, unsigned mode,
3649 const unsigned char *sha1,
3650 const char *concatpath)
3652 struct diff_filespec *one, *two;
3654 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(mode))
3655 return;
3657 /* This may look odd, but it is a preparation for
3658 * feeding "there are unchanged files which should
3659 * not produce diffs, but when you are doing copy
3660 * detection you would need them, so here they are"
3661 * entries to the diff-core. They will be prefixed
3662 * with something like '=' or '*' (I haven't decided
3663 * which but should not make any difference).
3664 * Feeding the same new and old to diff_change()
3665 * also has the same effect.
3666 * Before the final output happens, they are pruned after
3667 * merged into rename/copy pairs as appropriate.
3669 if (DIFF_OPT_TST(options, REVERSE_DIFF))
3670 addremove = (addremove == '+' ? '-' :
3671 addremove == '-' ? '+' : addremove);
3673 if (options->prefix &&
3674 strncmp(concatpath, options->prefix, options->prefix_length))
3675 return;
3677 one = alloc_filespec(concatpath);
3678 two = alloc_filespec(concatpath);
3680 if (addremove != '+')
3681 fill_filespec(one, sha1, mode);
3682 if (addremove != '-')
3683 fill_filespec(two, sha1, mode);
3685 diff_queue(&diff_queued_diff, one, two);
3686 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
3687 DIFF_OPT_SET(options, HAS_CHANGES);
3690 void diff_change(struct diff_options *options,
3691 unsigned old_mode, unsigned new_mode,
3692 const unsigned char *old_sha1,
3693 const unsigned char *new_sha1,
3694 const char *concatpath)
3696 struct diff_filespec *one, *two;
3698 if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(old_mode)
3699 && S_ISGITLINK(new_mode))
3700 return;
3702 if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
3703 unsigned tmp;
3704 const unsigned char *tmp_c;
3705 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
3706 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
3709 if (options->prefix &&
3710 strncmp(concatpath, options->prefix, options->prefix_length))
3711 return;
3713 one = alloc_filespec(concatpath);
3714 two = alloc_filespec(concatpath);
3715 fill_filespec(one, old_sha1, old_mode);
3716 fill_filespec(two, new_sha1, new_mode);
3718 diff_queue(&diff_queued_diff, one, two);
3719 if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
3720 DIFF_OPT_SET(options, HAS_CHANGES);
3723 void diff_unmerge(struct diff_options *options,
3724 const char *path,
3725 unsigned mode, const unsigned char *sha1)
3727 struct diff_filespec *one, *two;
3729 if (options->prefix &&
3730 strncmp(path, options->prefix, options->prefix_length))
3731 return;
3733 one = alloc_filespec(path);
3734 two = alloc_filespec(path);
3735 fill_filespec(one, sha1, mode);
3736 diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;
3739 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
3740 size_t *outsize)
3742 struct diff_tempfile *temp;
3743 const char *argv[3];
3744 const char **arg = argv;
3745 struct child_process child;
3746 struct strbuf buf = STRBUF_INIT;
3748 temp = prepare_temp_file(spec->path, spec);
3749 *arg++ = pgm;
3750 *arg++ = temp->name;
3751 *arg = NULL;
3753 memset(&child, 0, sizeof(child));
3754 child.argv = argv;
3755 child.out = -1;
3756 if (start_command(&child) != 0 ||
3757 strbuf_read(&buf, child.out, 0) < 0 ||
3758 finish_command(&child) != 0) {
3759 strbuf_release(&buf);
3760 remove_tempfile();
3761 error("error running textconv command '%s'", pgm);
3762 return NULL;
3764 remove_tempfile();
3766 return strbuf_detach(&buf, outsize);