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