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