Merge branch 'bb/unicode-12'
[git] / diff.c
1 /*
2  * Copyright (C) 2005 Junio C Hamano
3  */
4 #include "cache.h"
5 #include "config.h"
6 #include "tempfile.h"
7 #include "quote.h"
8 #include "diff.h"
9 #include "diffcore.h"
10 #include "delta.h"
11 #include "xdiff-interface.h"
12 #include "color.h"
13 #include "attr.h"
14 #include "run-command.h"
15 #include "utf8.h"
16 #include "object-store.h"
17 #include "userdiff.h"
18 #include "submodule-config.h"
19 #include "submodule.h"
20 #include "hashmap.h"
21 #include "ll-merge.h"
22 #include "string-list.h"
23 #include "argv-array.h"
24 #include "graph.h"
25 #include "packfile.h"
26 #include "parse-options.h"
27 #include "help.h"
28
29 #ifdef NO_FAST_WORKING_DIRECTORY
30 #define FAST_WORKING_DIRECTORY 0
31 #else
32 #define FAST_WORKING_DIRECTORY 1
33 #endif
34
35 static int diff_detect_rename_default;
36 static int diff_indent_heuristic = 1;
37 static int diff_rename_limit_default = 400;
38 static int diff_suppress_blank_empty;
39 static int diff_use_color_default = -1;
40 static int diff_color_moved_default;
41 static int diff_color_moved_ws_default;
42 static int diff_context_default = 3;
43 static int diff_interhunk_context_default;
44 static const char *diff_word_regex_cfg;
45 static const char *external_diff_cmd_cfg;
46 static const char *diff_order_file_cfg;
47 int diff_auto_refresh_index = 1;
48 static int diff_mnemonic_prefix;
49 static int diff_no_prefix;
50 static int diff_stat_graph_width;
51 static int diff_dirstat_permille_default = 30;
52 static struct diff_options default_diff_options;
53 static long diff_algorithm;
54 static unsigned ws_error_highlight_default = WSEH_NEW;
55
56 static char diff_colors[][COLOR_MAXLEN] = {
57         GIT_COLOR_RESET,
58         GIT_COLOR_NORMAL,       /* CONTEXT */
59         GIT_COLOR_BOLD,         /* METAINFO */
60         GIT_COLOR_CYAN,         /* FRAGINFO */
61         GIT_COLOR_RED,          /* OLD */
62         GIT_COLOR_GREEN,        /* NEW */
63         GIT_COLOR_YELLOW,       /* COMMIT */
64         GIT_COLOR_BG_RED,       /* WHITESPACE */
65         GIT_COLOR_NORMAL,       /* FUNCINFO */
66         GIT_COLOR_BOLD_MAGENTA, /* OLD_MOVED */
67         GIT_COLOR_BOLD_BLUE,    /* OLD_MOVED ALTERNATIVE */
68         GIT_COLOR_FAINT,        /* OLD_MOVED_DIM */
69         GIT_COLOR_FAINT_ITALIC, /* OLD_MOVED_ALTERNATIVE_DIM */
70         GIT_COLOR_BOLD_CYAN,    /* NEW_MOVED */
71         GIT_COLOR_BOLD_YELLOW,  /* NEW_MOVED ALTERNATIVE */
72         GIT_COLOR_FAINT,        /* NEW_MOVED_DIM */
73         GIT_COLOR_FAINT_ITALIC, /* NEW_MOVED_ALTERNATIVE_DIM */
74         GIT_COLOR_FAINT,        /* CONTEXT_DIM */
75         GIT_COLOR_FAINT_RED,    /* OLD_DIM */
76         GIT_COLOR_FAINT_GREEN,  /* NEW_DIM */
77         GIT_COLOR_BOLD,         /* CONTEXT_BOLD */
78         GIT_COLOR_BOLD_RED,     /* OLD_BOLD */
79         GIT_COLOR_BOLD_GREEN,   /* NEW_BOLD */
80 };
81
82 static const char *color_diff_slots[] = {
83         [DIFF_CONTEXT]                = "context",
84         [DIFF_METAINFO]               = "meta",
85         [DIFF_FRAGINFO]               = "frag",
86         [DIFF_FILE_OLD]               = "old",
87         [DIFF_FILE_NEW]               = "new",
88         [DIFF_COMMIT]                 = "commit",
89         [DIFF_WHITESPACE]             = "whitespace",
90         [DIFF_FUNCINFO]               = "func",
91         [DIFF_FILE_OLD_MOVED]         = "oldMoved",
92         [DIFF_FILE_OLD_MOVED_ALT]     = "oldMovedAlternative",
93         [DIFF_FILE_OLD_MOVED_DIM]     = "oldMovedDimmed",
94         [DIFF_FILE_OLD_MOVED_ALT_DIM] = "oldMovedAlternativeDimmed",
95         [DIFF_FILE_NEW_MOVED]         = "newMoved",
96         [DIFF_FILE_NEW_MOVED_ALT]     = "newMovedAlternative",
97         [DIFF_FILE_NEW_MOVED_DIM]     = "newMovedDimmed",
98         [DIFF_FILE_NEW_MOVED_ALT_DIM] = "newMovedAlternativeDimmed",
99         [DIFF_CONTEXT_DIM]            = "contextDimmed",
100         [DIFF_FILE_OLD_DIM]           = "oldDimmed",
101         [DIFF_FILE_NEW_DIM]           = "newDimmed",
102         [DIFF_CONTEXT_BOLD]           = "contextBold",
103         [DIFF_FILE_OLD_BOLD]          = "oldBold",
104         [DIFF_FILE_NEW_BOLD]          = "newBold",
105 };
106
107 define_list_config_array_extra(color_diff_slots, {"plain"});
108
109 static int parse_diff_color_slot(const char *var)
110 {
111         if (!strcasecmp(var, "plain"))
112                 return DIFF_CONTEXT;
113         return LOOKUP_CONFIG(color_diff_slots, var);
114 }
115
116 static int parse_dirstat_params(struct diff_options *options, const char *params_string,
117                                 struct strbuf *errmsg)
118 {
119         char *params_copy = xstrdup(params_string);
120         struct string_list params = STRING_LIST_INIT_NODUP;
121         int ret = 0;
122         int i;
123
124         if (*params_copy)
125                 string_list_split_in_place(&params, params_copy, ',', -1);
126         for (i = 0; i < params.nr; i++) {
127                 const char *p = params.items[i].string;
128                 if (!strcmp(p, "changes")) {
129                         options->flags.dirstat_by_line = 0;
130                         options->flags.dirstat_by_file = 0;
131                 } else if (!strcmp(p, "lines")) {
132                         options->flags.dirstat_by_line = 1;
133                         options->flags.dirstat_by_file = 0;
134                 } else if (!strcmp(p, "files")) {
135                         options->flags.dirstat_by_line = 0;
136                         options->flags.dirstat_by_file = 1;
137                 } else if (!strcmp(p, "noncumulative")) {
138                         options->flags.dirstat_cumulative = 0;
139                 } else if (!strcmp(p, "cumulative")) {
140                         options->flags.dirstat_cumulative = 1;
141                 } else if (isdigit(*p)) {
142                         char *end;
143                         int permille = strtoul(p, &end, 10) * 10;
144                         if (*end == '.' && isdigit(*++end)) {
145                                 /* only use first digit */
146                                 permille += *end - '0';
147                                 /* .. and ignore any further digits */
148                                 while (isdigit(*++end))
149                                         ; /* nothing */
150                         }
151                         if (!*end)
152                                 options->dirstat_permille = permille;
153                         else {
154                                 strbuf_addf(errmsg, _("  Failed to parse dirstat cut-off percentage '%s'\n"),
155                                             p);
156                                 ret++;
157                         }
158                 } else {
159                         strbuf_addf(errmsg, _("  Unknown dirstat parameter '%s'\n"), p);
160                         ret++;
161                 }
162
163         }
164         string_list_clear(&params, 0);
165         free(params_copy);
166         return ret;
167 }
168
169 static int parse_submodule_params(struct diff_options *options, const char *value)
170 {
171         if (!strcmp(value, "log"))
172                 options->submodule_format = DIFF_SUBMODULE_LOG;
173         else if (!strcmp(value, "short"))
174                 options->submodule_format = DIFF_SUBMODULE_SHORT;
175         else if (!strcmp(value, "diff"))
176                 options->submodule_format = DIFF_SUBMODULE_INLINE_DIFF;
177         /*
178          * Please update $__git_diff_submodule_formats in
179          * git-completion.bash when you add new formats.
180          */
181         else
182                 return -1;
183         return 0;
184 }
185
186 int git_config_rename(const char *var, const char *value)
187 {
188         if (!value)
189                 return DIFF_DETECT_RENAME;
190         if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
191                 return  DIFF_DETECT_COPY;
192         return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
193 }
194
195 long parse_algorithm_value(const char *value)
196 {
197         if (!value)
198                 return -1;
199         else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
200                 return 0;
201         else if (!strcasecmp(value, "minimal"))
202                 return XDF_NEED_MINIMAL;
203         else if (!strcasecmp(value, "patience"))
204                 return XDF_PATIENCE_DIFF;
205         else if (!strcasecmp(value, "histogram"))
206                 return XDF_HISTOGRAM_DIFF;
207         /*
208          * Please update $__git_diff_algorithms in git-completion.bash
209          * when you add new algorithms.
210          */
211         return -1;
212 }
213
214 static int parse_one_token(const char **arg, const char *token)
215 {
216         const char *rest;
217         if (skip_prefix(*arg, token, &rest) && (!*rest || *rest == ',')) {
218                 *arg = rest;
219                 return 1;
220         }
221         return 0;
222 }
223
224 static int parse_ws_error_highlight(const char *arg)
225 {
226         const char *orig_arg = arg;
227         unsigned val = 0;
228
229         while (*arg) {
230                 if (parse_one_token(&arg, "none"))
231                         val = 0;
232                 else if (parse_one_token(&arg, "default"))
233                         val = WSEH_NEW;
234                 else if (parse_one_token(&arg, "all"))
235                         val = WSEH_NEW | WSEH_OLD | WSEH_CONTEXT;
236                 else if (parse_one_token(&arg, "new"))
237                         val |= WSEH_NEW;
238                 else if (parse_one_token(&arg, "old"))
239                         val |= WSEH_OLD;
240                 else if (parse_one_token(&arg, "context"))
241                         val |= WSEH_CONTEXT;
242                 else {
243                         return -1 - (int)(arg - orig_arg);
244                 }
245                 if (*arg)
246                         arg++;
247         }
248         return val;
249 }
250
251 /*
252  * These are to give UI layer defaults.
253  * The core-level commands such as git-diff-files should
254  * never be affected by the setting of diff.renames
255  * the user happens to have in the configuration file.
256  */
257 void init_diff_ui_defaults(void)
258 {
259         diff_detect_rename_default = DIFF_DETECT_RENAME;
260 }
261
262 int git_diff_heuristic_config(const char *var, const char *value, void *cb)
263 {
264         if (!strcmp(var, "diff.indentheuristic"))
265                 diff_indent_heuristic = git_config_bool(var, value);
266         return 0;
267 }
268
269 static int parse_color_moved(const char *arg)
270 {
271         switch (git_parse_maybe_bool(arg)) {
272         case 0:
273                 return COLOR_MOVED_NO;
274         case 1:
275                 return COLOR_MOVED_DEFAULT;
276         default:
277                 break;
278         }
279
280         if (!strcmp(arg, "no"))
281                 return COLOR_MOVED_NO;
282         else if (!strcmp(arg, "plain"))
283                 return COLOR_MOVED_PLAIN;
284         else if (!strcmp(arg, "blocks"))
285                 return COLOR_MOVED_BLOCKS;
286         else if (!strcmp(arg, "zebra"))
287                 return COLOR_MOVED_ZEBRA;
288         else if (!strcmp(arg, "default"))
289                 return COLOR_MOVED_DEFAULT;
290         else if (!strcmp(arg, "dimmed-zebra"))
291                 return COLOR_MOVED_ZEBRA_DIM;
292         else if (!strcmp(arg, "dimmed_zebra"))
293                 return COLOR_MOVED_ZEBRA_DIM;
294         else
295                 return error(_("color moved setting must be one of 'no', 'default', 'blocks', 'zebra', 'dimmed-zebra', 'plain'"));
296 }
297
298 static unsigned parse_color_moved_ws(const char *arg)
299 {
300         int ret = 0;
301         struct string_list l = STRING_LIST_INIT_DUP;
302         struct string_list_item *i;
303
304         string_list_split(&l, arg, ',', -1);
305
306         for_each_string_list_item(i, &l) {
307                 struct strbuf sb = STRBUF_INIT;
308                 strbuf_addstr(&sb, i->string);
309                 strbuf_trim(&sb);
310
311                 if (!strcmp(sb.buf, "no"))
312                         ret = 0;
313                 else if (!strcmp(sb.buf, "ignore-space-change"))
314                         ret |= XDF_IGNORE_WHITESPACE_CHANGE;
315                 else if (!strcmp(sb.buf, "ignore-space-at-eol"))
316                         ret |= XDF_IGNORE_WHITESPACE_AT_EOL;
317                 else if (!strcmp(sb.buf, "ignore-all-space"))
318                         ret |= XDF_IGNORE_WHITESPACE;
319                 else if (!strcmp(sb.buf, "allow-indentation-change"))
320                         ret |= COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE;
321                 else {
322                         ret |= COLOR_MOVED_WS_ERROR;
323                         error(_("unknown color-moved-ws mode '%s', possible values are 'ignore-space-change', 'ignore-space-at-eol', 'ignore-all-space', 'allow-indentation-change'"), sb.buf);
324                 }
325
326                 strbuf_release(&sb);
327         }
328
329         if ((ret & COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE) &&
330             (ret & XDF_WHITESPACE_FLAGS)) {
331                 error(_("color-moved-ws: allow-indentation-change cannot be combined with other whitespace modes"));
332                 ret |= COLOR_MOVED_WS_ERROR;
333         }
334
335         string_list_clear(&l, 0);
336
337         return ret;
338 }
339
340 int git_diff_ui_config(const char *var, const char *value, void *cb)
341 {
342         if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
343                 diff_use_color_default = git_config_colorbool(var, value);
344                 return 0;
345         }
346         if (!strcmp(var, "diff.colormoved")) {
347                 int cm = parse_color_moved(value);
348                 if (cm < 0)
349                         return -1;
350                 diff_color_moved_default = cm;
351                 return 0;
352         }
353         if (!strcmp(var, "diff.colormovedws")) {
354                 unsigned cm = parse_color_moved_ws(value);
355                 if (cm & COLOR_MOVED_WS_ERROR)
356                         return -1;
357                 diff_color_moved_ws_default = cm;
358                 return 0;
359         }
360         if (!strcmp(var, "diff.context")) {
361                 diff_context_default = git_config_int(var, value);
362                 if (diff_context_default < 0)
363                         return -1;
364                 return 0;
365         }
366         if (!strcmp(var, "diff.interhunkcontext")) {
367                 diff_interhunk_context_default = git_config_int(var, value);
368                 if (diff_interhunk_context_default < 0)
369                         return -1;
370                 return 0;
371         }
372         if (!strcmp(var, "diff.renames")) {
373                 diff_detect_rename_default = git_config_rename(var, value);
374                 return 0;
375         }
376         if (!strcmp(var, "diff.autorefreshindex")) {
377                 diff_auto_refresh_index = git_config_bool(var, value);
378                 return 0;
379         }
380         if (!strcmp(var, "diff.mnemonicprefix")) {
381                 diff_mnemonic_prefix = git_config_bool(var, value);
382                 return 0;
383         }
384         if (!strcmp(var, "diff.noprefix")) {
385                 diff_no_prefix = git_config_bool(var, value);
386                 return 0;
387         }
388         if (!strcmp(var, "diff.statgraphwidth")) {
389                 diff_stat_graph_width = git_config_int(var, value);
390                 return 0;
391         }
392         if (!strcmp(var, "diff.external"))
393                 return git_config_string(&external_diff_cmd_cfg, var, value);
394         if (!strcmp(var, "diff.wordregex"))
395                 return git_config_string(&diff_word_regex_cfg, var, value);
396         if (!strcmp(var, "diff.orderfile"))
397                 return git_config_pathname(&diff_order_file_cfg, var, value);
398
399         if (!strcmp(var, "diff.ignoresubmodules"))
400                 handle_ignore_submodules_arg(&default_diff_options, value);
401
402         if (!strcmp(var, "diff.submodule")) {
403                 if (parse_submodule_params(&default_diff_options, value))
404                         warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
405                                 value);
406                 return 0;
407         }
408
409         if (!strcmp(var, "diff.algorithm")) {
410                 diff_algorithm = parse_algorithm_value(value);
411                 if (diff_algorithm < 0)
412                         return -1;
413                 return 0;
414         }
415
416         if (!strcmp(var, "diff.wserrorhighlight")) {
417                 int val = parse_ws_error_highlight(value);
418                 if (val < 0)
419                         return -1;
420                 ws_error_highlight_default = val;
421                 return 0;
422         }
423
424         if (git_color_config(var, value, cb) < 0)
425                 return -1;
426
427         return git_diff_basic_config(var, value, cb);
428 }
429
430 int git_diff_basic_config(const char *var, const char *value, void *cb)
431 {
432         const char *name;
433
434         if (!strcmp(var, "diff.renamelimit")) {
435                 diff_rename_limit_default = git_config_int(var, value);
436                 return 0;
437         }
438
439         if (userdiff_config(var, value) < 0)
440                 return -1;
441
442         if (skip_prefix(var, "diff.color.", &name) ||
443             skip_prefix(var, "color.diff.", &name)) {
444                 int slot = parse_diff_color_slot(name);
445                 if (slot < 0)
446                         return 0;
447                 if (!value)
448                         return config_error_nonbool(var);
449                 return color_parse(value, diff_colors[slot]);
450         }
451
452         /* like GNU diff's --suppress-blank-empty option  */
453         if (!strcmp(var, "diff.suppressblankempty") ||
454                         /* for backwards compatibility */
455                         !strcmp(var, "diff.suppress-blank-empty")) {
456                 diff_suppress_blank_empty = git_config_bool(var, value);
457                 return 0;
458         }
459
460         if (!strcmp(var, "diff.dirstat")) {
461                 struct strbuf errmsg = STRBUF_INIT;
462                 default_diff_options.dirstat_permille = diff_dirstat_permille_default;
463                 if (parse_dirstat_params(&default_diff_options, value, &errmsg))
464                         warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
465                                 errmsg.buf);
466                 strbuf_release(&errmsg);
467                 diff_dirstat_permille_default = default_diff_options.dirstat_permille;
468                 return 0;
469         }
470
471         if (git_diff_heuristic_config(var, value, cb) < 0)
472                 return -1;
473
474         return git_default_config(var, value, cb);
475 }
476
477 static char *quote_two(const char *one, const char *two)
478 {
479         int need_one = quote_c_style(one, NULL, NULL, 1);
480         int need_two = quote_c_style(two, NULL, NULL, 1);
481         struct strbuf res = STRBUF_INIT;
482
483         if (need_one + need_two) {
484                 strbuf_addch(&res, '"');
485                 quote_c_style(one, &res, NULL, 1);
486                 quote_c_style(two, &res, NULL, 1);
487                 strbuf_addch(&res, '"');
488         } else {
489                 strbuf_addstr(&res, one);
490                 strbuf_addstr(&res, two);
491         }
492         return strbuf_detach(&res, NULL);
493 }
494
495 static const char *external_diff(void)
496 {
497         static const char *external_diff_cmd = NULL;
498         static int done_preparing = 0;
499
500         if (done_preparing)
501                 return external_diff_cmd;
502         external_diff_cmd = xstrdup_or_null(getenv("GIT_EXTERNAL_DIFF"));
503         if (!external_diff_cmd)
504                 external_diff_cmd = external_diff_cmd_cfg;
505         done_preparing = 1;
506         return external_diff_cmd;
507 }
508
509 /*
510  * Keep track of files used for diffing. Sometimes such an entry
511  * refers to a temporary file, sometimes to an existing file, and
512  * sometimes to "/dev/null".
513  */
514 static struct diff_tempfile {
515         /*
516          * filename external diff should read from, or NULL if this
517          * entry is currently not in use:
518          */
519         const char *name;
520
521         char hex[GIT_MAX_HEXSZ + 1];
522         char mode[10];
523
524         /*
525          * If this diff_tempfile instance refers to a temporary file,
526          * this tempfile object is used to manage its lifetime.
527          */
528         struct tempfile *tempfile;
529 } diff_temp[2];
530
531 struct emit_callback {
532         int color_diff;
533         unsigned ws_rule;
534         int blank_at_eof_in_preimage;
535         int blank_at_eof_in_postimage;
536         int lno_in_preimage;
537         int lno_in_postimage;
538         const char **label_path;
539         struct diff_words_data *diff_words;
540         struct diff_options *opt;
541         struct strbuf *header;
542 };
543
544 static int count_lines(const char *data, int size)
545 {
546         int count, ch, completely_empty = 1, nl_just_seen = 0;
547         count = 0;
548         while (0 < size--) {
549                 ch = *data++;
550                 if (ch == '\n') {
551                         count++;
552                         nl_just_seen = 1;
553                         completely_empty = 0;
554                 }
555                 else {
556                         nl_just_seen = 0;
557                         completely_empty = 0;
558                 }
559         }
560         if (completely_empty)
561                 return 0;
562         if (!nl_just_seen)
563                 count++; /* no trailing newline */
564         return count;
565 }
566
567 static int fill_mmfile(struct repository *r, mmfile_t *mf,
568                        struct diff_filespec *one)
569 {
570         if (!DIFF_FILE_VALID(one)) {
571                 mf->ptr = (char *)""; /* does not matter */
572                 mf->size = 0;
573                 return 0;
574         }
575         else if (diff_populate_filespec(r, one, 0))
576                 return -1;
577
578         mf->ptr = one->data;
579         mf->size = one->size;
580         return 0;
581 }
582
583 /* like fill_mmfile, but only for size, so we can avoid retrieving blob */
584 static unsigned long diff_filespec_size(struct repository *r,
585                                         struct diff_filespec *one)
586 {
587         if (!DIFF_FILE_VALID(one))
588                 return 0;
589         diff_populate_filespec(r, one, CHECK_SIZE_ONLY);
590         return one->size;
591 }
592
593 static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
594 {
595         char *ptr = mf->ptr;
596         long size = mf->size;
597         int cnt = 0;
598
599         if (!size)
600                 return cnt;
601         ptr += size - 1; /* pointing at the very end */
602         if (*ptr != '\n')
603                 ; /* incomplete line */
604         else
605                 ptr--; /* skip the last LF */
606         while (mf->ptr < ptr) {
607                 char *prev_eol;
608                 for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
609                         if (*prev_eol == '\n')
610                                 break;
611                 if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
612                         break;
613                 cnt++;
614                 ptr = prev_eol - 1;
615         }
616         return cnt;
617 }
618
619 static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
620                                struct emit_callback *ecbdata)
621 {
622         int l1, l2, at;
623         unsigned ws_rule = ecbdata->ws_rule;
624         l1 = count_trailing_blank(mf1, ws_rule);
625         l2 = count_trailing_blank(mf2, ws_rule);
626         if (l2 <= l1) {
627                 ecbdata->blank_at_eof_in_preimage = 0;
628                 ecbdata->blank_at_eof_in_postimage = 0;
629                 return;
630         }
631         at = count_lines(mf1->ptr, mf1->size);
632         ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
633
634         at = count_lines(mf2->ptr, mf2->size);
635         ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
636 }
637
638 static void emit_line_0(struct diff_options *o,
639                         const char *set_sign, const char *set, unsigned reverse, const char *reset,
640                         int first, const char *line, int len)
641 {
642         int has_trailing_newline, has_trailing_carriage_return;
643         int needs_reset = 0; /* at the end of the line */
644         FILE *file = o->file;
645
646         fputs(diff_line_prefix(o), file);
647
648         has_trailing_newline = (len > 0 && line[len-1] == '\n');
649         if (has_trailing_newline)
650                 len--;
651
652         has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
653         if (has_trailing_carriage_return)
654                 len--;
655
656         if (!len && !first)
657                 goto end_of_line;
658
659         if (reverse && want_color(o->use_color)) {
660                 fputs(GIT_COLOR_REVERSE, file);
661                 needs_reset = 1;
662         }
663
664         if (set_sign) {
665                 fputs(set_sign, file);
666                 needs_reset = 1;
667         }
668
669         if (first)
670                 fputc(first, file);
671
672         if (!len)
673                 goto end_of_line;
674
675         if (set) {
676                 if (set_sign && set != set_sign)
677                         fputs(reset, file);
678                 fputs(set, file);
679                 needs_reset = 1;
680         }
681         fwrite(line, len, 1, file);
682         needs_reset = 1; /* 'line' may contain color codes. */
683
684 end_of_line:
685         if (needs_reset)
686                 fputs(reset, file);
687         if (has_trailing_carriage_return)
688                 fputc('\r', file);
689         if (has_trailing_newline)
690                 fputc('\n', file);
691 }
692
693 static void emit_line(struct diff_options *o, const char *set, const char *reset,
694                       const char *line, int len)
695 {
696         emit_line_0(o, set, NULL, 0, reset, 0, line, len);
697 }
698
699 enum diff_symbol {
700         DIFF_SYMBOL_BINARY_DIFF_HEADER,
701         DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
702         DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
703         DIFF_SYMBOL_BINARY_DIFF_BODY,
704         DIFF_SYMBOL_BINARY_DIFF_FOOTER,
705         DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
706         DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
707         DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
708         DIFF_SYMBOL_STATS_LINE,
709         DIFF_SYMBOL_WORD_DIFF,
710         DIFF_SYMBOL_STAT_SEP,
711         DIFF_SYMBOL_SUMMARY,
712         DIFF_SYMBOL_SUBMODULE_ADD,
713         DIFF_SYMBOL_SUBMODULE_DEL,
714         DIFF_SYMBOL_SUBMODULE_UNTRACKED,
715         DIFF_SYMBOL_SUBMODULE_MODIFIED,
716         DIFF_SYMBOL_SUBMODULE_HEADER,
717         DIFF_SYMBOL_SUBMODULE_ERROR,
718         DIFF_SYMBOL_SUBMODULE_PIPETHROUGH,
719         DIFF_SYMBOL_REWRITE_DIFF,
720         DIFF_SYMBOL_BINARY_FILES,
721         DIFF_SYMBOL_HEADER,
722         DIFF_SYMBOL_FILEPAIR_PLUS,
723         DIFF_SYMBOL_FILEPAIR_MINUS,
724         DIFF_SYMBOL_WORDS_PORCELAIN,
725         DIFF_SYMBOL_WORDS,
726         DIFF_SYMBOL_CONTEXT,
727         DIFF_SYMBOL_CONTEXT_INCOMPLETE,
728         DIFF_SYMBOL_PLUS,
729         DIFF_SYMBOL_MINUS,
730         DIFF_SYMBOL_NO_LF_EOF,
731         DIFF_SYMBOL_CONTEXT_FRAGINFO,
732         DIFF_SYMBOL_CONTEXT_MARKER,
733         DIFF_SYMBOL_SEPARATOR
734 };
735 /*
736  * Flags for content lines:
737  * 0..12 are whitespace rules
738  * 13-15 are WSEH_NEW | WSEH_OLD | WSEH_CONTEXT
739  * 16 is marking if the line is blank at EOF
740  */
741 #define DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF      (1<<16)
742 #define DIFF_SYMBOL_MOVED_LINE                  (1<<17)
743 #define DIFF_SYMBOL_MOVED_LINE_ALT              (1<<18)
744 #define DIFF_SYMBOL_MOVED_LINE_UNINTERESTING    (1<<19)
745 #define DIFF_SYMBOL_CONTENT_WS_MASK (WSEH_NEW | WSEH_OLD | WSEH_CONTEXT | WS_RULE_MASK)
746
747 /*
748  * This struct is used when we need to buffer the output of the diff output.
749  *
750  * NEEDSWORK: Instead of storing a copy of the line, add an offset pointer
751  * into the pre/post image file. This pointer could be a union with the
752  * line pointer. By storing an offset into the file instead of the literal line,
753  * we can decrease the memory footprint for the buffered output. At first we
754  * may want to only have indirection for the content lines, but we could also
755  * enhance the state for emitting prefabricated lines, e.g. the similarity
756  * score line or hunk/file headers would only need to store a number or path
757  * and then the output can be constructed later on depending on state.
758  */
759 struct emitted_diff_symbol {
760         const char *line;
761         int len;
762         int flags;
763         int indent_off;   /* Offset to first non-whitespace character */
764         int indent_width; /* The visual width of the indentation */
765         enum diff_symbol s;
766 };
767 #define EMITTED_DIFF_SYMBOL_INIT {NULL}
768
769 struct emitted_diff_symbols {
770         struct emitted_diff_symbol *buf;
771         int nr, alloc;
772 };
773 #define EMITTED_DIFF_SYMBOLS_INIT {NULL, 0, 0}
774
775 static void append_emitted_diff_symbol(struct diff_options *o,
776                                        struct emitted_diff_symbol *e)
777 {
778         struct emitted_diff_symbol *f;
779
780         ALLOC_GROW(o->emitted_symbols->buf,
781                    o->emitted_symbols->nr + 1,
782                    o->emitted_symbols->alloc);
783         f = &o->emitted_symbols->buf[o->emitted_symbols->nr++];
784
785         memcpy(f, e, sizeof(struct emitted_diff_symbol));
786         f->line = e->line ? xmemdupz(e->line, e->len) : NULL;
787 }
788
789 struct moved_entry {
790         struct hashmap_entry ent;
791         const struct emitted_diff_symbol *es;
792         struct moved_entry *next_line;
793 };
794
795 struct moved_block {
796         struct moved_entry *match;
797         int wsd; /* The whitespace delta of this block */
798 };
799
800 static void moved_block_clear(struct moved_block *b)
801 {
802         memset(b, 0, sizeof(*b));
803 }
804
805 #define INDENT_BLANKLINE INT_MIN
806
807 static void fill_es_indent_data(struct emitted_diff_symbol *es)
808 {
809         unsigned int off = 0, i;
810         int width = 0, tab_width = es->flags & WS_TAB_WIDTH_MASK;
811         const char *s = es->line;
812         const int len = es->len;
813
814         /* skip any \v \f \r at start of indentation */
815         while (s[off] == '\f' || s[off] == '\v' ||
816                (s[off] == '\r' && off < len - 1))
817                 off++;
818
819         /* calculate the visual width of indentation */
820         while(1) {
821                 if (s[off] == ' ') {
822                         width++;
823                         off++;
824                 } else if (s[off] == '\t') {
825                         width += tab_width - (width % tab_width);
826                         while (s[++off] == '\t')
827                                 width += tab_width;
828                 } else {
829                         break;
830                 }
831         }
832
833         /* check if this line is blank */
834         for (i = off; i < len; i++)
835                 if (!isspace(s[i]))
836                     break;
837
838         if (i == len) {
839                 es->indent_width = INDENT_BLANKLINE;
840                 es->indent_off = len;
841         } else {
842                 es->indent_off = off;
843                 es->indent_width = width;
844         }
845 }
846
847 static int compute_ws_delta(const struct emitted_diff_symbol *a,
848                             const struct emitted_diff_symbol *b,
849                             int *out)
850 {
851         int a_len = a->len,
852             b_len = b->len,
853             a_off = a->indent_off,
854             a_width = a->indent_width,
855             b_off = b->indent_off,
856             b_width = b->indent_width;
857         int delta;
858
859         if (a_width == INDENT_BLANKLINE && b_width == INDENT_BLANKLINE) {
860                 *out = INDENT_BLANKLINE;
861                 return 1;
862         }
863
864         if (a->s == DIFF_SYMBOL_PLUS)
865                 delta = a_width - b_width;
866         else
867                 delta = b_width - a_width;
868
869         if (a_len - a_off != b_len - b_off ||
870             memcmp(a->line + a_off, b->line + b_off, a_len - a_off))
871                 return 0;
872
873         *out = delta;
874
875         return 1;
876 }
877
878 static int cmp_in_block_with_wsd(const struct diff_options *o,
879                                  const struct moved_entry *cur,
880                                  const struct moved_entry *match,
881                                  struct moved_block *pmb,
882                                  int n)
883 {
884         struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
885         int al = cur->es->len, bl = match->es->len, cl = l->len;
886         const char *a = cur->es->line,
887                    *b = match->es->line,
888                    *c = l->line;
889         int a_off = cur->es->indent_off,
890             a_width = cur->es->indent_width,
891             c_off = l->indent_off,
892             c_width = l->indent_width;
893         int delta;
894
895         /*
896          * We need to check if 'cur' is equal to 'match'.  As those
897          * are from the same (+/-) side, we do not need to adjust for
898          * indent changes. However these were found using fuzzy
899          * matching so we do have to check if they are equal. Here we
900          * just check the lengths. We delay calling memcmp() to check
901          * the contents until later as if the length comparison for a
902          * and c fails we can avoid the call all together.
903          */
904         if (al != bl)
905                 return 1;
906
907         /* If 'l' and 'cur' are both blank then they match. */
908         if (a_width == INDENT_BLANKLINE && c_width == INDENT_BLANKLINE)
909                 return 0;
910
911         /*
912          * The indent changes of the block are known and stored in pmb->wsd;
913          * however we need to check if the indent changes of the current line
914          * match those of the current block and that the text of 'l' and 'cur'
915          * after the indentation match.
916          */
917         if (cur->es->s == DIFF_SYMBOL_PLUS)
918                 delta = a_width - c_width;
919         else
920                 delta = c_width - a_width;
921
922         /*
923          * If the previous lines of this block were all blank then set its
924          * whitespace delta.
925          */
926         if (pmb->wsd == INDENT_BLANKLINE)
927                 pmb->wsd = delta;
928
929         return !(delta == pmb->wsd && al - a_off == cl - c_off &&
930                  !memcmp(a, b, al) && !
931                  memcmp(a + a_off, c + c_off, al - a_off));
932 }
933
934 static int moved_entry_cmp(const void *hashmap_cmp_fn_data,
935                            const void *entry,
936                            const void *entry_or_key,
937                            const void *keydata)
938 {
939         const struct diff_options *diffopt = hashmap_cmp_fn_data;
940         const struct moved_entry *a = entry;
941         const struct moved_entry *b = entry_or_key;
942         unsigned flags = diffopt->color_moved_ws_handling
943                          & XDF_WHITESPACE_FLAGS;
944
945         if (diffopt->color_moved_ws_handling &
946             COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
947                 /*
948                  * As there is not specific white space config given,
949                  * we'd need to check for a new block, so ignore all
950                  * white space. The setup of the white space
951                  * configuration for the next block is done else where
952                  */
953                 flags |= XDF_IGNORE_WHITESPACE;
954
955         return !xdiff_compare_lines(a->es->line, a->es->len,
956                                     b->es->line, b->es->len,
957                                     flags);
958 }
959
960 static struct moved_entry *prepare_entry(struct diff_options *o,
961                                          int line_no)
962 {
963         struct moved_entry *ret = xmalloc(sizeof(*ret));
964         struct emitted_diff_symbol *l = &o->emitted_symbols->buf[line_no];
965         unsigned flags = o->color_moved_ws_handling & XDF_WHITESPACE_FLAGS;
966
967         ret->ent.hash = xdiff_hash_string(l->line, l->len, flags);
968         ret->es = l;
969         ret->next_line = NULL;
970
971         return ret;
972 }
973
974 static void add_lines_to_move_detection(struct diff_options *o,
975                                         struct hashmap *add_lines,
976                                         struct hashmap *del_lines)
977 {
978         struct moved_entry *prev_line = NULL;
979
980         int n;
981         for (n = 0; n < o->emitted_symbols->nr; n++) {
982                 struct hashmap *hm;
983                 struct moved_entry *key;
984
985                 switch (o->emitted_symbols->buf[n].s) {
986                 case DIFF_SYMBOL_PLUS:
987                         hm = add_lines;
988                         break;
989                 case DIFF_SYMBOL_MINUS:
990                         hm = del_lines;
991                         break;
992                 default:
993                         prev_line = NULL;
994                         continue;
995                 }
996
997                 if (o->color_moved_ws_handling &
998                     COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
999                         fill_es_indent_data(&o->emitted_symbols->buf[n]);
1000                 key = prepare_entry(o, n);
1001                 if (prev_line && prev_line->es->s == o->emitted_symbols->buf[n].s)
1002                         prev_line->next_line = key;
1003
1004                 hashmap_add(hm, key);
1005                 prev_line = key;
1006         }
1007 }
1008
1009 static void pmb_advance_or_null(struct diff_options *o,
1010                                 struct moved_entry *match,
1011                                 struct hashmap *hm,
1012                                 struct moved_block *pmb,
1013                                 int pmb_nr)
1014 {
1015         int i;
1016         for (i = 0; i < pmb_nr; i++) {
1017                 struct moved_entry *prev = pmb[i].match;
1018                 struct moved_entry *cur = (prev && prev->next_line) ?
1019                                 prev->next_line : NULL;
1020                 if (cur && !hm->cmpfn(o, cur, match, NULL)) {
1021                         pmb[i].match = cur;
1022                 } else {
1023                         pmb[i].match = NULL;
1024                 }
1025         }
1026 }
1027
1028 static void pmb_advance_or_null_multi_match(struct diff_options *o,
1029                                             struct moved_entry *match,
1030                                             struct hashmap *hm,
1031                                             struct moved_block *pmb,
1032                                             int pmb_nr, int n)
1033 {
1034         int i;
1035         char *got_match = xcalloc(1, pmb_nr);
1036
1037         for (; match; match = hashmap_get_next(hm, match)) {
1038                 for (i = 0; i < pmb_nr; i++) {
1039                         struct moved_entry *prev = pmb[i].match;
1040                         struct moved_entry *cur = (prev && prev->next_line) ?
1041                                         prev->next_line : NULL;
1042                         if (!cur)
1043                                 continue;
1044                         if (!cmp_in_block_with_wsd(o, cur, match, &pmb[i], n))
1045                                 got_match[i] |= 1;
1046                 }
1047         }
1048
1049         for (i = 0; i < pmb_nr; i++) {
1050                 if (got_match[i]) {
1051                         /* Advance to the next line */
1052                         pmb[i].match = pmb[i].match->next_line;
1053                 } else {
1054                         moved_block_clear(&pmb[i]);
1055                 }
1056         }
1057
1058         free(got_match);
1059 }
1060
1061 static int shrink_potential_moved_blocks(struct moved_block *pmb,
1062                                          int pmb_nr)
1063 {
1064         int lp, rp;
1065
1066         /* Shrink the set of potential block to the remaining running */
1067         for (lp = 0, rp = pmb_nr - 1; lp <= rp;) {
1068                 while (lp < pmb_nr && pmb[lp].match)
1069                         lp++;
1070                 /* lp points at the first NULL now */
1071
1072                 while (rp > -1 && !pmb[rp].match)
1073                         rp--;
1074                 /* rp points at the last non-NULL */
1075
1076                 if (lp < pmb_nr && rp > -1 && lp < rp) {
1077                         pmb[lp] = pmb[rp];
1078                         memset(&pmb[rp], 0, sizeof(pmb[rp]));
1079                         rp--;
1080                         lp++;
1081                 }
1082         }
1083
1084         /* Remember the number of running sets */
1085         return rp + 1;
1086 }
1087
1088 /*
1089  * If o->color_moved is COLOR_MOVED_PLAIN, this function does nothing.
1090  *
1091  * Otherwise, if the last block has fewer alphanumeric characters than
1092  * COLOR_MOVED_MIN_ALNUM_COUNT, unset DIFF_SYMBOL_MOVED_LINE on all lines in
1093  * that block.
1094  *
1095  * The last block consists of the (n - block_length)'th line up to but not
1096  * including the nth line.
1097  *
1098  * Returns 0 if the last block is empty or is unset by this function, non zero
1099  * otherwise.
1100  *
1101  * NEEDSWORK: This uses the same heuristic as blame_entry_score() in blame.c.
1102  * Think of a way to unify them.
1103  */
1104 static int adjust_last_block(struct diff_options *o, int n, int block_length)
1105 {
1106         int i, alnum_count = 0;
1107         if (o->color_moved == COLOR_MOVED_PLAIN)
1108                 return block_length;
1109         for (i = 1; i < block_length + 1; i++) {
1110                 const char *c = o->emitted_symbols->buf[n - i].line;
1111                 for (; *c; c++) {
1112                         if (!isalnum(*c))
1113                                 continue;
1114                         alnum_count++;
1115                         if (alnum_count >= COLOR_MOVED_MIN_ALNUM_COUNT)
1116                                 return 1;
1117                 }
1118         }
1119         for (i = 1; i < block_length + 1; i++)
1120                 o->emitted_symbols->buf[n - i].flags &= ~DIFF_SYMBOL_MOVED_LINE;
1121         return 0;
1122 }
1123
1124 /* Find blocks of moved code, delegate actual coloring decision to helper */
1125 static void mark_color_as_moved(struct diff_options *o,
1126                                 struct hashmap *add_lines,
1127                                 struct hashmap *del_lines)
1128 {
1129         struct moved_block *pmb = NULL; /* potentially moved blocks */
1130         int pmb_nr = 0, pmb_alloc = 0;
1131         int n, flipped_block = 0, block_length = 0;
1132
1133
1134         for (n = 0; n < o->emitted_symbols->nr; n++) {
1135                 struct hashmap *hm = NULL;
1136                 struct moved_entry *key;
1137                 struct moved_entry *match = NULL;
1138                 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1139                 enum diff_symbol last_symbol = 0;
1140
1141                 switch (l->s) {
1142                 case DIFF_SYMBOL_PLUS:
1143                         hm = del_lines;
1144                         key = prepare_entry(o, n);
1145                         match = hashmap_get(hm, key, NULL);
1146                         free(key);
1147                         break;
1148                 case DIFF_SYMBOL_MINUS:
1149                         hm = add_lines;
1150                         key = prepare_entry(o, n);
1151                         match = hashmap_get(hm, key, NULL);
1152                         free(key);
1153                         break;
1154                 default:
1155                         flipped_block = 0;
1156                 }
1157
1158                 if (!match) {
1159                         int i;
1160
1161                         adjust_last_block(o, n, block_length);
1162                         for(i = 0; i < pmb_nr; i++)
1163                                 moved_block_clear(&pmb[i]);
1164                         pmb_nr = 0;
1165                         block_length = 0;
1166                         flipped_block = 0;
1167                         last_symbol = l->s;
1168                         continue;
1169                 }
1170
1171                 if (o->color_moved == COLOR_MOVED_PLAIN) {
1172                         last_symbol = l->s;
1173                         l->flags |= DIFF_SYMBOL_MOVED_LINE;
1174                         continue;
1175                 }
1176
1177                 if (o->color_moved_ws_handling &
1178                     COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
1179                         pmb_advance_or_null_multi_match(o, match, hm, pmb, pmb_nr, n);
1180                 else
1181                         pmb_advance_or_null(o, match, hm, pmb, pmb_nr);
1182
1183                 pmb_nr = shrink_potential_moved_blocks(pmb, pmb_nr);
1184
1185                 if (pmb_nr == 0) {
1186                         /*
1187                          * The current line is the start of a new block.
1188                          * Setup the set of potential blocks.
1189                          */
1190                         for (; match; match = hashmap_get_next(hm, match)) {
1191                                 ALLOC_GROW(pmb, pmb_nr + 1, pmb_alloc);
1192                                 if (o->color_moved_ws_handling &
1193                                     COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE) {
1194                                         if (compute_ws_delta(l, match->es,
1195                                                              &pmb[pmb_nr].wsd))
1196                                                 pmb[pmb_nr++].match = match;
1197                                 } else {
1198                                         pmb[pmb_nr].wsd = 0;
1199                                         pmb[pmb_nr++].match = match;
1200                                 }
1201                         }
1202
1203                         if (adjust_last_block(o, n, block_length) &&
1204                             pmb_nr && last_symbol != l->s)
1205                                 flipped_block = (flipped_block + 1) % 2;
1206                         else
1207                                 flipped_block = 0;
1208
1209                         block_length = 0;
1210                 }
1211
1212                 if (pmb_nr) {
1213                         block_length++;
1214                         l->flags |= DIFF_SYMBOL_MOVED_LINE;
1215                         if (flipped_block && o->color_moved != COLOR_MOVED_BLOCKS)
1216                                 l->flags |= DIFF_SYMBOL_MOVED_LINE_ALT;
1217                 }
1218                 last_symbol = l->s;
1219         }
1220         adjust_last_block(o, n, block_length);
1221
1222         for(n = 0; n < pmb_nr; n++)
1223                 moved_block_clear(&pmb[n]);
1224         free(pmb);
1225 }
1226
1227 #define DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK \
1228   (DIFF_SYMBOL_MOVED_LINE | DIFF_SYMBOL_MOVED_LINE_ALT)
1229 static void dim_moved_lines(struct diff_options *o)
1230 {
1231         int n;
1232         for (n = 0; n < o->emitted_symbols->nr; n++) {
1233                 struct emitted_diff_symbol *prev = (n != 0) ?
1234                                 &o->emitted_symbols->buf[n - 1] : NULL;
1235                 struct emitted_diff_symbol *l = &o->emitted_symbols->buf[n];
1236                 struct emitted_diff_symbol *next =
1237                                 (n < o->emitted_symbols->nr - 1) ?
1238                                 &o->emitted_symbols->buf[n + 1] : NULL;
1239
1240                 /* Not a plus or minus line? */
1241                 if (l->s != DIFF_SYMBOL_PLUS && l->s != DIFF_SYMBOL_MINUS)
1242                         continue;
1243
1244                 /* Not a moved line? */
1245                 if (!(l->flags & DIFF_SYMBOL_MOVED_LINE))
1246                         continue;
1247
1248                 /*
1249                  * If prev or next are not a plus or minus line,
1250                  * pretend they don't exist
1251                  */
1252                 if (prev && prev->s != DIFF_SYMBOL_PLUS &&
1253                             prev->s != DIFF_SYMBOL_MINUS)
1254                         prev = NULL;
1255                 if (next && next->s != DIFF_SYMBOL_PLUS &&
1256                             next->s != DIFF_SYMBOL_MINUS)
1257                         next = NULL;
1258
1259                 /* Inside a block? */
1260                 if ((prev &&
1261                     (prev->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1262                     (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK)) &&
1263                     (next &&
1264                     (next->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK) ==
1265                     (l->flags & DIFF_SYMBOL_MOVED_LINE_ZEBRA_MASK))) {
1266                         l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1267                         continue;
1268                 }
1269
1270                 /* Check if we are at an interesting bound: */
1271                 if (prev && (prev->flags & DIFF_SYMBOL_MOVED_LINE) &&
1272                     (prev->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1273                        (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1274                         continue;
1275                 if (next && (next->flags & DIFF_SYMBOL_MOVED_LINE) &&
1276                     (next->flags & DIFF_SYMBOL_MOVED_LINE_ALT) !=
1277                        (l->flags & DIFF_SYMBOL_MOVED_LINE_ALT))
1278                         continue;
1279
1280                 /*
1281                  * The boundary to prev and next are not interesting,
1282                  * so this line is not interesting as a whole
1283                  */
1284                 l->flags |= DIFF_SYMBOL_MOVED_LINE_UNINTERESTING;
1285         }
1286 }
1287
1288 static void emit_line_ws_markup(struct diff_options *o,
1289                                 const char *set_sign, const char *set,
1290                                 const char *reset,
1291                                 int sign_index, const char *line, int len,
1292                                 unsigned ws_rule, int blank_at_eof)
1293 {
1294         const char *ws = NULL;
1295         int sign = o->output_indicators[sign_index];
1296
1297         if (o->ws_error_highlight & ws_rule) {
1298                 ws = diff_get_color_opt(o, DIFF_WHITESPACE);
1299                 if (!*ws)
1300                         ws = NULL;
1301         }
1302
1303         if (!ws && !set_sign)
1304                 emit_line_0(o, set, NULL, 0, reset, sign, line, len);
1305         else if (!ws) {
1306                 emit_line_0(o, set_sign, set, !!set_sign, reset, sign, line, len);
1307         } else if (blank_at_eof)
1308                 /* Blank line at EOF - paint '+' as well */
1309                 emit_line_0(o, ws, NULL, 0, reset, sign, line, len);
1310         else {
1311                 /* Emit just the prefix, then the rest. */
1312                 emit_line_0(o, set_sign ? set_sign : set, NULL, !!set_sign, reset,
1313                             sign, "", 0);
1314                 ws_check_emit(line, len, ws_rule,
1315                               o->file, set, reset, ws);
1316         }
1317 }
1318
1319 static void emit_diff_symbol_from_struct(struct diff_options *o,
1320                                          struct emitted_diff_symbol *eds)
1321 {
1322         static const char *nneof = " No newline at end of file\n";
1323         const char *context, *reset, *set, *set_sign, *meta, *fraginfo;
1324         struct strbuf sb = STRBUF_INIT;
1325
1326         enum diff_symbol s = eds->s;
1327         const char *line = eds->line;
1328         int len = eds->len;
1329         unsigned flags = eds->flags;
1330
1331         switch (s) {
1332         case DIFF_SYMBOL_NO_LF_EOF:
1333                 context = diff_get_color_opt(o, DIFF_CONTEXT);
1334                 reset = diff_get_color_opt(o, DIFF_RESET);
1335                 putc('\n', o->file);
1336                 emit_line_0(o, context, NULL, 0, reset, '\\',
1337                             nneof, strlen(nneof));
1338                 break;
1339         case DIFF_SYMBOL_SUBMODULE_HEADER:
1340         case DIFF_SYMBOL_SUBMODULE_ERROR:
1341         case DIFF_SYMBOL_SUBMODULE_PIPETHROUGH:
1342         case DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES:
1343         case DIFF_SYMBOL_SUMMARY:
1344         case DIFF_SYMBOL_STATS_LINE:
1345         case DIFF_SYMBOL_BINARY_DIFF_BODY:
1346         case DIFF_SYMBOL_CONTEXT_FRAGINFO:
1347                 emit_line(o, "", "", line, len);
1348                 break;
1349         case DIFF_SYMBOL_CONTEXT_INCOMPLETE:
1350         case DIFF_SYMBOL_CONTEXT_MARKER:
1351                 context = diff_get_color_opt(o, DIFF_CONTEXT);
1352                 reset = diff_get_color_opt(o, DIFF_RESET);
1353                 emit_line(o, context, reset, line, len);
1354                 break;
1355         case DIFF_SYMBOL_SEPARATOR:
1356                 fprintf(o->file, "%s%c",
1357                         diff_line_prefix(o),
1358                         o->line_termination);
1359                 break;
1360         case DIFF_SYMBOL_CONTEXT:
1361                 set = diff_get_color_opt(o, DIFF_CONTEXT);
1362                 reset = diff_get_color_opt(o, DIFF_RESET);
1363                 set_sign = NULL;
1364                 if (o->flags.dual_color_diffed_diffs) {
1365                         char c = !len ? 0 : line[0];
1366
1367                         if (c == '+')
1368                                 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1369                         else if (c == '@')
1370                                 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1371                         else if (c == '-')
1372                                 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1373                 }
1374                 emit_line_ws_markup(o, set_sign, set, reset,
1375                                     OUTPUT_INDICATOR_CONTEXT, line, len,
1376                                     flags & (DIFF_SYMBOL_CONTENT_WS_MASK), 0);
1377                 break;
1378         case DIFF_SYMBOL_PLUS:
1379                 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1380                                  DIFF_SYMBOL_MOVED_LINE_ALT |
1381                                  DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1382                 case DIFF_SYMBOL_MOVED_LINE |
1383                      DIFF_SYMBOL_MOVED_LINE_ALT |
1384                      DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1385                         set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT_DIM);
1386                         break;
1387                 case DIFF_SYMBOL_MOVED_LINE |
1388                      DIFF_SYMBOL_MOVED_LINE_ALT:
1389                         set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_ALT);
1390                         break;
1391                 case DIFF_SYMBOL_MOVED_LINE |
1392                      DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1393                         set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED_DIM);
1394                         break;
1395                 case DIFF_SYMBOL_MOVED_LINE:
1396                         set = diff_get_color_opt(o, DIFF_FILE_NEW_MOVED);
1397                         break;
1398                 default:
1399                         set = diff_get_color_opt(o, DIFF_FILE_NEW);
1400                 }
1401                 reset = diff_get_color_opt(o, DIFF_RESET);
1402                 if (!o->flags.dual_color_diffed_diffs)
1403                         set_sign = NULL;
1404                 else {
1405                         char c = !len ? 0 : line[0];
1406
1407                         set_sign = set;
1408                         if (c == '-')
1409                                 set = diff_get_color_opt(o, DIFF_FILE_OLD_BOLD);
1410                         else if (c == '@')
1411                                 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1412                         else if (c == '+')
1413                                 set = diff_get_color_opt(o, DIFF_FILE_NEW_BOLD);
1414                         else
1415                                 set = diff_get_color_opt(o, DIFF_CONTEXT_BOLD);
1416                         flags &= ~DIFF_SYMBOL_CONTENT_WS_MASK;
1417                 }
1418                 emit_line_ws_markup(o, set_sign, set, reset,
1419                                     OUTPUT_INDICATOR_NEW, line, len,
1420                                     flags & DIFF_SYMBOL_CONTENT_WS_MASK,
1421                                     flags & DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF);
1422                 break;
1423         case DIFF_SYMBOL_MINUS:
1424                 switch (flags & (DIFF_SYMBOL_MOVED_LINE |
1425                                  DIFF_SYMBOL_MOVED_LINE_ALT |
1426                                  DIFF_SYMBOL_MOVED_LINE_UNINTERESTING)) {
1427                 case DIFF_SYMBOL_MOVED_LINE |
1428                      DIFF_SYMBOL_MOVED_LINE_ALT |
1429                      DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1430                         set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT_DIM);
1431                         break;
1432                 case DIFF_SYMBOL_MOVED_LINE |
1433                      DIFF_SYMBOL_MOVED_LINE_ALT:
1434                         set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_ALT);
1435                         break;
1436                 case DIFF_SYMBOL_MOVED_LINE |
1437                      DIFF_SYMBOL_MOVED_LINE_UNINTERESTING:
1438                         set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED_DIM);
1439                         break;
1440                 case DIFF_SYMBOL_MOVED_LINE:
1441                         set = diff_get_color_opt(o, DIFF_FILE_OLD_MOVED);
1442                         break;
1443                 default:
1444                         set = diff_get_color_opt(o, DIFF_FILE_OLD);
1445                 }
1446                 reset = diff_get_color_opt(o, DIFF_RESET);
1447                 if (!o->flags.dual_color_diffed_diffs)
1448                         set_sign = NULL;
1449                 else {
1450                         char c = !len ? 0 : line[0];
1451
1452                         set_sign = set;
1453                         if (c == '+')
1454                                 set = diff_get_color_opt(o, DIFF_FILE_NEW_DIM);
1455                         else if (c == '@')
1456                                 set = diff_get_color_opt(o, DIFF_FRAGINFO);
1457                         else if (c == '-')
1458                                 set = diff_get_color_opt(o, DIFF_FILE_OLD_DIM);
1459                         else
1460                                 set = diff_get_color_opt(o, DIFF_CONTEXT_DIM);
1461                 }
1462                 emit_line_ws_markup(o, set_sign, set, reset,
1463                                     OUTPUT_INDICATOR_OLD, line, len,
1464                                     flags & DIFF_SYMBOL_CONTENT_WS_MASK, 0);
1465                 break;
1466         case DIFF_SYMBOL_WORDS_PORCELAIN:
1467                 context = diff_get_color_opt(o, DIFF_CONTEXT);
1468                 reset = diff_get_color_opt(o, DIFF_RESET);
1469                 emit_line(o, context, reset, line, len);
1470                 fputs("~\n", o->file);
1471                 break;
1472         case DIFF_SYMBOL_WORDS:
1473                 context = diff_get_color_opt(o, DIFF_CONTEXT);
1474                 reset = diff_get_color_opt(o, DIFF_RESET);
1475                 /*
1476                  * Skip the prefix character, if any.  With
1477                  * diff_suppress_blank_empty, there may be
1478                  * none.
1479                  */
1480                 if (line[0] != '\n') {
1481                         line++;
1482                         len--;
1483                 }
1484                 emit_line(o, context, reset, line, len);
1485                 break;
1486         case DIFF_SYMBOL_FILEPAIR_PLUS:
1487                 meta = diff_get_color_opt(o, DIFF_METAINFO);
1488                 reset = diff_get_color_opt(o, DIFF_RESET);
1489                 fprintf(o->file, "%s%s+++ %s%s%s\n", diff_line_prefix(o), meta,
1490                         line, reset,
1491                         strchr(line, ' ') ? "\t" : "");
1492                 break;
1493         case DIFF_SYMBOL_FILEPAIR_MINUS:
1494                 meta = diff_get_color_opt(o, DIFF_METAINFO);
1495                 reset = diff_get_color_opt(o, DIFF_RESET);
1496                 fprintf(o->file, "%s%s--- %s%s%s\n", diff_line_prefix(o), meta,
1497                         line, reset,
1498                         strchr(line, ' ') ? "\t" : "");
1499                 break;
1500         case DIFF_SYMBOL_BINARY_FILES:
1501         case DIFF_SYMBOL_HEADER:
1502                 fprintf(o->file, "%s", line);
1503                 break;
1504         case DIFF_SYMBOL_BINARY_DIFF_HEADER:
1505                 fprintf(o->file, "%sGIT binary patch\n", diff_line_prefix(o));
1506                 break;
1507         case DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA:
1508                 fprintf(o->file, "%sdelta %s\n", diff_line_prefix(o), line);
1509                 break;
1510         case DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL:
1511                 fprintf(o->file, "%sliteral %s\n", diff_line_prefix(o), line);
1512                 break;
1513         case DIFF_SYMBOL_BINARY_DIFF_FOOTER:
1514                 fputs(diff_line_prefix(o), o->file);
1515                 fputc('\n', o->file);
1516                 break;
1517         case DIFF_SYMBOL_REWRITE_DIFF:
1518                 fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
1519                 reset = diff_get_color_opt(o, DIFF_RESET);
1520                 emit_line(o, fraginfo, reset, line, len);
1521                 break;
1522         case DIFF_SYMBOL_SUBMODULE_ADD:
1523                 set = diff_get_color_opt(o, DIFF_FILE_NEW);
1524                 reset = diff_get_color_opt(o, DIFF_RESET);
1525                 emit_line(o, set, reset, line, len);
1526                 break;
1527         case DIFF_SYMBOL_SUBMODULE_DEL:
1528                 set = diff_get_color_opt(o, DIFF_FILE_OLD);
1529                 reset = diff_get_color_opt(o, DIFF_RESET);
1530                 emit_line(o, set, reset, line, len);
1531                 break;
1532         case DIFF_SYMBOL_SUBMODULE_UNTRACKED:
1533                 fprintf(o->file, "%sSubmodule %s contains untracked content\n",
1534                         diff_line_prefix(o), line);
1535                 break;
1536         case DIFF_SYMBOL_SUBMODULE_MODIFIED:
1537                 fprintf(o->file, "%sSubmodule %s contains modified content\n",
1538                         diff_line_prefix(o), line);
1539                 break;
1540         case DIFF_SYMBOL_STATS_SUMMARY_NO_FILES:
1541                 emit_line(o, "", "", " 0 files changed\n",
1542                           strlen(" 0 files changed\n"));
1543                 break;
1544         case DIFF_SYMBOL_STATS_SUMMARY_ABBREV:
1545                 emit_line(o, "", "", " ...\n", strlen(" ...\n"));
1546                 break;
1547         case DIFF_SYMBOL_WORD_DIFF:
1548                 fprintf(o->file, "%.*s", len, line);
1549                 break;
1550         case DIFF_SYMBOL_STAT_SEP:
1551                 fputs(o->stat_sep, o->file);
1552                 break;
1553         default:
1554                 BUG("unknown diff symbol");
1555         }
1556         strbuf_release(&sb);
1557 }
1558
1559 static void emit_diff_symbol(struct diff_options *o, enum diff_symbol s,
1560                              const char *line, int len, unsigned flags)
1561 {
1562         struct emitted_diff_symbol e = {line, len, flags, 0, 0, s};
1563
1564         if (o->emitted_symbols)
1565                 append_emitted_diff_symbol(o, &e);
1566         else
1567                 emit_diff_symbol_from_struct(o, &e);
1568 }
1569
1570 void diff_emit_submodule_del(struct diff_options *o, const char *line)
1571 {
1572         emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_DEL, line, strlen(line), 0);
1573 }
1574
1575 void diff_emit_submodule_add(struct diff_options *o, const char *line)
1576 {
1577         emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ADD, line, strlen(line), 0);
1578 }
1579
1580 void diff_emit_submodule_untracked(struct diff_options *o, const char *path)
1581 {
1582         emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_UNTRACKED,
1583                          path, strlen(path), 0);
1584 }
1585
1586 void diff_emit_submodule_modified(struct diff_options *o, const char *path)
1587 {
1588         emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_MODIFIED,
1589                          path, strlen(path), 0);
1590 }
1591
1592 void diff_emit_submodule_header(struct diff_options *o, const char *header)
1593 {
1594         emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_HEADER,
1595                          header, strlen(header), 0);
1596 }
1597
1598 void diff_emit_submodule_error(struct diff_options *o, const char *err)
1599 {
1600         emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_ERROR, err, strlen(err), 0);
1601 }
1602
1603 void diff_emit_submodule_pipethrough(struct diff_options *o,
1604                                      const char *line, int len)
1605 {
1606         emit_diff_symbol(o, DIFF_SYMBOL_SUBMODULE_PIPETHROUGH, line, len, 0);
1607 }
1608
1609 static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
1610 {
1611         if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
1612               ecbdata->blank_at_eof_in_preimage &&
1613               ecbdata->blank_at_eof_in_postimage &&
1614               ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
1615               ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
1616                 return 0;
1617         return ws_blank_line(line, len, ecbdata->ws_rule);
1618 }
1619
1620 static void emit_add_line(struct emit_callback *ecbdata,
1621                           const char *line, int len)
1622 {
1623         unsigned flags = WSEH_NEW | ecbdata->ws_rule;
1624         if (new_blank_line_at_eof(ecbdata, line, len))
1625                 flags |= DIFF_SYMBOL_CONTENT_BLANK_LINE_EOF;
1626
1627         emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_PLUS, line, len, flags);
1628 }
1629
1630 static void emit_del_line(struct emit_callback *ecbdata,
1631                           const char *line, int len)
1632 {
1633         unsigned flags = WSEH_OLD | ecbdata->ws_rule;
1634         emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_MINUS, line, len, flags);
1635 }
1636
1637 static void emit_context_line(struct emit_callback *ecbdata,
1638                               const char *line, int len)
1639 {
1640         unsigned flags = WSEH_CONTEXT | ecbdata->ws_rule;
1641         emit_diff_symbol(ecbdata->opt, DIFF_SYMBOL_CONTEXT, line, len, flags);
1642 }
1643
1644 static void emit_hunk_header(struct emit_callback *ecbdata,
1645                              const char *line, int len)
1646 {
1647         const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
1648         const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
1649         const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
1650         const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1651         const char *reverse = ecbdata->color_diff ? GIT_COLOR_REVERSE : "";
1652         static const char atat[2] = { '@', '@' };
1653         const char *cp, *ep;
1654         struct strbuf msgbuf = STRBUF_INIT;
1655         int org_len = len;
1656         int i = 1;
1657
1658         /*
1659          * As a hunk header must begin with "@@ -<old>, +<new> @@",
1660          * it always is at least 10 bytes long.
1661          */
1662         if (len < 10 ||
1663             memcmp(line, atat, 2) ||
1664             !(ep = memmem(line + 2, len - 2, atat, 2))) {
1665                 emit_diff_symbol(ecbdata->opt,
1666                                  DIFF_SYMBOL_CONTEXT_MARKER, line, len, 0);
1667                 return;
1668         }
1669         ep += 2; /* skip over @@ */
1670
1671         /* The hunk header in fraginfo color */
1672         if (ecbdata->opt->flags.dual_color_diffed_diffs)
1673                 strbuf_addstr(&msgbuf, reverse);
1674         strbuf_addstr(&msgbuf, frag);
1675         strbuf_add(&msgbuf, line, ep - line);
1676         strbuf_addstr(&msgbuf, reset);
1677
1678         /*
1679          * trailing "\r\n"
1680          */
1681         for ( ; i < 3; i++)
1682                 if (line[len - i] == '\r' || line[len - i] == '\n')
1683                         len--;
1684
1685         /* blank before the func header */
1686         for (cp = ep; ep - line < len; ep++)
1687                 if (*ep != ' ' && *ep != '\t')
1688                         break;
1689         if (ep != cp) {
1690                 strbuf_addstr(&msgbuf, context);
1691                 strbuf_add(&msgbuf, cp, ep - cp);
1692                 strbuf_addstr(&msgbuf, reset);
1693         }
1694
1695         if (ep < line + len) {
1696                 strbuf_addstr(&msgbuf, func);
1697                 strbuf_add(&msgbuf, ep, line + len - ep);
1698                 strbuf_addstr(&msgbuf, reset);
1699         }
1700
1701         strbuf_add(&msgbuf, line + len, org_len - len);
1702         strbuf_complete_line(&msgbuf);
1703         emit_diff_symbol(ecbdata->opt,
1704                          DIFF_SYMBOL_CONTEXT_FRAGINFO, msgbuf.buf, msgbuf.len, 0);
1705         strbuf_release(&msgbuf);
1706 }
1707
1708 static struct diff_tempfile *claim_diff_tempfile(void)
1709 {
1710         int i;
1711         for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
1712                 if (!diff_temp[i].name)
1713                         return diff_temp + i;
1714         BUG("diff is failing to clean up its tempfiles");
1715 }
1716
1717 static void remove_tempfile(void)
1718 {
1719         int i;
1720         for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
1721                 if (is_tempfile_active(diff_temp[i].tempfile))
1722                         delete_tempfile(&diff_temp[i].tempfile);
1723                 diff_temp[i].name = NULL;
1724         }
1725 }
1726
1727 static void add_line_count(struct strbuf *out, int count)
1728 {
1729         switch (count) {
1730         case 0:
1731                 strbuf_addstr(out, "0,0");
1732                 break;
1733         case 1:
1734                 strbuf_addstr(out, "1");
1735                 break;
1736         default:
1737                 strbuf_addf(out, "1,%d", count);
1738                 break;
1739         }
1740 }
1741
1742 static void emit_rewrite_lines(struct emit_callback *ecb,
1743                                int prefix, const char *data, int size)
1744 {
1745         const char *endp = NULL;
1746
1747         while (0 < size) {
1748                 int len;
1749
1750                 endp = memchr(data, '\n', size);
1751                 len = endp ? (endp - data + 1) : size;
1752                 if (prefix != '+') {
1753                         ecb->lno_in_preimage++;
1754                         emit_del_line(ecb, data, len);
1755                 } else {
1756                         ecb->lno_in_postimage++;
1757                         emit_add_line(ecb, data, len);
1758                 }
1759                 size -= len;
1760                 data += len;
1761         }
1762         if (!endp)
1763                 emit_diff_symbol(ecb->opt, DIFF_SYMBOL_NO_LF_EOF, NULL, 0, 0);
1764 }
1765
1766 static void emit_rewrite_diff(const char *name_a,
1767                               const char *name_b,
1768                               struct diff_filespec *one,
1769                               struct diff_filespec *two,
1770                               struct userdiff_driver *textconv_one,
1771                               struct userdiff_driver *textconv_two,
1772                               struct diff_options *o)
1773 {
1774         int lc_a, lc_b;
1775         static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
1776         const char *a_prefix, *b_prefix;
1777         char *data_one, *data_two;
1778         size_t size_one, size_two;
1779         struct emit_callback ecbdata;
1780         struct strbuf out = STRBUF_INIT;
1781
1782         if (diff_mnemonic_prefix && o->flags.reverse_diff) {
1783                 a_prefix = o->b_prefix;
1784                 b_prefix = o->a_prefix;
1785         } else {
1786                 a_prefix = o->a_prefix;
1787                 b_prefix = o->b_prefix;
1788         }
1789
1790         name_a += (*name_a == '/');
1791         name_b += (*name_b == '/');
1792
1793         strbuf_reset(&a_name);
1794         strbuf_reset(&b_name);
1795         quote_two_c_style(&a_name, a_prefix, name_a, 0);
1796         quote_two_c_style(&b_name, b_prefix, name_b, 0);
1797
1798         size_one = fill_textconv(o->repo, textconv_one, one, &data_one);
1799         size_two = fill_textconv(o->repo, textconv_two, two, &data_two);
1800
1801         memset(&ecbdata, 0, sizeof(ecbdata));
1802         ecbdata.color_diff = want_color(o->use_color);
1803         ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
1804         ecbdata.opt = o;
1805         if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
1806                 mmfile_t mf1, mf2;
1807                 mf1.ptr = (char *)data_one;
1808                 mf2.ptr = (char *)data_two;
1809                 mf1.size = size_one;
1810                 mf2.size = size_two;
1811                 check_blank_at_eof(&mf1, &mf2, &ecbdata);
1812         }
1813         ecbdata.lno_in_preimage = 1;
1814         ecbdata.lno_in_postimage = 1;
1815
1816         lc_a = count_lines(data_one, size_one);
1817         lc_b = count_lines(data_two, size_two);
1818
1819         emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
1820                          a_name.buf, a_name.len, 0);
1821         emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
1822                          b_name.buf, b_name.len, 0);
1823
1824         strbuf_addstr(&out, "@@ -");
1825         if (!o->irreversible_delete)
1826                 add_line_count(&out, lc_a);
1827         else
1828                 strbuf_addstr(&out, "?,?");
1829         strbuf_addstr(&out, " +");
1830         add_line_count(&out, lc_b);
1831         strbuf_addstr(&out, " @@\n");
1832         emit_diff_symbol(o, DIFF_SYMBOL_REWRITE_DIFF, out.buf, out.len, 0);
1833         strbuf_release(&out);
1834
1835         if (lc_a && !o->irreversible_delete)
1836                 emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
1837         if (lc_b)
1838                 emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
1839         if (textconv_one)
1840                 free((char *)data_one);
1841         if (textconv_two)
1842                 free((char *)data_two);
1843 }
1844
1845 struct diff_words_buffer {
1846         mmfile_t text;
1847         unsigned long alloc;
1848         struct diff_words_orig {
1849                 const char *begin, *end;
1850         } *orig;
1851         int orig_nr, orig_alloc;
1852 };
1853
1854 static void diff_words_append(char *line, unsigned long len,
1855                 struct diff_words_buffer *buffer)
1856 {
1857         ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
1858         line++;
1859         len--;
1860         memcpy(buffer->text.ptr + buffer->text.size, line, len);
1861         buffer->text.size += len;
1862         buffer->text.ptr[buffer->text.size] = '\0';
1863 }
1864
1865 struct diff_words_style_elem {
1866         const char *prefix;
1867         const char *suffix;
1868         const char *color; /* NULL; filled in by the setup code if
1869                             * color is enabled */
1870 };
1871
1872 struct diff_words_style {
1873         enum diff_words_type type;
1874         struct diff_words_style_elem new_word, old_word, ctx;
1875         const char *newline;
1876 };
1877
1878 static struct diff_words_style diff_words_styles[] = {
1879         { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
1880         { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
1881         { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
1882 };
1883
1884 struct diff_words_data {
1885         struct diff_words_buffer minus, plus;
1886         const char *current_plus;
1887         int last_minus;
1888         struct diff_options *opt;
1889         regex_t *word_regex;
1890         enum diff_words_type type;
1891         struct diff_words_style *style;
1892 };
1893
1894 static int fn_out_diff_words_write_helper(struct diff_options *o,
1895                                           struct diff_words_style_elem *st_el,
1896                                           const char *newline,
1897                                           size_t count, const char *buf)
1898 {
1899         int print = 0;
1900         struct strbuf sb = STRBUF_INIT;
1901
1902         while (count) {
1903                 char *p = memchr(buf, '\n', count);
1904                 if (print)
1905                         strbuf_addstr(&sb, diff_line_prefix(o));
1906
1907                 if (p != buf) {
1908                         const char *reset = st_el->color && *st_el->color ?
1909                                             GIT_COLOR_RESET : NULL;
1910                         if (st_el->color && *st_el->color)
1911                                 strbuf_addstr(&sb, st_el->color);
1912                         strbuf_addstr(&sb, st_el->prefix);
1913                         strbuf_add(&sb, buf, p ? p - buf : count);
1914                         strbuf_addstr(&sb, st_el->suffix);
1915                         if (reset)
1916                                 strbuf_addstr(&sb, reset);
1917                 }
1918                 if (!p)
1919                         goto out;
1920
1921                 strbuf_addstr(&sb, newline);
1922                 count -= p + 1 - buf;
1923                 buf = p + 1;
1924                 print = 1;
1925                 if (count) {
1926                         emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1927                                          sb.buf, sb.len, 0);
1928                         strbuf_reset(&sb);
1929                 }
1930         }
1931
1932 out:
1933         if (sb.len)
1934                 emit_diff_symbol(o, DIFF_SYMBOL_WORD_DIFF,
1935                                  sb.buf, sb.len, 0);
1936         strbuf_release(&sb);
1937         return 0;
1938 }
1939
1940 /*
1941  * '--color-words' algorithm can be described as:
1942  *
1943  *   1. collect the minus/plus lines of a diff hunk, divided into
1944  *      minus-lines and plus-lines;
1945  *
1946  *   2. break both minus-lines and plus-lines into words and
1947  *      place them into two mmfile_t with one word for each line;
1948  *
1949  *   3. use xdiff to run diff on the two mmfile_t to get the words level diff;
1950  *
1951  * And for the common parts of the both file, we output the plus side text.
1952  * diff_words->current_plus is used to trace the current position of the plus file
1953  * which printed. diff_words->last_minus is used to trace the last minus word
1954  * printed.
1955  *
1956  * For '--graph' to work with '--color-words', we need to output the graph prefix
1957  * on each line of color words output. Generally, there are two conditions on
1958  * which we should output the prefix.
1959  *
1960  *   1. diff_words->last_minus == 0 &&
1961  *      diff_words->current_plus == diff_words->plus.text.ptr
1962  *
1963  *      that is: the plus text must start as a new line, and if there is no minus
1964  *      word printed, a graph prefix must be printed.
1965  *
1966  *   2. diff_words->current_plus > diff_words->plus.text.ptr &&
1967  *      *(diff_words->current_plus - 1) == '\n'
1968  *
1969  *      that is: a graph prefix must be printed following a '\n'
1970  */
1971 static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
1972 {
1973         if ((diff_words->last_minus == 0 &&
1974                 diff_words->current_plus == diff_words->plus.text.ptr) ||
1975                 (diff_words->current_plus > diff_words->plus.text.ptr &&
1976                 *(diff_words->current_plus - 1) == '\n')) {
1977                 return 1;
1978         } else {
1979                 return 0;
1980         }
1981 }
1982
1983 static void fn_out_diff_words_aux(void *priv,
1984                                   long minus_first, long minus_len,
1985                                   long plus_first, long plus_len,
1986                                   const char *func, long funclen)
1987 {
1988         struct diff_words_data *diff_words = priv;
1989         struct diff_words_style *style = diff_words->style;
1990         const char *minus_begin, *minus_end, *plus_begin, *plus_end;
1991         struct diff_options *opt = diff_words->opt;
1992         const char *line_prefix;
1993
1994         assert(opt);
1995         line_prefix = diff_line_prefix(opt);
1996
1997         /* POSIX requires that first be decremented by one if len == 0... */
1998         if (minus_len) {
1999                 minus_begin = diff_words->minus.orig[minus_first].begin;
2000                 minus_end =
2001                         diff_words->minus.orig[minus_first + minus_len - 1].end;
2002         } else
2003                 minus_begin = minus_end =
2004                         diff_words->minus.orig[minus_first].end;
2005
2006         if (plus_len) {
2007                 plus_begin = diff_words->plus.orig[plus_first].begin;
2008                 plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
2009         } else
2010                 plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
2011
2012         if (color_words_output_graph_prefix(diff_words)) {
2013                 fputs(line_prefix, diff_words->opt->file);
2014         }
2015         if (diff_words->current_plus != plus_begin) {
2016                 fn_out_diff_words_write_helper(diff_words->opt,
2017                                 &style->ctx, style->newline,
2018                                 plus_begin - diff_words->current_plus,
2019                                 diff_words->current_plus);
2020         }
2021         if (minus_begin != minus_end) {
2022                 fn_out_diff_words_write_helper(diff_words->opt,
2023                                 &style->old_word, style->newline,
2024                                 minus_end - minus_begin, minus_begin);
2025         }
2026         if (plus_begin != plus_end) {
2027                 fn_out_diff_words_write_helper(diff_words->opt,
2028                                 &style->new_word, style->newline,
2029                                 plus_end - plus_begin, plus_begin);
2030         }
2031
2032         diff_words->current_plus = plus_end;
2033         diff_words->last_minus = minus_first;
2034 }
2035
2036 /* This function starts looking at *begin, and returns 0 iff a word was found. */
2037 static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
2038                 int *begin, int *end)
2039 {
2040         if (word_regex && *begin < buffer->size) {
2041                 regmatch_t match[1];
2042                 if (!regexec_buf(word_regex, buffer->ptr + *begin,
2043                                  buffer->size - *begin, 1, match, 0)) {
2044                         char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
2045                                         '\n', match[0].rm_eo - match[0].rm_so);
2046                         *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
2047                         *begin += match[0].rm_so;
2048                         return *begin >= *end;
2049                 }
2050                 return -1;
2051         }
2052
2053         /* find the next word */
2054         while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
2055                 (*begin)++;
2056         if (*begin >= buffer->size)
2057                 return -1;
2058
2059         /* find the end of the word */
2060         *end = *begin + 1;
2061         while (*end < buffer->size && !isspace(buffer->ptr[*end]))
2062                 (*end)++;
2063
2064         return 0;
2065 }
2066
2067 /*
2068  * This function splits the words in buffer->text, stores the list with
2069  * newline separator into out, and saves the offsets of the original words
2070  * in buffer->orig.
2071  */
2072 static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
2073                 regex_t *word_regex)
2074 {
2075         int i, j;
2076         long alloc = 0;
2077
2078         out->size = 0;
2079         out->ptr = NULL;
2080
2081         /* fake an empty "0th" word */
2082         ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
2083         buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
2084         buffer->orig_nr = 1;
2085
2086         for (i = 0; i < buffer->text.size; i++) {
2087                 if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
2088                         return;
2089
2090                 /* store original boundaries */
2091                 ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
2092                                 buffer->orig_alloc);
2093                 buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
2094                 buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
2095                 buffer->orig_nr++;
2096
2097                 /* store one word */
2098                 ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
2099                 memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
2100                 out->ptr[out->size + j - i] = '\n';
2101                 out->size += j - i + 1;
2102
2103                 i = j - 1;
2104         }
2105 }
2106
2107 /* this executes the word diff on the accumulated buffers */
2108 static void diff_words_show(struct diff_words_data *diff_words)
2109 {
2110         xpparam_t xpp;
2111         xdemitconf_t xecfg;
2112         mmfile_t minus, plus;
2113         struct diff_words_style *style = diff_words->style;
2114
2115         struct diff_options *opt = diff_words->opt;
2116         const char *line_prefix;
2117
2118         assert(opt);
2119         line_prefix = diff_line_prefix(opt);
2120
2121         /* special case: only removal */
2122         if (!diff_words->plus.text.size) {
2123                 emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2124                                  line_prefix, strlen(line_prefix), 0);
2125                 fn_out_diff_words_write_helper(diff_words->opt,
2126                         &style->old_word, style->newline,
2127                         diff_words->minus.text.size,
2128                         diff_words->minus.text.ptr);
2129                 diff_words->minus.text.size = 0;
2130                 return;
2131         }
2132
2133         diff_words->current_plus = diff_words->plus.text.ptr;
2134         diff_words->last_minus = 0;
2135
2136         memset(&xpp, 0, sizeof(xpp));
2137         memset(&xecfg, 0, sizeof(xecfg));
2138         diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
2139         diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
2140         xpp.flags = 0;
2141         /* as only the hunk header will be parsed, we need a 0-context */
2142         xecfg.ctxlen = 0;
2143         if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, NULL,
2144                           diff_words, &xpp, &xecfg))
2145                 die("unable to generate word diff");
2146         free(minus.ptr);
2147         free(plus.ptr);
2148         if (diff_words->current_plus != diff_words->plus.text.ptr +
2149                         diff_words->plus.text.size) {
2150                 if (color_words_output_graph_prefix(diff_words))
2151                         emit_diff_symbol(diff_words->opt, DIFF_SYMBOL_WORD_DIFF,
2152                                          line_prefix, strlen(line_prefix), 0);
2153                 fn_out_diff_words_write_helper(diff_words->opt,
2154                         &style->ctx, style->newline,
2155                         diff_words->plus.text.ptr + diff_words->plus.text.size
2156                         - diff_words->current_plus, diff_words->current_plus);
2157         }
2158         diff_words->minus.text.size = diff_words->plus.text.size = 0;
2159 }
2160
2161 /* In "color-words" mode, show word-diff of words accumulated in the buffer */
2162 static void diff_words_flush(struct emit_callback *ecbdata)
2163 {
2164         struct diff_options *wo = ecbdata->diff_words->opt;
2165
2166         if (ecbdata->diff_words->minus.text.size ||
2167             ecbdata->diff_words->plus.text.size)
2168                 diff_words_show(ecbdata->diff_words);
2169
2170         if (wo->emitted_symbols) {
2171                 struct diff_options *o = ecbdata->opt;
2172                 struct emitted_diff_symbols *wol = wo->emitted_symbols;
2173                 int i;
2174
2175                 /*
2176                  * NEEDSWORK:
2177                  * Instead of appending each, concat all words to a line?
2178                  */
2179                 for (i = 0; i < wol->nr; i++)
2180                         append_emitted_diff_symbol(o, &wol->buf[i]);
2181
2182                 for (i = 0; i < wol->nr; i++)
2183                         free((void *)wol->buf[i].line);
2184
2185                 wol->nr = 0;
2186         }
2187 }
2188
2189 static void diff_filespec_load_driver(struct diff_filespec *one,
2190                                       struct index_state *istate)
2191 {
2192         /* Use already-loaded driver */
2193         if (one->driver)
2194                 return;
2195
2196         if (S_ISREG(one->mode))
2197                 one->driver = userdiff_find_by_path(istate, one->path);
2198
2199         /* Fallback to default settings */
2200         if (!one->driver)
2201                 one->driver = userdiff_find_by_name("default");
2202 }
2203
2204 static const char *userdiff_word_regex(struct diff_filespec *one,
2205                                        struct index_state *istate)
2206 {
2207         diff_filespec_load_driver(one, istate);
2208         return one->driver->word_regex;
2209 }
2210
2211 static void init_diff_words_data(struct emit_callback *ecbdata,
2212                                  struct diff_options *orig_opts,
2213                                  struct diff_filespec *one,
2214                                  struct diff_filespec *two)
2215 {
2216         int i;
2217         struct diff_options *o = xmalloc(sizeof(struct diff_options));
2218         memcpy(o, orig_opts, sizeof(struct diff_options));
2219
2220         ecbdata->diff_words =
2221                 xcalloc(1, sizeof(struct diff_words_data));
2222         ecbdata->diff_words->type = o->word_diff;
2223         ecbdata->diff_words->opt = o;
2224
2225         if (orig_opts->emitted_symbols)
2226                 o->emitted_symbols =
2227                         xcalloc(1, sizeof(struct emitted_diff_symbols));
2228
2229         if (!o->word_regex)
2230                 o->word_regex = userdiff_word_regex(one, o->repo->index);
2231         if (!o->word_regex)
2232                 o->word_regex = userdiff_word_regex(two, o->repo->index);
2233         if (!o->word_regex)
2234                 o->word_regex = diff_word_regex_cfg;
2235         if (o->word_regex) {
2236                 ecbdata->diff_words->word_regex = (regex_t *)
2237                         xmalloc(sizeof(regex_t));
2238                 if (regcomp(ecbdata->diff_words->word_regex,
2239                             o->word_regex,
2240                             REG_EXTENDED | REG_NEWLINE))
2241                         die("invalid regular expression: %s",
2242                             o->word_regex);
2243         }
2244         for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
2245                 if (o->word_diff == diff_words_styles[i].type) {
2246                         ecbdata->diff_words->style =
2247                                 &diff_words_styles[i];
2248                         break;
2249                 }
2250         }
2251         if (want_color(o->use_color)) {
2252                 struct diff_words_style *st = ecbdata->diff_words->style;
2253                 st->old_word.color = diff_get_color_opt(o, DIFF_FILE_OLD);
2254                 st->new_word.color = diff_get_color_opt(o, DIFF_FILE_NEW);
2255                 st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
2256         }
2257 }
2258
2259 static void free_diff_words_data(struct emit_callback *ecbdata)
2260 {
2261         if (ecbdata->diff_words) {
2262                 diff_words_flush(ecbdata);
2263                 free (ecbdata->diff_words->opt->emitted_symbols);
2264                 free (ecbdata->diff_words->opt);
2265                 free (ecbdata->diff_words->minus.text.ptr);
2266                 free (ecbdata->diff_words->minus.orig);
2267                 free (ecbdata->diff_words->plus.text.ptr);
2268                 free (ecbdata->diff_words->plus.orig);
2269                 if (ecbdata->diff_words->word_regex) {
2270                         regfree(ecbdata->diff_words->word_regex);
2271                         free(ecbdata->diff_words->word_regex);
2272                 }
2273                 FREE_AND_NULL(ecbdata->diff_words);
2274         }
2275 }
2276
2277 const char *diff_get_color(int diff_use_color, enum color_diff ix)
2278 {
2279         if (want_color(diff_use_color))
2280                 return diff_colors[ix];
2281         return "";
2282 }
2283
2284 const char *diff_line_prefix(struct diff_options *opt)
2285 {
2286         struct strbuf *msgbuf;
2287         if (!opt->output_prefix)
2288                 return "";
2289
2290         msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
2291         return msgbuf->buf;
2292 }
2293
2294 static unsigned long sane_truncate_line(char *line, unsigned long len)
2295 {
2296         const char *cp;
2297         unsigned long allot;
2298         size_t l = len;
2299
2300         cp = line;
2301         allot = l;
2302         while (0 < l) {
2303                 (void) utf8_width(&cp, &l);
2304                 if (!cp)
2305                         break; /* truncated in the middle? */
2306         }
2307         return allot - l;
2308 }
2309
2310 static void find_lno(const char *line, struct emit_callback *ecbdata)
2311 {
2312         const char *p;
2313         ecbdata->lno_in_preimage = 0;
2314         ecbdata->lno_in_postimage = 0;
2315         p = strchr(line, '-');
2316         if (!p)
2317                 return; /* cannot happen */
2318         ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
2319         p = strchr(p, '+');
2320         if (!p)
2321                 return; /* cannot happen */
2322         ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
2323 }
2324
2325 static void fn_out_consume(void *priv, char *line, unsigned long len)
2326 {
2327         struct emit_callback *ecbdata = priv;
2328         struct diff_options *o = ecbdata->opt;
2329
2330         o->found_changes = 1;
2331
2332         if (ecbdata->header) {
2333                 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
2334                                  ecbdata->header->buf, ecbdata->header->len, 0);
2335                 strbuf_reset(ecbdata->header);
2336                 ecbdata->header = NULL;
2337         }
2338
2339         if (ecbdata->label_path[0]) {
2340                 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_MINUS,
2341                                  ecbdata->label_path[0],
2342                                  strlen(ecbdata->label_path[0]), 0);
2343                 emit_diff_symbol(o, DIFF_SYMBOL_FILEPAIR_PLUS,
2344                                  ecbdata->label_path[1],
2345                                  strlen(ecbdata->label_path[1]), 0);
2346                 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
2347         }
2348
2349         if (diff_suppress_blank_empty
2350             && len == 2 && line[0] == ' ' && line[1] == '\n') {
2351                 line[0] = '\n';
2352                 len = 1;
2353         }
2354
2355         if (line[0] == '@') {
2356                 if (ecbdata->diff_words)
2357                         diff_words_flush(ecbdata);
2358                 len = sane_truncate_line(line, len);
2359                 find_lno(line, ecbdata);
2360                 emit_hunk_header(ecbdata, line, len);
2361                 return;
2362         }
2363
2364         if (ecbdata->diff_words) {
2365                 enum diff_symbol s =
2366                         ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN ?
2367                         DIFF_SYMBOL_WORDS_PORCELAIN : DIFF_SYMBOL_WORDS;
2368                 if (line[0] == '-') {
2369                         diff_words_append(line, len,
2370                                           &ecbdata->diff_words->minus);
2371                         return;
2372                 } else if (line[0] == '+') {
2373                         diff_words_append(line, len,
2374                                           &ecbdata->diff_words->plus);
2375                         return;
2376                 } else if (starts_with(line, "\\ ")) {
2377                         /*
2378                          * Eat the "no newline at eof" marker as if we
2379                          * saw a "+" or "-" line with nothing on it,
2380                          * and return without diff_words_flush() to
2381                          * defer processing. If this is the end of
2382                          * preimage, more "+" lines may come after it.
2383                          */
2384                         return;
2385                 }
2386                 diff_words_flush(ecbdata);
2387                 emit_diff_symbol(o, s, line, len, 0);
2388                 return;
2389         }
2390
2391         switch (line[0]) {
2392         case '+':
2393                 ecbdata->lno_in_postimage++;
2394                 emit_add_line(ecbdata, line + 1, len - 1);
2395                 break;
2396         case '-':
2397                 ecbdata->lno_in_preimage++;
2398                 emit_del_line(ecbdata, line + 1, len - 1);
2399                 break;
2400         case ' ':
2401                 ecbdata->lno_in_postimage++;
2402                 ecbdata->lno_in_preimage++;
2403                 emit_context_line(ecbdata, line + 1, len - 1);
2404                 break;
2405         default:
2406                 /* incomplete line at the end */
2407                 ecbdata->lno_in_preimage++;
2408                 emit_diff_symbol(o, DIFF_SYMBOL_CONTEXT_INCOMPLETE,
2409                                  line, len, 0);
2410                 break;
2411         }
2412 }
2413
2414 static void pprint_rename(struct strbuf *name, const char *a, const char *b)
2415 {
2416         const char *old_name = a;
2417         const char *new_name = b;
2418         int pfx_length, sfx_length;
2419         int pfx_adjust_for_slash;
2420         int len_a = strlen(a);
2421         int len_b = strlen(b);
2422         int a_midlen, b_midlen;
2423         int qlen_a = quote_c_style(a, NULL, NULL, 0);
2424         int qlen_b = quote_c_style(b, NULL, NULL, 0);
2425
2426         if (qlen_a || qlen_b) {
2427                 quote_c_style(a, name, NULL, 0);
2428                 strbuf_addstr(name, " => ");
2429                 quote_c_style(b, name, NULL, 0);
2430                 return;
2431         }
2432
2433         /* Find common prefix */
2434         pfx_length = 0;
2435         while (*old_name && *new_name && *old_name == *new_name) {
2436                 if (*old_name == '/')
2437                         pfx_length = old_name - a + 1;
2438                 old_name++;
2439                 new_name++;
2440         }
2441
2442         /* Find common suffix */
2443         old_name = a + len_a;
2444         new_name = b + len_b;
2445         sfx_length = 0;
2446         /*
2447          * If there is a common prefix, it must end in a slash.  In
2448          * that case we let this loop run 1 into the prefix to see the
2449          * same slash.
2450          *
2451          * If there is no common prefix, we cannot do this as it would
2452          * underrun the input strings.
2453          */
2454         pfx_adjust_for_slash = (pfx_length ? 1 : 0);
2455         while (a + pfx_length - pfx_adjust_for_slash <= old_name &&
2456                b + pfx_length - pfx_adjust_for_slash <= new_name &&
2457                *old_name == *new_name) {
2458                 if (*old_name == '/')
2459                         sfx_length = len_a - (old_name - a);
2460                 old_name--;
2461                 new_name--;
2462         }
2463
2464         /*
2465          * pfx{mid-a => mid-b}sfx
2466          * {pfx-a => pfx-b}sfx
2467          * pfx{sfx-a => sfx-b}
2468          * name-a => name-b
2469          */
2470         a_midlen = len_a - pfx_length - sfx_length;
2471         b_midlen = len_b - pfx_length - sfx_length;
2472         if (a_midlen < 0)
2473                 a_midlen = 0;
2474         if (b_midlen < 0)
2475                 b_midlen = 0;
2476
2477         strbuf_grow(name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
2478         if (pfx_length + sfx_length) {
2479                 strbuf_add(name, a, pfx_length);
2480                 strbuf_addch(name, '{');
2481         }
2482         strbuf_add(name, a + pfx_length, a_midlen);
2483         strbuf_addstr(name, " => ");
2484         strbuf_add(name, b + pfx_length, b_midlen);
2485         if (pfx_length + sfx_length) {
2486                 strbuf_addch(name, '}');
2487                 strbuf_add(name, a + len_a - sfx_length, sfx_length);
2488         }
2489 }
2490
2491 struct diffstat_t {
2492         int nr;
2493         int alloc;
2494         struct diffstat_file {
2495                 char *from_name;
2496                 char *name;
2497                 char *print_name;
2498                 const char *comments;
2499                 unsigned is_unmerged:1;
2500                 unsigned is_binary:1;
2501                 unsigned is_renamed:1;
2502                 unsigned is_interesting:1;
2503                 uintmax_t added, deleted;
2504         } **files;
2505 };
2506
2507 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
2508                                           const char *name_a,
2509                                           const char *name_b)
2510 {
2511         struct diffstat_file *x;
2512         x = xcalloc(1, sizeof(*x));
2513         ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
2514         diffstat->files[diffstat->nr++] = x;
2515         if (name_b) {
2516                 x->from_name = xstrdup(name_a);
2517                 x->name = xstrdup(name_b);
2518                 x->is_renamed = 1;
2519         }
2520         else {
2521                 x->from_name = NULL;
2522                 x->name = xstrdup(name_a);
2523         }
2524         return x;
2525 }
2526
2527 static void diffstat_consume(void *priv, char *line, unsigned long len)
2528 {
2529         struct diffstat_t *diffstat = priv;
2530         struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
2531
2532         if (line[0] == '+')
2533                 x->added++;
2534         else if (line[0] == '-')
2535                 x->deleted++;
2536 }
2537
2538 const char mime_boundary_leader[] = "------------";
2539
2540 static int scale_linear(int it, int width, int max_change)
2541 {
2542         if (!it)
2543                 return 0;
2544         /*
2545          * make sure that at least one '-' or '+' is printed if
2546          * there is any change to this path. The easiest way is to
2547          * scale linearly as if the alloted width is one column shorter
2548          * than it is, and then add 1 to the result.
2549          */
2550         return 1 + (it * (width - 1) / max_change);
2551 }
2552
2553 static void show_graph(struct strbuf *out, char ch, int cnt,
2554                        const char *set, const char *reset)
2555 {
2556         if (cnt <= 0)
2557                 return;
2558         strbuf_addstr(out, set);
2559         strbuf_addchars(out, ch, cnt);
2560         strbuf_addstr(out, reset);
2561 }
2562
2563 static void fill_print_name(struct diffstat_file *file)
2564 {
2565         struct strbuf pname = STRBUF_INIT;
2566
2567         if (file->print_name)
2568                 return;
2569
2570         if (file->is_renamed)
2571                 pprint_rename(&pname, file->from_name, file->name);
2572         else
2573                 quote_c_style(file->name, &pname, NULL, 0);
2574
2575         if (file->comments)
2576                 strbuf_addf(&pname, " (%s)", file->comments);
2577
2578         file->print_name = strbuf_detach(&pname, NULL);
2579 }
2580
2581 static void print_stat_summary_inserts_deletes(struct diff_options *options,
2582                 int files, int insertions, int deletions)
2583 {
2584         struct strbuf sb = STRBUF_INIT;
2585
2586         if (!files) {
2587                 assert(insertions == 0 && deletions == 0);
2588                 emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
2589                                  NULL, 0, 0);
2590                 return;
2591         }
2592
2593         strbuf_addf(&sb,
2594                     (files == 1) ? " %d file changed" : " %d files changed",
2595                     files);
2596
2597         /*
2598          * For binary diff, the caller may want to print "x files
2599          * changed" with insertions == 0 && deletions == 0.
2600          *
2601          * Not omitting "0 insertions(+), 0 deletions(-)" in this case
2602          * is probably less confusing (i.e skip over "2 files changed
2603          * but nothing about added/removed lines? Is this a bug in Git?").
2604          */
2605         if (insertions || deletions == 0) {
2606                 strbuf_addf(&sb,
2607                             (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
2608                             insertions);
2609         }
2610
2611         if (deletions || insertions == 0) {
2612                 strbuf_addf(&sb,
2613                             (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
2614                             deletions);
2615         }
2616         strbuf_addch(&sb, '\n');
2617         emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
2618                          sb.buf, sb.len, 0);
2619         strbuf_release(&sb);
2620 }
2621
2622 void print_stat_summary(FILE *fp, int files,
2623                         int insertions, int deletions)
2624 {
2625         struct diff_options o;
2626         memset(&o, 0, sizeof(o));
2627         o.file = fp;
2628
2629         print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
2630 }
2631
2632 static void show_stats(struct diffstat_t *data, struct diff_options *options)
2633 {
2634         int i, len, add, del, adds = 0, dels = 0;
2635         uintmax_t max_change = 0, max_len = 0;
2636         int total_files = data->nr, count;
2637         int width, name_width, graph_width, number_width = 0, bin_width = 0;
2638         const char *reset, *add_c, *del_c;
2639         int extra_shown = 0;
2640         const char *line_prefix = diff_line_prefix(options);
2641         struct strbuf out = STRBUF_INIT;
2642
2643         if (data->nr == 0)
2644                 return;
2645
2646         count = options->stat_count ? options->stat_count : data->nr;
2647
2648         reset = diff_get_color_opt(options, DIFF_RESET);
2649         add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
2650         del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
2651
2652         /*
2653          * Find the longest filename and max number of changes
2654          */
2655         for (i = 0; (i < count) && (i < data->nr); i++) {
2656                 struct diffstat_file *file = data->files[i];
2657                 uintmax_t change = file->added + file->deleted;
2658
2659                 if (!file->is_interesting && (change == 0)) {
2660                         count++; /* not shown == room for one more */
2661                         continue;
2662                 }
2663                 fill_print_name(file);
2664                 len = strlen(file->print_name);
2665                 if (max_len < len)
2666                         max_len = len;
2667
2668                 if (file->is_unmerged) {
2669                         /* "Unmerged" is 8 characters */
2670                         bin_width = bin_width < 8 ? 8 : bin_width;
2671                         continue;
2672                 }
2673                 if (file->is_binary) {
2674                         /* "Bin XXX -> YYY bytes" */
2675                         int w = 14 + decimal_width(file->added)
2676                                 + decimal_width(file->deleted);
2677                         bin_width = bin_width < w ? w : bin_width;
2678                         /* Display change counts aligned with "Bin" */
2679                         number_width = 3;
2680                         continue;
2681                 }
2682
2683                 if (max_change < change)
2684                         max_change = change;
2685         }
2686         count = i; /* where we can stop scanning in data->files[] */
2687
2688         /*
2689          * We have width = stat_width or term_columns() columns total.
2690          * We want a maximum of min(max_len, stat_name_width) for the name part.
2691          * We want a maximum of min(max_change, stat_graph_width) for the +- part.
2692          * We also need 1 for " " and 4 + decimal_width(max_change)
2693          * for " | NNNN " and one the empty column at the end, altogether
2694          * 6 + decimal_width(max_change).
2695          *
2696          * If there's not enough space, we will use the smaller of
2697          * stat_name_width (if set) and 5/8*width for the filename,
2698          * and the rest for constant elements + graph part, but no more
2699          * than stat_graph_width for the graph part.
2700          * (5/8 gives 50 for filename and 30 for the constant parts + graph
2701          * for the standard terminal size).
2702          *
2703          * In other words: stat_width limits the maximum width, and
2704          * stat_name_width fixes the maximum width of the filename,
2705          * and is also used to divide available columns if there
2706          * aren't enough.
2707          *
2708          * Binary files are displayed with "Bin XXX -> YYY bytes"
2709          * instead of the change count and graph. This part is treated
2710          * similarly to the graph part, except that it is not
2711          * "scaled". If total width is too small to accommodate the
2712          * guaranteed minimum width of the filename part and the
2713          * separators and this message, this message will "overflow"
2714          * making the line longer than the maximum width.
2715          */
2716
2717         if (options->stat_width == -1)
2718                 width = term_columns() - strlen(line_prefix);
2719         else
2720                 width = options->stat_width ? options->stat_width : 80;
2721         number_width = decimal_width(max_change) > number_width ?
2722                 decimal_width(max_change) : number_width;
2723
2724         if (options->stat_graph_width == -1)
2725                 options->stat_graph_width = diff_stat_graph_width;
2726
2727         /*
2728          * Guarantee 3/8*16==6 for the graph part
2729          * and 5/8*16==10 for the filename part
2730          */
2731         if (width < 16 + 6 + number_width)
2732                 width = 16 + 6 + number_width;
2733
2734         /*
2735          * First assign sizes that are wanted, ignoring available width.
2736          * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
2737          * starting from "XXX" should fit in graph_width.
2738          */
2739         graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
2740         if (options->stat_graph_width &&
2741             options->stat_graph_width < graph_width)
2742                 graph_width = options->stat_graph_width;
2743
2744         name_width = (options->stat_name_width > 0 &&
2745                       options->stat_name_width < max_len) ?
2746                 options->stat_name_width : max_len;
2747
2748         /*
2749          * Adjust adjustable widths not to exceed maximum width
2750          */
2751         if (name_width + number_width + 6 + graph_width > width) {
2752                 if (graph_width > width * 3/8 - number_width - 6) {
2753                         graph_width = width * 3/8 - number_width - 6;
2754                         if (graph_width < 6)
2755                                 graph_width = 6;
2756                 }
2757
2758                 if (options->stat_graph_width &&
2759                     graph_width > options->stat_graph_width)
2760                         graph_width = options->stat_graph_width;
2761                 if (name_width > width - number_width - 6 - graph_width)
2762                         name_width = width - number_width - 6 - graph_width;
2763                 else
2764                         graph_width = width - number_width - 6 - name_width;
2765         }
2766
2767         /*
2768          * From here name_width is the width of the name area,
2769          * and graph_width is the width of the graph area.
2770          * max_change is used to scale graph properly.
2771          */
2772         for (i = 0; i < count; i++) {
2773                 const char *prefix = "";
2774                 struct diffstat_file *file = data->files[i];
2775                 char *name = file->print_name;
2776                 uintmax_t added = file->added;
2777                 uintmax_t deleted = file->deleted;
2778                 int name_len;
2779
2780                 if (!file->is_interesting && (added + deleted == 0))
2781                         continue;
2782
2783                 /*
2784                  * "scale" the filename
2785                  */
2786                 len = name_width;
2787                 name_len = strlen(name);
2788                 if (name_width < name_len) {
2789                         char *slash;
2790                         prefix = "...";
2791                         len -= 3;
2792                         name += name_len - len;
2793                         slash = strchr(name, '/');
2794                         if (slash)
2795                                 name = slash;
2796                 }
2797
2798                 if (file->is_binary) {
2799                         strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2800                         strbuf_addf(&out, " %*s", number_width, "Bin");
2801                         if (!added && !deleted) {
2802                                 strbuf_addch(&out, '\n');
2803                                 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2804                                                  out.buf, out.len, 0);
2805                                 strbuf_reset(&out);
2806                                 continue;
2807                         }
2808                         strbuf_addf(&out, " %s%"PRIuMAX"%s",
2809                                 del_c, deleted, reset);
2810                         strbuf_addstr(&out, " -> ");
2811                         strbuf_addf(&out, "%s%"PRIuMAX"%s",
2812                                 add_c, added, reset);
2813                         strbuf_addstr(&out, " bytes\n");
2814                         emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2815                                          out.buf, out.len, 0);
2816                         strbuf_reset(&out);
2817                         continue;
2818                 }
2819                 else if (file->is_unmerged) {
2820                         strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2821                         strbuf_addstr(&out, " Unmerged\n");
2822                         emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2823                                          out.buf, out.len, 0);
2824                         strbuf_reset(&out);
2825                         continue;
2826                 }
2827
2828                 /*
2829                  * scale the add/delete
2830                  */
2831                 add = added;
2832                 del = deleted;
2833
2834                 if (graph_width <= max_change) {
2835                         int total = scale_linear(add + del, graph_width, max_change);
2836                         if (total < 2 && add && del)
2837                                 /* width >= 2 due to the sanity check */
2838                                 total = 2;
2839                         if (add < del) {
2840                                 add = scale_linear(add, graph_width, max_change);
2841                                 del = total - add;
2842                         } else {
2843                                 del = scale_linear(del, graph_width, max_change);
2844                                 add = total - del;
2845                         }
2846                 }
2847                 strbuf_addf(&out, " %s%-*s |", prefix, len, name);
2848                 strbuf_addf(&out, " %*"PRIuMAX"%s",
2849                         number_width, added + deleted,
2850                         added + deleted ? " " : "");
2851                 show_graph(&out, '+', add, add_c, reset);
2852                 show_graph(&out, '-', del, del_c, reset);
2853                 strbuf_addch(&out, '\n');
2854                 emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
2855                                  out.buf, out.len, 0);
2856                 strbuf_reset(&out);
2857         }
2858
2859         for (i = 0; i < data->nr; i++) {
2860                 struct diffstat_file *file = data->files[i];
2861                 uintmax_t added = file->added;
2862                 uintmax_t deleted = file->deleted;
2863
2864                 if (file->is_unmerged ||
2865                     (!file->is_interesting && (added + deleted == 0))) {
2866                         total_files--;
2867                         continue;
2868                 }
2869
2870                 if (!file->is_binary) {
2871                         adds += added;
2872                         dels += deleted;
2873                 }
2874                 if (i < count)
2875                         continue;
2876                 if (!extra_shown)
2877                         emit_diff_symbol(options,
2878                                          DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
2879                                          NULL, 0, 0);
2880                 extra_shown = 1;
2881         }
2882
2883         print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2884         strbuf_release(&out);
2885 }
2886
2887 static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
2888 {
2889         int i, adds = 0, dels = 0, total_files = data->nr;
2890
2891         if (data->nr == 0)
2892                 return;
2893
2894         for (i = 0; i < data->nr; i++) {
2895                 int added = data->files[i]->added;
2896                 int deleted = data->files[i]->deleted;
2897
2898                 if (data->files[i]->is_unmerged ||
2899                     (!data->files[i]->is_interesting && (added + deleted == 0))) {
2900                         total_files--;
2901                 } else if (!data->files[i]->is_binary) { /* don't count bytes */
2902                         adds += added;
2903                         dels += deleted;
2904                 }
2905         }
2906         print_stat_summary_inserts_deletes(options, total_files, adds, dels);
2907 }
2908
2909 static void show_numstat(struct diffstat_t *data, struct diff_options *options)
2910 {
2911         int i;
2912
2913         if (data->nr == 0)
2914                 return;
2915
2916         for (i = 0; i < data->nr; i++) {
2917                 struct diffstat_file *file = data->files[i];
2918
2919                 fprintf(options->file, "%s", diff_line_prefix(options));
2920
2921                 if (file->is_binary)
2922                         fprintf(options->file, "-\t-\t");
2923                 else
2924                         fprintf(options->file,
2925                                 "%"PRIuMAX"\t%"PRIuMAX"\t",
2926                                 file->added, file->deleted);
2927                 if (options->line_termination) {
2928                         fill_print_name(file);
2929                         if (!file->is_renamed)
2930                                 write_name_quoted(file->name, options->file,
2931                                                   options->line_termination);
2932                         else {
2933                                 fputs(file->print_name, options->file);
2934                                 putc(options->line_termination, options->file);
2935                         }
2936                 } else {
2937                         if (file->is_renamed) {
2938                                 putc('\0', options->file);
2939                                 write_name_quoted(file->from_name, options->file, '\0');
2940                         }
2941                         write_name_quoted(file->name, options->file, '\0');
2942                 }
2943         }
2944 }
2945
2946 struct dirstat_file {
2947         const char *name;
2948         unsigned long changed;
2949 };
2950
2951 struct dirstat_dir {
2952         struct dirstat_file *files;
2953         int alloc, nr, permille, cumulative;
2954 };
2955
2956 static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
2957                 unsigned long changed, const char *base, int baselen)
2958 {
2959         unsigned long sum_changes = 0;
2960         unsigned int sources = 0;
2961         const char *line_prefix = diff_line_prefix(opt);
2962
2963         while (dir->nr) {
2964                 struct dirstat_file *f = dir->files;
2965                 int namelen = strlen(f->name);
2966                 unsigned long changes;
2967                 char *slash;
2968
2969                 if (namelen < baselen)
2970                         break;
2971                 if (memcmp(f->name, base, baselen))
2972                         break;
2973                 slash = strchr(f->name + baselen, '/');
2974                 if (slash) {
2975                         int newbaselen = slash + 1 - f->name;
2976                         changes = gather_dirstat(opt, dir, changed, f->name, newbaselen);
2977                         sources++;
2978                 } else {
2979                         changes = f->changed;
2980                         dir->files++;
2981                         dir->nr--;
2982                         sources += 2;
2983                 }
2984                 sum_changes += changes;
2985         }
2986
2987         /*
2988          * We don't report dirstat's for
2989          *  - the top level
2990          *  - or cases where everything came from a single directory
2991          *    under this directory (sources == 1).
2992          */
2993         if (baselen && sources != 1) {
2994                 if (sum_changes) {
2995                         int permille = sum_changes * 1000 / changed;
2996                         if (permille >= dir->permille) {
2997                                 fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
2998                                         permille / 10, permille % 10, baselen, base);
2999                                 if (!dir->cumulative)
3000                                         return 0;
3001                         }
3002                 }
3003         }
3004         return sum_changes;
3005 }
3006
3007 static int dirstat_compare(const void *_a, const void *_b)
3008 {
3009         const struct dirstat_file *a = _a;
3010         const struct dirstat_file *b = _b;
3011         return strcmp(a->name, b->name);
3012 }
3013
3014 static void show_dirstat(struct diff_options *options)
3015 {
3016         int i;
3017         unsigned long changed;
3018         struct dirstat_dir dir;
3019         struct diff_queue_struct *q = &diff_queued_diff;
3020
3021         dir.files = NULL;
3022         dir.alloc = 0;
3023         dir.nr = 0;
3024         dir.permille = options->dirstat_permille;
3025         dir.cumulative = options->flags.dirstat_cumulative;
3026
3027         changed = 0;
3028         for (i = 0; i < q->nr; i++) {
3029                 struct diff_filepair *p = q->queue[i];
3030                 const char *name;
3031                 unsigned long copied, added, damage;
3032
3033                 name = p->two->path ? p->two->path : p->one->path;
3034
3035                 if (p->one->oid_valid && p->two->oid_valid &&
3036                     oideq(&p->one->oid, &p->two->oid)) {
3037                         /*
3038                          * The SHA1 has not changed, so pre-/post-content is
3039                          * identical. We can therefore skip looking at the
3040                          * file contents altogether.
3041                          */
3042                         damage = 0;
3043                         goto found_damage;
3044                 }
3045
3046                 if (options->flags.dirstat_by_file) {
3047                         /*
3048                          * In --dirstat-by-file mode, we don't really need to
3049                          * look at the actual file contents at all.
3050                          * The fact that the SHA1 changed is enough for us to
3051                          * add this file to the list of results
3052                          * (with each file contributing equal damage).
3053                          */
3054                         damage = 1;
3055                         goto found_damage;
3056                 }
3057
3058                 if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
3059                         diff_populate_filespec(options->repo, p->one, 0);
3060                         diff_populate_filespec(options->repo, p->two, 0);
3061                         diffcore_count_changes(options->repo,
3062                                                p->one, p->two, NULL, NULL,
3063                                                &copied, &added);
3064                         diff_free_filespec_data(p->one);
3065                         diff_free_filespec_data(p->two);
3066                 } else if (DIFF_FILE_VALID(p->one)) {
3067                         diff_populate_filespec(options->repo, p->one, CHECK_SIZE_ONLY);
3068                         copied = added = 0;
3069                         diff_free_filespec_data(p->one);
3070                 } else if (DIFF_FILE_VALID(p->two)) {
3071                         diff_populate_filespec(options->repo, p->two, CHECK_SIZE_ONLY);
3072                         copied = 0;
3073                         added = p->two->size;
3074                         diff_free_filespec_data(p->two);
3075                 } else
3076                         continue;
3077
3078                 /*
3079                  * Original minus copied is the removed material,
3080                  * added is the new material.  They are both damages
3081                  * made to the preimage.
3082                  * If the resulting damage is zero, we know that
3083                  * diffcore_count_changes() considers the two entries to
3084                  * be identical, but since the oid changed, we
3085                  * know that there must have been _some_ kind of change,
3086                  * so we force all entries to have damage > 0.
3087                  */
3088                 damage = (p->one->size - copied) + added;
3089                 if (!damage)
3090                         damage = 1;
3091
3092 found_damage:
3093                 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3094                 dir.files[dir.nr].name = name;
3095                 dir.files[dir.nr].changed = damage;
3096                 changed += damage;
3097                 dir.nr++;
3098         }
3099
3100         /* This can happen even with many files, if everything was renames */
3101         if (!changed)
3102                 return;
3103
3104         /* Show all directories with more than x% of the changes */
3105         QSORT(dir.files, dir.nr, dirstat_compare);
3106         gather_dirstat(options, &dir, changed, "", 0);
3107 }
3108
3109 static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
3110 {
3111         int i;
3112         unsigned long changed;
3113         struct dirstat_dir dir;
3114
3115         if (data->nr == 0)
3116                 return;
3117
3118         dir.files = NULL;
3119         dir.alloc = 0;
3120         dir.nr = 0;
3121         dir.permille = options->dirstat_permille;
3122         dir.cumulative = options->flags.dirstat_cumulative;
3123
3124         changed = 0;
3125         for (i = 0; i < data->nr; i++) {
3126                 struct diffstat_file *file = data->files[i];
3127                 unsigned long damage = file->added + file->deleted;
3128                 if (file->is_binary)
3129                         /*
3130                          * binary files counts bytes, not lines. Must find some
3131                          * way to normalize binary bytes vs. textual lines.
3132                          * The following heuristic assumes that there are 64
3133                          * bytes per "line".
3134                          * This is stupid and ugly, but very cheap...
3135                          */
3136                         damage = DIV_ROUND_UP(damage, 64);
3137                 ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
3138                 dir.files[dir.nr].name = file->name;
3139                 dir.files[dir.nr].changed = damage;
3140                 changed += damage;
3141                 dir.nr++;
3142         }
3143
3144         /* This can happen even with many files, if everything was renames */
3145         if (!changed)
3146                 return;
3147
3148         /* Show all directories with more than x% of the changes */
3149         QSORT(dir.files, dir.nr, dirstat_compare);
3150         gather_dirstat(options, &dir, changed, "", 0);
3151 }
3152
3153 static void free_diffstat_info(struct diffstat_t *diffstat)
3154 {
3155         int i;
3156         for (i = 0; i < diffstat->nr; i++) {
3157                 struct diffstat_file *f = diffstat->files[i];
3158                 free(f->print_name);
3159                 free(f->name);
3160                 free(f->from_name);
3161                 free(f);
3162         }
3163         free(diffstat->files);
3164 }
3165
3166 struct checkdiff_t {
3167         const char *filename;
3168         int lineno;
3169         int conflict_marker_size;
3170         struct diff_options *o;
3171         unsigned ws_rule;
3172         unsigned status;
3173 };
3174
3175 static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
3176 {
3177         char firstchar;
3178         int cnt;
3179
3180         if (len < marker_size + 1)
3181                 return 0;
3182         firstchar = line[0];
3183         switch (firstchar) {
3184         case '=': case '>': case '<': case '|':
3185                 break;
3186         default:
3187                 return 0;
3188         }
3189         for (cnt = 1; cnt < marker_size; cnt++)
3190                 if (line[cnt] != firstchar)
3191                         return 0;
3192         /* line[1] thru line[marker_size-1] are same as firstchar */
3193         if (len < marker_size + 1 || !isspace(line[marker_size]))
3194                 return 0;
3195         return 1;
3196 }
3197
3198 static void checkdiff_consume_hunk(void *priv,
3199                                    long ob, long on, long nb, long nn,
3200                                    const char *func, long funclen)
3201
3202 {
3203         struct checkdiff_t *data = priv;
3204         data->lineno = nb - 1;
3205 }
3206
3207 static void checkdiff_consume(void *priv, char *line, unsigned long len)
3208 {
3209         struct checkdiff_t *data = priv;
3210         int marker_size = data->conflict_marker_size;
3211         const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
3212         const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
3213         const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
3214         char *err;
3215         const char *line_prefix;
3216
3217         assert(data->o);
3218         line_prefix = diff_line_prefix(data->o);
3219
3220         if (line[0] == '+') {
3221                 unsigned bad;
3222                 data->lineno++;
3223                 if (is_conflict_marker(line + 1, marker_size, len - 1)) {
3224                         data->status |= 1;
3225                         fprintf(data->o->file,
3226                                 "%s%s:%d: leftover conflict marker\n",
3227                                 line_prefix, data->filename, data->lineno);
3228                 }
3229                 bad = ws_check(line + 1, len - 1, data->ws_rule);
3230                 if (!bad)
3231                         return;
3232                 data->status |= bad;
3233                 err = whitespace_error_string(bad);
3234                 fprintf(data->o->file, "%s%s:%d: %s.\n",
3235                         line_prefix, data->filename, data->lineno, err);
3236                 free(err);
3237                 emit_line(data->o, set, reset, line, 1);
3238                 ws_check_emit(line + 1, len - 1, data->ws_rule,
3239                               data->o->file, set, reset, ws);
3240         } else if (line[0] == ' ') {
3241                 data->lineno++;
3242         }
3243 }
3244
3245 static unsigned char *deflate_it(char *data,
3246                                  unsigned long size,
3247                                  unsigned long *result_size)
3248 {
3249         int bound;
3250         unsigned char *deflated;
3251         git_zstream stream;
3252
3253         git_deflate_init(&stream, zlib_compression_level);
3254         bound = git_deflate_bound(&stream, size);
3255         deflated = xmalloc(bound);
3256         stream.next_out = deflated;
3257         stream.avail_out = bound;
3258
3259         stream.next_in = (unsigned char *)data;
3260         stream.avail_in = size;
3261         while (git_deflate(&stream, Z_FINISH) == Z_OK)
3262                 ; /* nothing */
3263         git_deflate_end(&stream);
3264         *result_size = stream.total_out;
3265         return deflated;
3266 }
3267
3268 static void emit_binary_diff_body(struct diff_options *o,
3269                                   mmfile_t *one, mmfile_t *two)
3270 {
3271         void *cp;
3272         void *delta;
3273         void *deflated;
3274         void *data;
3275         unsigned long orig_size;
3276         unsigned long delta_size;
3277         unsigned long deflate_size;
3278         unsigned long data_size;
3279
3280         /* We could do deflated delta, or we could do just deflated two,
3281          * whichever is smaller.
3282          */
3283         delta = NULL;
3284         deflated = deflate_it(two->ptr, two->size, &deflate_size);
3285         if (one->size && two->size) {
3286                 delta = diff_delta(one->ptr, one->size,
3287                                    two->ptr, two->size,
3288                                    &delta_size, deflate_size);
3289                 if (delta) {
3290                         void *to_free = delta;
3291                         orig_size = delta_size;
3292                         delta = deflate_it(delta, delta_size, &delta_size);
3293                         free(to_free);
3294                 }
3295         }
3296
3297         if (delta && delta_size < deflate_size) {
3298                 char *s = xstrfmt("%"PRIuMAX , (uintmax_t)orig_size);
3299                 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
3300                                  s, strlen(s), 0);
3301                 free(s);
3302                 free(deflated);
3303                 data = delta;
3304                 data_size = delta_size;
3305         } else {
3306                 char *s = xstrfmt("%lu", two->size);
3307                 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
3308                                  s, strlen(s), 0);
3309                 free(s);
3310                 free(delta);
3311                 data = deflated;
3312                 data_size = deflate_size;
3313         }
3314
3315         /* emit data encoded in base85 */
3316         cp = data;
3317         while (data_size) {
3318                 int len;
3319                 int bytes = (52 < data_size) ? 52 : data_size;
3320                 char line[71];
3321                 data_size -= bytes;
3322                 if (bytes <= 26)
3323                         line[0] = bytes + 'A' - 1;
3324                 else
3325                         line[0] = bytes - 26 + 'a' - 1;
3326                 encode_85(line + 1, cp, bytes);
3327                 cp = (char *) cp + bytes;
3328
3329                 len = strlen(line);
3330                 line[len++] = '\n';
3331                 line[len] = '\0';
3332
3333                 emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
3334                                  line, len, 0);
3335         }
3336         emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
3337         free(data);
3338 }
3339
3340 static void emit_binary_diff(struct diff_options *o,
3341                              mmfile_t *one, mmfile_t *two)
3342 {
3343         emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
3344         emit_binary_diff_body(o, one, two);
3345         emit_binary_diff_body(o, two, one);
3346 }
3347
3348 int diff_filespec_is_binary(struct repository *r,
3349                             struct diff_filespec *one)
3350 {
3351         if (one->is_binary == -1) {
3352                 diff_filespec_load_driver(one, r->index);
3353                 if (one->driver->binary != -1)
3354                         one->is_binary = one->driver->binary;
3355                 else {
3356                         if (!one->data && DIFF_FILE_VALID(one))
3357                                 diff_populate_filespec(r, one, CHECK_BINARY);
3358                         if (one->is_binary == -1 && one->data)
3359                                 one->is_binary = buffer_is_binary(one->data,
3360                                                 one->size);
3361                         if (one->is_binary == -1)
3362                                 one->is_binary = 0;
3363                 }
3364         }
3365         return one->is_binary;
3366 }
3367
3368 static const struct userdiff_funcname *
3369 diff_funcname_pattern(struct diff_options *o, struct diff_filespec *one)
3370 {
3371         diff_filespec_load_driver(one, o->repo->index);
3372         return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
3373 }
3374
3375 void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
3376 {
3377         if (!options->a_prefix)
3378                 options->a_prefix = a;
3379         if (!options->b_prefix)
3380                 options->b_prefix = b;
3381 }
3382
3383 struct userdiff_driver *get_textconv(struct repository *r,
3384                                      struct diff_filespec *one)
3385 {
3386         if (!DIFF_FILE_VALID(one))
3387                 return NULL;
3388
3389         diff_filespec_load_driver(one, r->index);
3390         return userdiff_get_textconv(r, one->driver);
3391 }
3392
3393 static void builtin_diff(const char *name_a,
3394                          const char *name_b,
3395                          struct diff_filespec *one,
3396                          struct diff_filespec *two,
3397                          const char *xfrm_msg,
3398                          int must_show_header,
3399                          struct diff_options *o,
3400                          int complete_rewrite)
3401 {
3402         mmfile_t mf1, mf2;
3403         const char *lbl[2];
3404         char *a_one, *b_two;
3405         const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
3406         const char *reset = diff_get_color_opt(o, DIFF_RESET);
3407         const char *a_prefix, *b_prefix;
3408         struct userdiff_driver *textconv_one = NULL;
3409         struct userdiff_driver *textconv_two = NULL;
3410         struct strbuf header = STRBUF_INIT;
3411         const char *line_prefix = diff_line_prefix(o);
3412
3413         diff_set_mnemonic_prefix(o, "a/", "b/");
3414         if (o->flags.reverse_diff) {
3415                 a_prefix = o->b_prefix;
3416                 b_prefix = o->a_prefix;
3417         } else {
3418                 a_prefix = o->a_prefix;
3419                 b_prefix = o->b_prefix;
3420         }
3421
3422         if (o->submodule_format == DIFF_SUBMODULE_LOG &&
3423             (!one->mode || S_ISGITLINK(one->mode)) &&
3424             (!two->mode || S_ISGITLINK(two->mode))) {
3425                 show_submodule_summary(o, one->path ? one->path : two->path,
3426                                 &one->oid, &two->oid,
3427                                 two->dirty_submodule);
3428                 return;
3429         } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
3430                    (!one->mode || S_ISGITLINK(one->mode)) &&
3431                    (!two->mode || S_ISGITLINK(two->mode))) {
3432                 show_submodule_inline_diff(o, one->path ? one->path : two->path,
3433                                 &one->oid, &two->oid,
3434                                 two->dirty_submodule);
3435                 return;
3436         }
3437
3438         if (o->flags.allow_textconv) {
3439                 textconv_one = get_textconv(o->repo, one);
3440                 textconv_two = get_textconv(o->repo, two);
3441         }
3442
3443         /* Never use a non-valid filename anywhere if at all possible */
3444         name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
3445         name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
3446
3447         a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
3448         b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
3449         lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
3450         lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
3451         strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
3452         if (lbl[0][0] == '/') {
3453                 /* /dev/null */
3454                 strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
3455                 if (xfrm_msg)
3456                         strbuf_addstr(&header, xfrm_msg);
3457                 must_show_header = 1;
3458         }
3459         else if (lbl[1][0] == '/') {
3460                 strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
3461                 if (xfrm_msg)
3462                         strbuf_addstr(&header, xfrm_msg);
3463                 must_show_header = 1;
3464         }
3465         else {
3466                 if (one->mode != two->mode) {
3467                         strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
3468                         strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
3469                         must_show_header = 1;
3470                 }
3471                 if (xfrm_msg)
3472                         strbuf_addstr(&header, xfrm_msg);
3473
3474                 /*
3475                  * we do not run diff between different kind
3476                  * of objects.
3477                  */
3478                 if ((one->mode ^ two->mode) & S_IFMT)
3479                         goto free_ab_and_return;
3480                 if (complete_rewrite &&
3481                     (textconv_one || !diff_filespec_is_binary(o->repo, one)) &&
3482                     (textconv_two || !diff_filespec_is_binary(o->repo, two))) {
3483                         emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3484                                          header.buf, header.len, 0);
3485                         strbuf_reset(&header);
3486                         emit_rewrite_diff(name_a, name_b, one, two,
3487                                           textconv_one, textconv_two, o);
3488                         o->found_changes = 1;
3489                         goto free_ab_and_return;
3490                 }
3491         }
3492
3493         if (o->irreversible_delete && lbl[1][0] == '/') {
3494                 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
3495                                  header.len, 0);
3496                 strbuf_reset(&header);
3497                 goto free_ab_and_return;
3498         } else if (!o->flags.text &&
3499                    ( (!textconv_one && diff_filespec_is_binary(o->repo, one)) ||
3500                      (!textconv_two && diff_filespec_is_binary(o->repo, two)) )) {
3501                 struct strbuf sb = STRBUF_INIT;
3502                 if (!one->data && !two->data &&
3503                     S_ISREG(one->mode) && S_ISREG(two->mode) &&
3504                     !o->flags.binary) {
3505                         if (oideq(&one->oid, &two->oid)) {
3506                                 if (must_show_header)
3507                                         emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3508                                                          header.buf, header.len,
3509                                                          0);
3510                                 goto free_ab_and_return;
3511                         }
3512                         emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3513                                          header.buf, header.len, 0);
3514                         strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3515                                     diff_line_prefix(o), lbl[0], lbl[1]);
3516                         emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3517                                          sb.buf, sb.len, 0);
3518                         strbuf_release(&sb);
3519                         goto free_ab_and_return;
3520                 }
3521                 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3522                     fill_mmfile(o->repo, &mf2, two) < 0)
3523                         die("unable to read files to diff");
3524                 /* Quite common confusing case */
3525                 if (mf1.size == mf2.size &&
3526                     !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
3527                         if (must_show_header)
3528                                 emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3529                                                  header.buf, header.len, 0);
3530                         goto free_ab_and_return;
3531                 }
3532                 emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
3533                 strbuf_reset(&header);
3534                 if (o->flags.binary)
3535                         emit_binary_diff(o, &mf1, &mf2);
3536                 else {
3537                         strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
3538                                     diff_line_prefix(o), lbl[0], lbl[1]);
3539                         emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
3540                                          sb.buf, sb.len, 0);
3541                         strbuf_release(&sb);
3542                 }
3543                 o->found_changes = 1;
3544         } else {
3545                 /* Crazy xdl interfaces.. */
3546                 const char *diffopts;
3547                 const char *v;
3548                 xpparam_t xpp;
3549                 xdemitconf_t xecfg;
3550                 struct emit_callback ecbdata;
3551                 const struct userdiff_funcname *pe;
3552
3553                 if (must_show_header) {
3554                         emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
3555                                          header.buf, header.len, 0);
3556                         strbuf_reset(&header);
3557                 }
3558
3559                 mf1.size = fill_textconv(o->repo, textconv_one, one, &mf1.ptr);
3560                 mf2.size = fill_textconv(o->repo, textconv_two, two, &mf2.ptr);
3561
3562                 pe = diff_funcname_pattern(o, one);
3563                 if (!pe)
3564                         pe = diff_funcname_pattern(o, two);
3565
3566                 memset(&xpp, 0, sizeof(xpp));
3567                 memset(&xecfg, 0, sizeof(xecfg));
3568                 memset(&ecbdata, 0, sizeof(ecbdata));
3569                 if (o->flags.suppress_diff_headers)
3570                         lbl[0] = NULL;
3571                 ecbdata.label_path = lbl;
3572                 ecbdata.color_diff = want_color(o->use_color);
3573                 ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
3574                 if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
3575                         check_blank_at_eof(&mf1, &mf2, &ecbdata);
3576                 ecbdata.opt = o;
3577                 if (header.len && !o->flags.suppress_diff_headers)
3578                         ecbdata.header = &header;
3579                 xpp.flags = o->xdl_opts;
3580                 xpp.anchors = o->anchors;
3581                 xpp.anchors_nr = o->anchors_nr;
3582                 xecfg.ctxlen = o->context;
3583                 xecfg.interhunkctxlen = o->interhunkcontext;
3584                 xecfg.flags = XDL_EMIT_FUNCNAMES;
3585                 if (o->flags.funccontext)
3586                         xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
3587                 if (pe)
3588                         xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
3589
3590                 diffopts = getenv("GIT_DIFF_OPTS");
3591                 if (!diffopts)
3592                         ;
3593                 else if (skip_prefix(diffopts, "--unified=", &v))
3594                         xecfg.ctxlen = strtoul(v, NULL, 10);
3595                 else if (skip_prefix(diffopts, "-u", &v))
3596                         xecfg.ctxlen = strtoul(v, NULL, 10);
3597
3598                 if (o->word_diff)
3599                         init_diff_words_data(&ecbdata, o, one, two);
3600                 if (xdi_diff_outf(&mf1, &mf2, NULL, fn_out_consume,
3601                                   &ecbdata, &xpp, &xecfg))
3602                         die("unable to generate diff for %s", one->path);
3603                 if (o->word_diff)
3604                         free_diff_words_data(&ecbdata);
3605                 if (textconv_one)
3606                         free(mf1.ptr);
3607                 if (textconv_two)
3608                         free(mf2.ptr);
3609                 xdiff_clear_find_func(&xecfg);
3610         }
3611
3612  free_ab_and_return:
3613         strbuf_release(&header);
3614         diff_free_filespec_data(one);
3615         diff_free_filespec_data(two);
3616         free(a_one);
3617         free(b_two);
3618         return;
3619 }
3620
3621 static char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
3622 {
3623         if (!is_renamed) {
3624                 if (p->status == DIFF_STATUS_ADDED) {
3625                         if (S_ISLNK(p->two->mode))
3626                                 return "new +l";
3627                         else if ((p->two->mode & 0777) == 0755)
3628                                 return "new +x";
3629                         else
3630                                 return "new";
3631                 } else if (p->status == DIFF_STATUS_DELETED)
3632                         return "gone";
3633         }
3634         if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
3635                 return "mode -l";
3636         else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
3637                 return "mode +l";
3638         else if ((p->one->mode & 0777) == 0644 &&
3639                  (p->two->mode & 0777) == 0755)
3640                 return "mode +x";
3641         else if ((p->one->mode & 0777) == 0755 &&
3642                  (p->two->mode & 0777) == 0644)
3643                 return "mode -x";
3644         return NULL;
3645 }
3646
3647 static void builtin_diffstat(const char *name_a, const char *name_b,
3648                              struct diff_filespec *one,
3649                              struct diff_filespec *two,
3650                              struct diffstat_t *diffstat,
3651                              struct diff_options *o,
3652                              struct diff_filepair *p)
3653 {
3654         mmfile_t mf1, mf2;
3655         struct diffstat_file *data;
3656         int same_contents;
3657         int complete_rewrite = 0;
3658
3659         if (!DIFF_PAIR_UNMERGED(p)) {
3660                 if (p->status == DIFF_STATUS_MODIFIED && p->score)
3661                         complete_rewrite = 1;
3662         }
3663
3664         data = diffstat_add(diffstat, name_a, name_b);
3665         data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
3666         if (o->flags.stat_with_summary)
3667                 data->comments = get_compact_summary(p, data->is_renamed);
3668
3669         if (!one || !two) {
3670                 data->is_unmerged = 1;
3671                 return;
3672         }
3673
3674         same_contents = oideq(&one->oid, &two->oid);
3675
3676         if (diff_filespec_is_binary(o->repo, one) ||
3677             diff_filespec_is_binary(o->repo, two)) {
3678                 data->is_binary = 1;
3679                 if (same_contents) {
3680                         data->added = 0;
3681                         data->deleted = 0;
3682                 } else {
3683                         data->added = diff_filespec_size(o->repo, two);
3684                         data->deleted = diff_filespec_size(o->repo, one);
3685                 }
3686         }
3687
3688         else if (complete_rewrite) {
3689                 diff_populate_filespec(o->repo, one, 0);
3690                 diff_populate_filespec(o->repo, two, 0);
3691                 data->deleted = count_lines(one->data, one->size);
3692                 data->added = count_lines(two->data, two->size);
3693         }
3694
3695         else if (!same_contents) {
3696                 /* Crazy xdl interfaces.. */
3697                 xpparam_t xpp;
3698                 xdemitconf_t xecfg;
3699
3700                 if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3701                     fill_mmfile(o->repo, &mf2, two) < 0)
3702                         die("unable to read files to diff");
3703
3704                 memset(&xpp, 0, sizeof(xpp));
3705                 memset(&xecfg, 0, sizeof(xecfg));
3706                 xpp.flags = o->xdl_opts;
3707                 xpp.anchors = o->anchors;
3708                 xpp.anchors_nr = o->anchors_nr;
3709                 xecfg.ctxlen = o->context;
3710                 xecfg.interhunkctxlen = o->interhunkcontext;
3711                 if (xdi_diff_outf(&mf1, &mf2, discard_hunk_line,
3712                                   diffstat_consume, diffstat, &xpp, &xecfg))
3713                         die("unable to generate diffstat for %s", one->path);
3714         }
3715
3716         diff_free_filespec_data(one);
3717         diff_free_filespec_data(two);
3718 }
3719
3720 static void builtin_checkdiff(const char *name_a, const char *name_b,
3721                               const char *attr_path,
3722                               struct diff_filespec *one,
3723                               struct diff_filespec *two,
3724                               struct diff_options *o)
3725 {
3726         mmfile_t mf1, mf2;
3727         struct checkdiff_t data;
3728
3729         if (!two)
3730                 return;
3731
3732         memset(&data, 0, sizeof(data));
3733         data.filename = name_b ? name_b : name_a;
3734         data.lineno = 0;
3735         data.o = o;
3736         data.ws_rule = whitespace_rule(o->repo->index, attr_path);
3737         data.conflict_marker_size = ll_merge_marker_size(o->repo->index, attr_path);
3738
3739         if (fill_mmfile(o->repo, &mf1, one) < 0 ||
3740             fill_mmfile(o->repo, &mf2, two) < 0)
3741                 die("unable to read files to diff");
3742
3743         /*
3744          * All the other codepaths check both sides, but not checking
3745          * the "old" side here is deliberate.  We are checking the newly
3746          * introduced changes, and as long as the "new" side is text, we
3747          * can and should check what it introduces.
3748          */
3749         if (diff_filespec_is_binary(o->repo, two))
3750                 goto free_and_return;
3751         else {
3752                 /* Crazy xdl interfaces.. */
3753                 xpparam_t xpp;
3754                 xdemitconf_t xecfg;
3755
3756                 memset(&xpp, 0, sizeof(xpp));
3757                 memset(&xecfg, 0, sizeof(xecfg));
3758                 xecfg.ctxlen = 1; /* at least one context line */
3759                 xpp.flags = 0;
3760                 if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume_hunk,
3761                                   checkdiff_consume, &data,
3762                                   &xpp, &xecfg))
3763                         die("unable to generate checkdiff for %s", one->path);
3764
3765                 if (data.ws_rule & WS_BLANK_AT_EOF) {
3766                         struct emit_callback ecbdata;
3767                         int blank_at_eof;
3768
3769                         ecbdata.ws_rule = data.ws_rule;
3770                         check_blank_at_eof(&mf1, &mf2, &ecbdata);
3771                         blank_at_eof = ecbdata.blank_at_eof_in_postimage;
3772
3773                         if (blank_at_eof) {
3774                                 static char *err;
3775                                 if (!err)
3776                                         err = whitespace_error_string(WS_BLANK_AT_EOF);
3777                                 fprintf(o->file, "%s:%d: %s.\n",
3778                                         data.filename, blank_at_eof, err);
3779                                 data.status = 1; /* report errors */
3780                         }
3781                 }
3782         }
3783  free_and_return:
3784         diff_free_filespec_data(one);
3785         diff_free_filespec_data(two);
3786         if (data.status)
3787                 o->flags.check_failed = 1;
3788 }
3789
3790 struct diff_filespec *alloc_filespec(const char *path)
3791 {
3792         struct diff_filespec *spec;
3793
3794         FLEXPTR_ALLOC_STR(spec, path, path);
3795         spec->count = 1;
3796         spec->is_binary = -1;
3797         return spec;
3798 }
3799
3800 void free_filespec(struct diff_filespec *spec)
3801 {
3802         if (!--spec->count) {
3803                 diff_free_filespec_data(spec);
3804                 free(spec);
3805         }
3806 }
3807
3808 void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
3809                    int oid_valid, unsigned short mode)
3810 {
3811         if (mode) {
3812                 spec->mode = canon_mode(mode);
3813                 oidcpy(&spec->oid, oid);
3814                 spec->oid_valid = oid_valid;
3815         }
3816 }
3817
3818 /*
3819  * Given a name and sha1 pair, if the index tells us the file in
3820  * the work tree has that object contents, return true, so that
3821  * prepare_temp_file() does not have to inflate and extract.
3822  */
3823 static int reuse_worktree_file(struct index_state *istate,
3824                                const char *name,
3825                                const struct object_id *oid,
3826                                int want_file)
3827 {
3828         const struct cache_entry *ce;
3829         struct stat st;
3830         int pos, len;
3831
3832         /*
3833          * We do not read the cache ourselves here, because the
3834          * benchmark with my previous version that always reads cache
3835          * shows that it makes things worse for diff-tree comparing
3836          * two linux-2.6 kernel trees in an already checked out work
3837          * tree.  This is because most diff-tree comparisons deal with
3838          * only a small number of files, while reading the cache is
3839          * expensive for a large project, and its cost outweighs the
3840          * savings we get by not inflating the object to a temporary
3841          * file.  Practically, this code only helps when we are used
3842          * by diff-cache --cached, which does read the cache before
3843          * calling us.
3844          */
3845         if (!istate->cache)
3846                 return 0;
3847
3848         /* We want to avoid the working directory if our caller
3849          * doesn't need the data in a normal file, this system
3850          * is rather slow with its stat/open/mmap/close syscalls,
3851          * and the object is contained in a pack file.  The pack
3852          * is probably already open and will be faster to obtain
3853          * the data through than the working directory.  Loose
3854          * objects however would tend to be slower as they need
3855          * to be individually opened and inflated.
3856          */
3857         if (!FAST_WORKING_DIRECTORY && !want_file && has_object_pack(oid))
3858                 return 0;
3859
3860         /*
3861          * Similarly, if we'd have to convert the file contents anyway, that
3862          * makes the optimization not worthwhile.
3863          */
3864         if (!want_file && would_convert_to_git(istate, name))
3865                 return 0;
3866
3867         len = strlen(name);
3868         pos = index_name_pos(istate, name, len);
3869         if (pos < 0)
3870                 return 0;
3871         ce = istate->cache[pos];
3872
3873         /*
3874          * This is not the sha1 we are looking for, or
3875          * unreusable because it is not a regular file.
3876          */
3877         if (!oideq(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
3878                 return 0;
3879
3880         /*
3881          * If ce is marked as "assume unchanged", there is no
3882          * guarantee that work tree matches what we are looking for.
3883          */
3884         if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
3885                 return 0;
3886
3887         /*
3888          * If ce matches the file in the work tree, we can reuse it.
3889          */
3890         if (ce_uptodate(ce) ||
3891             (!lstat(name, &st) && !ie_match_stat(istate, ce, &st, 0)))
3892                 return 1;
3893
3894         return 0;
3895 }
3896
3897 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
3898 {
3899         struct strbuf buf = STRBUF_INIT;
3900         char *dirty = "";
3901
3902         /* Are we looking at the work tree? */
3903         if (s->dirty_submodule)
3904                 dirty = "-dirty";
3905
3906         strbuf_addf(&buf, "Subproject commit %s%s\n",
3907                     oid_to_hex(&s->oid), dirty);
3908         s->size = buf.len;
3909         if (size_only) {
3910                 s->data = NULL;
3911                 strbuf_release(&buf);
3912         } else {
3913                 s->data = strbuf_detach(&buf, NULL);
3914                 s->should_free = 1;
3915         }
3916         return 0;
3917 }
3918
3919 /*
3920  * While doing rename detection and pickaxe operation, we may need to
3921  * grab the data for the blob (or file) for our own in-core comparison.
3922  * diff_filespec has data and size fields for this purpose.
3923  */
3924 int diff_populate_filespec(struct repository *r,
3925                            struct diff_filespec *s,
3926                            unsigned int flags)
3927 {
3928         int size_only = flags & CHECK_SIZE_ONLY;
3929         int err = 0;
3930         int conv_flags = global_conv_flags_eol;
3931         /*
3932          * demote FAIL to WARN to allow inspecting the situation
3933          * instead of refusing.
3934          */
3935         if (conv_flags & CONV_EOL_RNDTRP_DIE)
3936                 conv_flags = CONV_EOL_RNDTRP_WARN;
3937
3938         if (!DIFF_FILE_VALID(s))
3939                 die("internal error: asking to populate invalid file.");
3940         if (S_ISDIR(s->mode))
3941                 return -1;
3942
3943         if (s->data)
3944                 return 0;
3945
3946         if (size_only && 0 < s->size)
3947                 return 0;
3948
3949         if (S_ISGITLINK(s->mode))
3950                 return diff_populate_gitlink(s, size_only);
3951
3952         if (!s->oid_valid ||
3953             reuse_worktree_file(r->index, s->path, &s->oid, 0)) {
3954                 struct strbuf buf = STRBUF_INIT;
3955                 struct stat st;
3956                 int fd;
3957
3958                 if (lstat(s->path, &st) < 0) {
3959                 err_empty:
3960                         err = -1;
3961                 empty:
3962                         s->data = (char *)"";
3963                         s->size = 0;
3964                         return err;
3965                 }
3966                 s->size = xsize_t(st.st_size);
3967                 if (!s->size)
3968                         goto empty;
3969                 if (S_ISLNK(st.st_mode)) {
3970                         struct strbuf sb = STRBUF_INIT;
3971
3972                         if (strbuf_readlink(&sb, s->path, s->size))
3973                                 goto err_empty;
3974                         s->size = sb.len;
3975                         s->data = strbuf_detach(&sb, NULL);
3976                         s->should_free = 1;
3977                         return 0;
3978                 }
3979
3980                 /*
3981                  * Even if the caller would be happy with getting
3982                  * only the size, we cannot return early at this
3983                  * point if the path requires us to run the content
3984                  * conversion.
3985                  */
3986                 if (size_only && !would_convert_to_git(r->index, s->path))
3987                         return 0;
3988
3989                 /*
3990                  * Note: this check uses xsize_t(st.st_size) that may
3991                  * not be the true size of the blob after it goes
3992                  * through convert_to_git().  This may not strictly be
3993                  * correct, but the whole point of big_file_threshold
3994                  * and is_binary check being that we want to avoid
3995                  * opening the file and inspecting the contents, this
3996                  * is probably fine.
3997                  */
3998                 if ((flags & CHECK_BINARY) &&
3999                     s->size > big_file_threshold && s->is_binary == -1) {
4000                         s->is_binary = 1;
4001                         return 0;
4002                 }
4003                 fd = open(s->path, O_RDONLY);
4004                 if (fd < 0)
4005                         goto err_empty;
4006                 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
4007                 close(fd);
4008                 s->should_munmap = 1;
4009
4010                 /*
4011                  * Convert from working tree format to canonical git format
4012                  */
4013                 if (convert_to_git(r->index, s->path, s->data, s->size, &buf, conv_flags)) {
4014                         size_t size = 0;
4015                         munmap(s->data, s->size);
4016                         s->should_munmap = 0;
4017                         s->data = strbuf_detach(&buf, &size);
4018                         s->size = size;
4019                         s->should_free = 1;
4020                 }
4021         }
4022         else {
4023                 enum object_type type;
4024                 if (size_only || (flags & CHECK_BINARY)) {
4025                         type = oid_object_info(r, &s->oid, &s->size);
4026                         if (type < 0)
4027                                 die("unable to read %s",
4028                                     oid_to_hex(&s->oid));
4029                         if (size_only)
4030                                 return 0;
4031                         if (s->size > big_file_threshold && s->is_binary == -1) {
4032                                 s->is_binary = 1;
4033                                 return 0;
4034                         }
4035                 }
4036                 s->data = read_object_file(&s->oid, &type, &s->size);
4037                 if (!s->data)
4038                         die("unable to read %s", oid_to_hex(&s->oid));
4039                 s->should_free = 1;
4040         }
4041         return 0;
4042 }
4043
4044 void diff_free_filespec_blob(struct diff_filespec *s)
4045 {
4046         if (s->should_free)
4047                 free(s->data);
4048         else if (s->should_munmap)
4049                 munmap(s->data, s->size);
4050
4051         if (s->should_free || s->should_munmap) {
4052                 s->should_free = s->should_munmap = 0;
4053                 s->data = NULL;
4054         }
4055 }
4056
4057 void diff_free_filespec_data(struct diff_filespec *s)
4058 {
4059         diff_free_filespec_blob(s);
4060         FREE_AND_NULL(s->cnt_data);
4061 }
4062
4063 static void prep_temp_blob(struct index_state *istate,
4064                            const char *path, struct diff_tempfile *temp,
4065                            void *blob,
4066                            unsigned long size,
4067                            const struct object_id *oid,
4068                            int mode)
4069 {
4070         struct strbuf buf = STRBUF_INIT;
4071         struct strbuf tempfile = STRBUF_INIT;
4072         char *path_dup = xstrdup(path);
4073         const char *base = basename(path_dup);
4074
4075         /* Generate "XXXXXX_basename.ext" */
4076         strbuf_addstr(&tempfile, "XXXXXX_");
4077         strbuf_addstr(&tempfile, base);
4078
4079         temp->tempfile = mks_tempfile_ts(tempfile.buf, strlen(base) + 1);
4080         if (!temp->tempfile)
4081                 die_errno("unable to create temp-file");
4082         if (convert_to_working_tree(istate, path,
4083                         (const char *)blob, (size_t)size, &buf)) {
4084                 blob = buf.buf;
4085                 size = buf.len;
4086         }
4087         if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
4088             close_tempfile_gently(temp->tempfile))
4089                 die_errno("unable to write temp-file");
4090         temp->name = get_tempfile_path(temp->tempfile);
4091         oid_to_hex_r(temp->hex, oid);
4092         xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
4093         strbuf_release(&buf);
4094         strbuf_release(&tempfile);
4095         free(path_dup);
4096 }
4097
4098 static struct diff_tempfile *prepare_temp_file(struct repository *r,
4099                                                const char *name,
4100                                                struct diff_filespec *one)
4101 {
4102         struct diff_tempfile *temp = claim_diff_tempfile();
4103
4104         if (!DIFF_FILE_VALID(one)) {
4105         not_a_valid_file:
4106                 /* A '-' entry produces this for file-2, and
4107                  * a '+' entry produces this for file-1.
4108                  */
4109                 temp->name = "/dev/null";
4110                 xsnprintf(temp->hex, sizeof(temp->hex), ".");
4111                 xsnprintf(temp->mode, sizeof(temp->mode), ".");
4112                 return temp;
4113         }
4114
4115         if (!S_ISGITLINK(one->mode) &&
4116             (!one->oid_valid ||
4117              reuse_worktree_file(r->index, name, &one->oid, 1))) {
4118                 struct stat st;
4119                 if (lstat(name, &st) < 0) {
4120                         if (errno == ENOENT)
4121                                 goto not_a_valid_file;
4122                         die_errno("stat(%s)", name);
4123                 }
4124                 if (S_ISLNK(st.st_mode)) {
4125                         struct strbuf sb = STRBUF_INIT;
4126                         if (strbuf_readlink(&sb, name, st.st_size) < 0)
4127                                 die_errno("readlink(%s)", name);
4128                         prep_temp_blob(r->index, name, temp, sb.buf, sb.len,
4129                                        (one->oid_valid ?
4130                                         &one->oid : &null_oid),
4131                                        (one->oid_valid ?
4132                                         one->mode : S_IFLNK));
4133                         strbuf_release(&sb);
4134                 }
4135                 else {
4136                         /* we can borrow from the file in the work tree */
4137                         temp->name = name;
4138                         if (!one->oid_valid)
4139                                 oid_to_hex_r(temp->hex, &null_oid);
4140                         else
4141                                 oid_to_hex_r(temp->hex, &one->oid);
4142                         /* Even though we may sometimes borrow the
4143                          * contents from the work tree, we always want
4144                          * one->mode.  mode is trustworthy even when
4145                          * !(one->oid_valid), as long as
4146                          * DIFF_FILE_VALID(one).
4147                          */
4148                         xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
4149                 }
4150                 return temp;
4151         }
4152         else {
4153                 if (diff_populate_filespec(r, one, 0))
4154                         die("cannot read data blob for %s", one->path);
4155                 prep_temp_blob(r->index, name, temp,
4156                                one->data, one->size,
4157                                &one->oid, one->mode);
4158         }
4159         return temp;
4160 }
4161
4162 static void add_external_diff_name(struct repository *r,
4163                                    struct argv_array *argv,
4164                                    const char *name,
4165                                    struct diff_filespec *df)
4166 {
4167         struct diff_tempfile *temp = prepare_temp_file(r, name, df);
4168         argv_array_push(argv, temp->name);
4169         argv_array_push(argv, temp->hex);
4170         argv_array_push(argv, temp->mode);
4171 }
4172
4173 /* An external diff command takes:
4174  *
4175  * diff-cmd name infile1 infile1-sha1 infile1-mode \
4176  *               infile2 infile2-sha1 infile2-mode [ rename-to ]
4177  *
4178  */
4179 static void run_external_diff(const char *pgm,
4180                               const char *name,
4181                               const char *other,
4182                               struct diff_filespec *one,
4183                               struct diff_filespec *two,
4184                               const char *xfrm_msg,
4185                               struct diff_options *o)
4186 {
4187         struct argv_array argv = ARGV_ARRAY_INIT;
4188         struct argv_array env = ARGV_ARRAY_INIT;
4189         struct diff_queue_struct *q = &diff_queued_diff;
4190
4191         argv_array_push(&argv, pgm);
4192         argv_array_push(&argv, name);
4193
4194         if (one && two) {
4195                 add_external_diff_name(o->repo, &argv, name, one);
4196                 if (!other)
4197                         add_external_diff_name(o->repo, &argv, name, two);
4198                 else {
4199                         add_external_diff_name(o->repo, &argv, other, two);
4200                         argv_array_push(&argv, other);
4201                         argv_array_push(&argv, xfrm_msg);
4202                 }
4203         }
4204
4205         argv_array_pushf(&env, "GIT_DIFF_PATH_COUNTER=%d", ++o->diff_path_counter);
4206         argv_array_pushf(&env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
4207
4208         if (run_command_v_opt_cd_env(argv.argv, RUN_USING_SHELL, NULL, env.argv))
4209                 die(_("external diff died, stopping at %s"), name);
4210
4211         remove_tempfile();
4212         argv_array_clear(&argv);
4213         argv_array_clear(&env);
4214 }
4215
4216 static int similarity_index(struct diff_filepair *p)
4217 {
4218         return p->score * 100 / MAX_SCORE;
4219 }
4220
4221 static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
4222 {
4223         if (startup_info->have_repository)
4224                 return find_unique_abbrev(oid, abbrev);
4225         else {
4226                 char *hex = oid_to_hex(oid);
4227                 if (abbrev < 0)
4228                         abbrev = FALLBACK_DEFAULT_ABBREV;
4229                 if (abbrev > the_hash_algo->hexsz)
4230                         BUG("oid abbreviation out of range: %d", abbrev);
4231                 if (abbrev)
4232                         hex[abbrev] = '\0';
4233                 return hex;
4234         }
4235 }
4236
4237 static void fill_metainfo(struct strbuf *msg,
4238                           const char *name,
4239                           const char *other,
4240                           struct diff_filespec *one,
4241                           struct diff_filespec *two,
4242                           struct diff_options *o,
4243                           struct diff_filepair *p,
4244                           int *must_show_header,
4245                           int use_color)
4246 {
4247         const char *set = diff_get_color(use_color, DIFF_METAINFO);
4248         const char *reset = diff_get_color(use_color, DIFF_RESET);
4249         const char *line_prefix = diff_line_prefix(o);
4250
4251         *must_show_header = 1;
4252         strbuf_init(msg, PATH_MAX * 2 + 300);
4253         switch (p->status) {
4254         case DIFF_STATUS_COPIED:
4255                 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4256                             line_prefix, set, similarity_index(p));
4257                 strbuf_addf(msg, "%s\n%s%scopy from ",
4258                             reset,  line_prefix, set);
4259                 quote_c_style(name, msg, NULL, 0);
4260                 strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
4261                 quote_c_style(other, msg, NULL, 0);
4262                 strbuf_addf(msg, "%s\n", reset);
4263                 break;
4264         case DIFF_STATUS_RENAMED:
4265                 strbuf_addf(msg, "%s%ssimilarity index %d%%",
4266                             line_prefix, set, similarity_index(p));
4267                 strbuf_addf(msg, "%s\n%s%srename from ",
4268                             reset, line_prefix, set);
4269                 quote_c_style(name, msg, NULL, 0);
4270                 strbuf_addf(msg, "%s\n%s%srename to ",
4271                             reset, line_prefix, set);
4272                 quote_c_style(other, msg, NULL, 0);
4273                 strbuf_addf(msg, "%s\n", reset);
4274                 break;
4275         case DIFF_STATUS_MODIFIED:
4276                 if (p->score) {
4277                         strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
4278                                     line_prefix,
4279                                     set, similarity_index(p), reset);
4280                         break;
4281                 }
4282                 /* fallthru */
4283         default:
4284                 *must_show_header = 0;
4285         }
4286         if (one && two && !oideq(&one->oid, &two->oid)) {
4287                 const unsigned hexsz = the_hash_algo->hexsz;
4288                 int abbrev = o->flags.full_index ? hexsz : DEFAULT_ABBREV;
4289
4290                 if (o->flags.binary) {
4291                         mmfile_t mf;
4292                         if ((!fill_mmfile(o->repo, &mf, one) &&
4293                              diff_filespec_is_binary(o->repo, one)) ||
4294                             (!fill_mmfile(o->repo, &mf, two) &&
4295                              diff_filespec_is_binary(o->repo, two)))
4296                                 abbrev = hexsz;
4297                 }
4298                 strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
4299                             diff_abbrev_oid(&one->oid, abbrev),
4300                             diff_abbrev_oid(&two->oid, abbrev));
4301                 if (one->mode == two->mode)
4302                         strbuf_addf(msg, " %06o", one->mode);
4303                 strbuf_addf(msg, "%s\n", reset);
4304         }
4305 }
4306
4307 static void run_diff_cmd(const char *pgm,
4308                          const char *name,
4309                          const char *other,
4310                          const char *attr_path,
4311                          struct diff_filespec *one,
4312                          struct diff_filespec *two,
4313                          struct strbuf *msg,
4314                          struct diff_options *o,
4315                          struct diff_filepair *p)
4316 {
4317         const char *xfrm_msg = NULL;
4318         int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
4319         int must_show_header = 0;
4320
4321
4322         if (o->flags.allow_external) {
4323                 struct userdiff_driver *drv;
4324
4325                 drv = userdiff_find_by_path(o->repo->index, attr_path);
4326                 if (drv && drv->external)
4327                         pgm = drv->external;
4328         }
4329
4330         if (msg) {
4331                 /*
4332                  * don't use colors when the header is intended for an
4333                  * external diff driver
4334                  */
4335                 fill_metainfo(msg, name, other, one, two, o, p,
4336                               &must_show_header,
4337                               want_color(o->use_color) && !pgm);
4338                 xfrm_msg = msg->len ? msg->buf : NULL;
4339         }
4340
4341         if (pgm) {
4342                 run_external_diff(pgm, name, other, one, two, xfrm_msg, o);
4343                 return;
4344         }
4345         if (one && two)
4346                 builtin_diff(name, other ? other : name,
4347                              one, two, xfrm_msg, must_show_header,
4348                              o, complete_rewrite);
4349         else
4350                 fprintf(o->file, "* Unmerged path %s\n", name);
4351 }
4352
4353 static void diff_fill_oid_info(struct diff_filespec *one, struct index_state *istate)
4354 {
4355         if (DIFF_FILE_VALID(one)) {
4356                 if (!one->oid_valid) {
4357                         struct stat st;
4358                         if (one->is_stdin) {
4359                                 oidclr(&one->oid);
4360                                 return;
4361                         }
4362                         if (lstat(one->path, &st) < 0)
4363                                 die_errno("stat '%s'", one->path);
4364                         if (index_path(istate, &one->oid, one->path, &st, 0))
4365                                 die("cannot hash %s", one->path);
4366                 }
4367         }
4368         else
4369                 oidclr(&one->oid);
4370 }
4371
4372 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
4373 {
4374         /* Strip the prefix but do not molest /dev/null and absolute paths */
4375         if (*namep && !is_absolute_path(*namep)) {
4376                 *namep += prefix_length;
4377                 if (**namep == '/')
4378                         ++*namep;
4379         }
4380         if (*otherp && !is_absolute_path(*otherp)) {
4381                 *otherp += prefix_length;
4382                 if (**otherp == '/')
4383                         ++*otherp;
4384         }
4385 }
4386
4387 static void run_diff(struct diff_filepair *p, struct diff_options *o)
4388 {
4389         const char *pgm = external_diff();
4390         struct strbuf msg;
4391         struct diff_filespec *one = p->one;
4392         struct diff_filespec *two = p->two;
4393         const char *name;
4394         const char *other;
4395         const char *attr_path;
4396
4397         name  = one->path;
4398         other = (strcmp(name, two->path) ? two->path : NULL);
4399         attr_path = name;
4400         if (o->prefix_length)
4401                 strip_prefix(o->prefix_length, &name, &other);
4402
4403         if (!o->flags.allow_external)
4404                 pgm = NULL;
4405
4406         if (DIFF_PAIR_UNMERGED(p)) {
4407                 run_diff_cmd(pgm, name, NULL, attr_path,
4408                              NULL, NULL, NULL, o, p);
4409                 return;
4410         }
4411
4412         diff_fill_oid_info(one, o->repo->index);
4413         diff_fill_oid_info(two, o->repo->index);
4414
4415         if (!pgm &&
4416             DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
4417             (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
4418                 /*
4419                  * a filepair that changes between file and symlink
4420                  * needs to be split into deletion and creation.
4421                  */
4422                 struct diff_filespec *null = alloc_filespec(two->path);
4423                 run_diff_cmd(NULL, name, other, attr_path,
4424                              one, null, &msg,
4425                              o, p);
4426                 free(null);
4427                 strbuf_release(&msg);
4428
4429                 null = alloc_filespec(one->path);
4430                 run_diff_cmd(NULL, name, other, attr_path,
4431                              null, two, &msg, o, p);
4432                 free(null);
4433         }
4434         else
4435                 run_diff_cmd(pgm, name, other, attr_path,
4436                              one, two, &msg, o, p);
4437
4438         strbuf_release(&msg);
4439 }
4440
4441 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
4442                          struct diffstat_t *diffstat)
4443 {
4444         const char *name;
4445         const char *other;
4446
4447         if (DIFF_PAIR_UNMERGED(p)) {
4448                 /* unmerged */
4449                 builtin_diffstat(p->one->path, NULL, NULL, NULL,
4450                                  diffstat, o, p);
4451                 return;
4452         }
4453
4454         name = p->one->path;
4455         other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4456
4457         if (o->prefix_length)
4458                 strip_prefix(o->prefix_length, &name, &other);
4459
4460         diff_fill_oid_info(p->one, o->repo->index);
4461         diff_fill_oid_info(p->two, o->repo->index);
4462
4463         builtin_diffstat(name, other, p->one, p->two,
4464                          diffstat, o, p);
4465 }
4466
4467 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
4468 {
4469         const char *name;
4470         const char *other;
4471         const char *attr_path;
4472
4473         if (DIFF_PAIR_UNMERGED(p)) {
4474                 /* unmerged */
4475                 return;
4476         }
4477
4478         name = p->one->path;
4479         other = (strcmp(name, p->two->path) ? p->two->path : NULL);
4480         attr_path = other ? other : name;
4481
4482         if (o->prefix_length)
4483                 strip_prefix(o->prefix_length, &name, &other);
4484
4485         diff_fill_oid_info(p->one, o->repo->index);
4486         diff_fill_oid_info(p->two, o->repo->index);
4487
4488         builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
4489 }
4490
4491 static void prep_parse_options(struct diff_options *options);
4492
4493 void repo_diff_setup(struct repository *r, struct diff_options *options)
4494 {
4495         memcpy(options, &default_diff_options, sizeof(*options));
4496
4497         options->file = stdout;
4498         options->repo = r;
4499
4500         options->output_indicators[OUTPUT_INDICATOR_NEW] = '+';
4501         options->output_indicators[OUTPUT_INDICATOR_OLD] = '-';
4502         options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = ' ';
4503         options->abbrev = DEFAULT_ABBREV;
4504         options->line_termination = '\n';
4505         options->break_opt = -1;
4506         options->rename_limit = -1;
4507         options->dirstat_permille = diff_dirstat_permille_default;
4508         options->context = diff_context_default;
4509         options->interhunkcontext = diff_interhunk_context_default;
4510         options->ws_error_highlight = ws_error_highlight_default;
4511         options->flags.rename_empty = 1;
4512         options->objfind = NULL;
4513
4514         /* pathchange left =NULL by default */
4515         options->change = diff_change;
4516         options->add_remove = diff_addremove;
4517         options->use_color = diff_use_color_default;
4518         options->detect_rename = diff_detect_rename_default;
4519         options->xdl_opts |= diff_algorithm;
4520         if (diff_indent_heuristic)
4521                 DIFF_XDL_SET(options, INDENT_HEURISTIC);
4522
4523         options->orderfile = diff_order_file_cfg;
4524
4525         if (diff_no_prefix) {
4526                 options->a_prefix = options->b_prefix = "";
4527         } else if (!diff_mnemonic_prefix) {
4528                 options->a_prefix = "a/";
4529                 options->b_prefix = "b/";
4530         }
4531
4532         options->color_moved = diff_color_moved_default;
4533         options->color_moved_ws_handling = diff_color_moved_ws_default;
4534
4535         prep_parse_options(options);
4536 }
4537
4538 void diff_setup_done(struct diff_options *options)
4539 {
4540         unsigned check_mask = DIFF_FORMAT_NAME |
4541                               DIFF_FORMAT_NAME_STATUS |
4542                               DIFF_FORMAT_CHECKDIFF |
4543                               DIFF_FORMAT_NO_OUTPUT;
4544         /*
4545          * This must be signed because we're comparing against a potentially
4546          * negative value.
4547          */
4548         const int hexsz = the_hash_algo->hexsz;
4549
4550         if (options->set_default)
4551                 options->set_default(options);
4552
4553         if (HAS_MULTI_BITS(options->output_format & check_mask))
4554                 die(_("--name-only, --name-status, --check and -s are mutually exclusive"));
4555
4556         if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
4557                 die(_("-G, -S and --find-object are mutually exclusive"));
4558
4559         /*
4560          * Most of the time we can say "there are changes"
4561          * only by checking if there are changed paths, but
4562          * --ignore-whitespace* options force us to look
4563          * inside contents.
4564          */
4565
4566         if ((options->xdl_opts & XDF_WHITESPACE_FLAGS))
4567                 options->flags.diff_from_contents = 1;
4568         else
4569                 options->flags.diff_from_contents = 0;
4570
4571         if (options->flags.find_copies_harder)
4572                 options->detect_rename = DIFF_DETECT_COPY;
4573
4574         if (!options->flags.relative_name)
4575                 options->prefix = NULL;
4576         if (options->prefix)
4577                 options->prefix_length = strlen(options->prefix);
4578         else
4579                 options->prefix_length = 0;
4580
4581         if (options->output_format & (DIFF_FORMAT_NAME |
4582                                       DIFF_FORMAT_NAME_STATUS |
4583                                       DIFF_FORMAT_CHECKDIFF |
4584                                       DIFF_FORMAT_NO_OUTPUT))
4585                 options->output_format &= ~(DIFF_FORMAT_RAW |
4586                                             DIFF_FORMAT_NUMSTAT |
4587                                             DIFF_FORMAT_DIFFSTAT |
4588                                             DIFF_FORMAT_SHORTSTAT |
4589                                             DIFF_FORMAT_DIRSTAT |
4590                                             DIFF_FORMAT_SUMMARY |
4591                                             DIFF_FORMAT_PATCH);
4592
4593         /*
4594          * These cases always need recursive; we do not drop caller-supplied
4595          * recursive bits for other formats here.
4596          */
4597         if (options->output_format & (DIFF_FORMAT_PATCH |
4598                                       DIFF_FORMAT_NUMSTAT |
4599                                       DIFF_FORMAT_DIFFSTAT |
4600                                       DIFF_FORMAT_SHORTSTAT |
4601                                       DIFF_FORMAT_DIRSTAT |
4602                                       DIFF_FORMAT_SUMMARY |
4603                                       DIFF_FORMAT_CHECKDIFF))
4604                 options->flags.recursive = 1;
4605         /*
4606          * Also pickaxe would not work very well if you do not say recursive
4607          */
4608         if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
4609                 options->flags.recursive = 1;
4610         /*
4611          * When patches are generated, submodules diffed against the work tree
4612          * must be checked for dirtiness too so it can be shown in the output
4613          */
4614         if (options->output_format & DIFF_FORMAT_PATCH)
4615                 options->flags.dirty_submodules = 1;
4616
4617         if (options->detect_rename && options->rename_limit < 0)
4618                 options->rename_limit = diff_rename_limit_default;
4619         if (hexsz < options->abbrev)
4620                 options->abbrev = hexsz; /* full */
4621
4622         /*
4623          * It does not make sense to show the first hit we happened
4624          * to have found.  It does not make sense not to return with
4625          * exit code in such a case either.
4626          */
4627         if (options->flags.quick) {
4628                 options->output_format = DIFF_FORMAT_NO_OUTPUT;
4629                 options->flags.exit_with_status = 1;
4630         }
4631
4632         options->diff_path_counter = 0;
4633
4634         if (options->flags.follow_renames && options->pathspec.nr != 1)
4635                 die(_("--follow requires exactly one pathspec"));
4636
4637         if (!options->use_color || external_diff())
4638                 options->color_moved = 0;
4639
4640         FREE_AND_NULL(options->parseopts);
4641 }
4642
4643 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
4644 {
4645         char c, *eq;
4646         int len;
4647
4648         if (*arg != '-')
4649                 return 0;
4650         c = *++arg;
4651         if (!c)
4652                 return 0;
4653         if (c == arg_short) {
4654                 c = *++arg;
4655                 if (!c)
4656                         return 1;
4657                 if (val && isdigit(c)) {
4658                         char *end;
4659                         int n = strtoul(arg, &end, 10);
4660                         if (*end)
4661                                 return 0;
4662                         *val = n;
4663                         return 1;
4664                 }
4665                 return 0;
4666         }
4667         if (c != '-')
4668                 return 0;
4669         arg++;
4670         eq = strchrnul(arg, '=');
4671         len = eq - arg;
4672         if (!len || strncmp(arg, arg_long, len))
4673                 return 0;
4674         if (*eq) {
4675                 int n;
4676                 char *end;
4677                 if (!isdigit(*++eq))
4678                         return 0;
4679                 n = strtoul(eq, &end, 10);
4680                 if (*end)
4681                         return 0;
4682                 *val = n;
4683         }
4684         return 1;
4685 }
4686
4687 static inline int short_opt(char opt, const char **argv,
4688                             const char **optarg)
4689 {
4690         const char *arg = argv[0];
4691         if (arg[0] != '-' || arg[1] != opt)
4692                 return 0;
4693         if (arg[2] != '\0') {
4694                 *optarg = arg + 2;
4695                 return 1;
4696         }
4697         if (!argv[1])
4698                 die("Option '%c' requires a value", opt);
4699         *optarg = argv[1];
4700         return 2;
4701 }
4702
4703 int parse_long_opt(const char *opt, const char **argv,
4704                    const char **optarg)
4705 {
4706         const char *arg = argv[0];
4707         if (!skip_prefix(arg, "--", &arg))
4708                 return 0;
4709         if (!skip_prefix(arg, opt, &arg))
4710                 return 0;
4711         if (*arg == '=') { /* stuck form: --option=value */
4712                 *optarg = arg + 1;
4713                 return 1;
4714         }
4715         if (*arg != '\0')
4716                 return 0;
4717         /* separate form: --option value */
4718         if (!argv[1])
4719                 die("Option '--%s' requires a value", opt);
4720         *optarg = argv[1];
4721         return 2;
4722 }
4723
4724 static int diff_opt_stat(const struct option *opt, const char *value, int unset)
4725 {
4726         struct diff_options *options = opt->value;
4727         int width = options->stat_width;
4728         int name_width = options->stat_name_width;
4729         int graph_width = options->stat_graph_width;
4730         int count = options->stat_count;
4731         char *end;
4732
4733         BUG_ON_OPT_NEG(unset);
4734
4735         if (!strcmp(opt->long_name, "stat")) {
4736                 if (value) {
4737                         width = strtoul(value, &end, 10);
4738                         if (*end == ',')
4739                                 name_width = strtoul(end+1, &end, 10);
4740                         if (*end == ',')
4741                                 count = strtoul(end+1, &end, 10);
4742                         if (*end)
4743                                 return error(_("invalid --stat value: %s"), value);
4744                 }
4745         } else if (!strcmp(opt->long_name, "stat-width")) {
4746                 width = strtoul(value, &end, 10);
4747                 if (*end)
4748                         return error(_("%s expects a numerical value"),
4749                                      opt->long_name);
4750         } else if (!strcmp(opt->long_name, "stat-name-width")) {
4751                 name_width = strtoul(value, &end, 10);
4752                 if (*end)
4753                         return error(_("%s expects a numerical value"),
4754                                      opt->long_name);
4755         } else if (!strcmp(opt->long_name, "stat-graph-width")) {
4756                 graph_width = strtoul(value, &end, 10);
4757                 if (*end)
4758                         return error(_("%s expects a numerical value"),
4759                                      opt->long_name);
4760         } else if (!strcmp(opt->long_name, "stat-count")) {
4761                 count = strtoul(value, &end, 10);
4762                 if (*end)
4763                         return error(_("%s expects a numerical value"),
4764                                      opt->long_name);
4765         } else
4766                 BUG("%s should not get here", opt->long_name);
4767
4768         options->output_format |= DIFF_FORMAT_DIFFSTAT;
4769         options->stat_name_width = name_width;
4770         options->stat_graph_width = graph_width;
4771         options->stat_width = width;
4772         options->stat_count = count;
4773         return 0;
4774 }
4775
4776 static int parse_dirstat_opt(struct diff_options *options, const char *params)
4777 {
4778         struct strbuf errmsg = STRBUF_INIT;
4779         if (parse_dirstat_params(options, params, &errmsg))
4780                 die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
4781                     errmsg.buf);
4782         strbuf_release(&errmsg);
4783         /*
4784          * The caller knows a dirstat-related option is given from the command
4785          * line; allow it to say "return this_function();"
4786          */
4787         options->output_format |= DIFF_FORMAT_DIRSTAT;
4788         return 1;
4789 }
4790
4791 static const char diff_status_letters[] = {
4792         DIFF_STATUS_ADDED,
4793         DIFF_STATUS_COPIED,
4794         DIFF_STATUS_DELETED,
4795         DIFF_STATUS_MODIFIED,
4796         DIFF_STATUS_RENAMED,
4797         DIFF_STATUS_TYPE_CHANGED,
4798         DIFF_STATUS_UNKNOWN,
4799         DIFF_STATUS_UNMERGED,
4800         DIFF_STATUS_FILTER_AON,
4801         DIFF_STATUS_FILTER_BROKEN,
4802         '\0',
4803 };
4804
4805 static unsigned int filter_bit['Z' + 1];
4806
4807 static void prepare_filter_bits(void)
4808 {
4809         int i;
4810
4811         if (!filter_bit[DIFF_STATUS_ADDED]) {
4812                 for (i = 0; diff_status_letters[i]; i++)
4813                         filter_bit[(int) diff_status_letters[i]] = (1 << i);
4814         }
4815 }
4816
4817 static unsigned filter_bit_tst(char status, const struct diff_options *opt)
4818 {
4819         return opt->filter & filter_bit[(int) status];
4820 }
4821
4822 static int parse_diff_filter_opt(const char *optarg, struct diff_options *opt)
4823 {
4824         int i, optch;
4825
4826         prepare_filter_bits();
4827
4828         /*
4829          * If there is a negation e.g. 'd' in the input, and we haven't
4830          * initialized the filter field with another --diff-filter, start
4831          * from full set of bits, except for AON.
4832          */
4833         if (!opt->filter) {
4834                 for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4835                         if (optch < 'a' || 'z' < optch)
4836                                 continue;
4837                         opt->filter = (1 << (ARRAY_SIZE(diff_status_letters) - 1)) - 1;
4838                         opt->filter &= ~filter_bit[DIFF_STATUS_FILTER_AON];
4839                         break;
4840                 }
4841         }
4842
4843         for (i = 0; (optch = optarg[i]) != '\0'; i++) {
4844                 unsigned int bit;
4845                 int negate;
4846
4847                 if ('a' <= optch && optch <= 'z') {
4848                         negate = 1;
4849                         optch = toupper(optch);
4850                 } else {
4851                         negate = 0;
4852                 }
4853
4854                 bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
4855                 if (!bit)
4856                         return optarg[i];
4857                 if (negate)
4858                         opt->filter &= ~bit;
4859                 else
4860                         opt->filter |= bit;
4861         }
4862         return 0;
4863 }
4864
4865 static void enable_patch_output(int *fmt)
4866 {
4867         *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
4868         *fmt |= DIFF_FORMAT_PATCH;
4869 }
4870
4871 static int parse_ws_error_highlight_opt(struct diff_options *opt, const char *arg)
4872 {
4873         int val = parse_ws_error_highlight(arg);
4874
4875         if (val < 0) {
4876                 error("unknown value after ws-error-highlight=%.*s",
4877                       -1 - val, arg);
4878                 return 0;
4879         }
4880         opt->ws_error_highlight = val;
4881         return 1;
4882 }
4883
4884 static int parse_objfind_opt(struct diff_options *opt, const char *arg)
4885 {
4886         struct object_id oid;
4887
4888         if (get_oid(arg, &oid))
4889                 return error("unable to resolve '%s'", arg);
4890
4891         if (!opt->objfind)
4892                 opt->objfind = xcalloc(1, sizeof(*opt->objfind));
4893
4894         opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
4895         opt->flags.recursive = 1;
4896         opt->flags.tree_in_recursive = 1;
4897         oidset_insert(opt->objfind, &oid);
4898         return 1;
4899 }
4900
4901 static int diff_opt_anchored(const struct option *opt,
4902                              const char *arg, int unset)
4903 {
4904         struct diff_options *options = opt->value;
4905
4906         BUG_ON_OPT_NEG(unset);
4907         options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
4908         ALLOC_GROW(options->anchors, options->anchors_nr + 1,
4909                    options->anchors_alloc);
4910         options->anchors[options->anchors_nr++] = xstrdup(arg);
4911         return 0;
4912 }
4913
4914 static int diff_opt_binary(const struct option *opt,
4915                            const char *arg, int unset)
4916 {
4917         struct diff_options *options = opt->value;
4918
4919         BUG_ON_OPT_NEG(unset);
4920         BUG_ON_OPT_ARG(arg);
4921         enable_patch_output(&options->output_format);
4922         options->flags.binary = 1;
4923         return 0;
4924 }
4925
4926 static int diff_opt_break_rewrites(const struct option *opt,
4927                                    const char *arg, int unset)
4928 {
4929         int *break_opt = opt->value;
4930         int opt1, opt2;
4931
4932         BUG_ON_OPT_NEG(unset);
4933         if (!arg)
4934                 arg = "";
4935         opt1 = parse_rename_score(&arg);
4936         if (*arg == 0)
4937                 opt2 = 0;
4938         else if (*arg != '/')
4939                 return error(_("%s expects <n>/<m> form"), opt->long_name);
4940         else {
4941                 arg++;
4942                 opt2 = parse_rename_score(&arg);
4943         }
4944         if (*arg != 0)
4945                 return error(_("%s expects <n>/<m> form"), opt->long_name);
4946         *break_opt = opt1 | (opt2 << 16);
4947         return 0;
4948 }
4949
4950 static int diff_opt_char(const struct option *opt,
4951                          const char *arg, int unset)
4952 {
4953         char *value = opt->value;
4954
4955         BUG_ON_OPT_NEG(unset);
4956         if (arg[1])
4957                 return error(_("%s expects a character, got '%s'"),
4958                              opt->long_name, arg);
4959         *value = arg[0];
4960         return 0;
4961 }
4962
4963 static int diff_opt_color_words(const struct option *opt,
4964                                 const char *arg, int unset)
4965 {
4966         struct diff_options *options = opt->value;
4967
4968         BUG_ON_OPT_NEG(unset);
4969         options->use_color = 1;
4970         options->word_diff = DIFF_WORDS_COLOR;
4971         options->word_regex = arg;
4972         return 0;
4973 }
4974
4975 static int diff_opt_compact_summary(const struct option *opt,
4976                                     const char *arg, int unset)
4977 {
4978         struct diff_options *options = opt->value;
4979
4980         BUG_ON_OPT_ARG(arg);
4981         if (unset) {
4982                 options->flags.stat_with_summary = 0;
4983         } else {
4984                 options->flags.stat_with_summary = 1;
4985                 options->output_format |= DIFF_FORMAT_DIFFSTAT;
4986         }
4987         return 0;
4988 }
4989
4990 static int diff_opt_diff_algorithm(const struct option *opt,
4991                                    const char *arg, int unset)
4992 {
4993         struct diff_options *options = opt->value;
4994         long value = parse_algorithm_value(arg);
4995
4996         BUG_ON_OPT_NEG(unset);
4997         if (value < 0)
4998                 return error(_("option diff-algorithm accepts \"myers\", "
4999                                "\"minimal\", \"patience\" and \"histogram\""));
5000
5001         /* clear out previous settings */
5002         DIFF_XDL_CLR(options, NEED_MINIMAL);
5003         options->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
5004         options->xdl_opts |= value;
5005         return 0;
5006 }
5007
5008 static int diff_opt_dirstat(const struct option *opt,
5009                             const char *arg, int unset)
5010 {
5011         struct diff_options *options = opt->value;
5012
5013         BUG_ON_OPT_NEG(unset);
5014         if (!strcmp(opt->long_name, "cumulative")) {
5015                 if (arg)
5016                         BUG("how come --cumulative take a value?");
5017                 arg = "cumulative";
5018         } else if (!strcmp(opt->long_name, "dirstat-by-file"))
5019                 parse_dirstat_opt(options, "files");
5020         parse_dirstat_opt(options, arg ? arg : "");
5021         return 0;
5022 }
5023
5024 static int diff_opt_find_copies(const struct option *opt,
5025                                 const char *arg, int unset)
5026 {
5027         struct diff_options *options = opt->value;
5028
5029         BUG_ON_OPT_NEG(unset);
5030         if (!arg)
5031                 arg = "";
5032         options->rename_score = parse_rename_score(&arg);
5033         if (*arg != 0)
5034                 return error(_("invalid argument to %s"), opt->long_name);
5035
5036         if (options->detect_rename == DIFF_DETECT_COPY)
5037                 options->flags.find_copies_harder = 1;
5038         else
5039                 options->detect_rename = DIFF_DETECT_COPY;
5040
5041         return 0;
5042 }
5043
5044 static int diff_opt_find_renames(const struct option *opt,
5045                                  const char *arg, int unset)
5046 {
5047         struct diff_options *options = opt->value;
5048
5049         BUG_ON_OPT_NEG(unset);
5050         if (!arg)
5051                 arg = "";
5052         options->rename_score = parse_rename_score(&arg);
5053         if (*arg != 0)
5054                 return error(_("invalid argument to %s"), opt->long_name);
5055
5056         options->detect_rename = DIFF_DETECT_RENAME;
5057         return 0;
5058 }
5059
5060 static int diff_opt_follow(const struct option *opt,
5061                            const char *arg, int unset)
5062 {
5063         struct diff_options *options = opt->value;
5064
5065         BUG_ON_OPT_ARG(arg);
5066         if (unset) {
5067                 options->flags.follow_renames = 0;
5068                 options->flags.default_follow_renames = 0;
5069         } else {
5070                 options->flags.follow_renames = 1;
5071         }
5072         return 0;
5073 }
5074
5075 static int diff_opt_ignore_submodules(const struct option *opt,
5076                                       const char *arg, int unset)
5077 {
5078         struct diff_options *options = opt->value;
5079
5080         BUG_ON_OPT_NEG(unset);
5081         if (!arg)
5082                 arg = "all";
5083         options->flags.override_submodule_config = 1;
5084         handle_ignore_submodules_arg(options, arg);
5085         return 0;
5086 }
5087
5088 static enum parse_opt_result diff_opt_output(struct parse_opt_ctx_t *ctx,
5089                                              const struct option *opt,
5090                                              const char *arg, int unset)
5091 {
5092         struct diff_options *options = opt->value;
5093         char *path;
5094
5095         BUG_ON_OPT_NEG(unset);
5096         path = prefix_filename(ctx->prefix, arg);
5097         options->file = xfopen(path, "w");
5098         options->close_file = 1;
5099         if (options->use_color != GIT_COLOR_ALWAYS)
5100                 options->use_color = GIT_COLOR_NEVER;
5101         free(path);
5102         return 0;
5103 }
5104
5105 static int diff_opt_patience(const struct option *opt,
5106                              const char *arg, int unset)
5107 {
5108         struct diff_options *options = opt->value;
5109         int i;
5110
5111         BUG_ON_OPT_NEG(unset);
5112         BUG_ON_OPT_ARG(arg);
5113         options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
5114         /*
5115          * Both --patience and --anchored use PATIENCE_DIFF
5116          * internally, so remove any anchors previously
5117          * specified.
5118          */
5119         for (i = 0; i < options->anchors_nr; i++)
5120                 free(options->anchors[i]);
5121         options->anchors_nr = 0;
5122         return 0;
5123 }
5124
5125 static int diff_opt_relative(const struct option *opt,
5126                              const char *arg, int unset)
5127 {
5128         struct diff_options *options = opt->value;
5129
5130         BUG_ON_OPT_NEG(unset);
5131         options->flags.relative_name = 1;
5132         if (arg)
5133                 options->prefix = arg;
5134         return 0;
5135 }
5136
5137 static int diff_opt_submodule(const struct option *opt,
5138                               const char *arg, int unset)
5139 {
5140         struct diff_options *options = opt->value;
5141
5142         BUG_ON_OPT_NEG(unset);
5143         if (!arg)
5144                 arg = "log";
5145         if (parse_submodule_params(options, arg))
5146                 return error(_("failed to parse --submodule option parameter: '%s'"),
5147                              arg);
5148         return 0;
5149 }
5150
5151 static int diff_opt_textconv(const struct option *opt,
5152                              const char *arg, int unset)
5153 {
5154         struct diff_options *options = opt->value;
5155
5156         BUG_ON_OPT_ARG(arg);
5157         if (unset) {
5158                 options->flags.allow_textconv = 0;
5159         } else {
5160                 options->flags.allow_textconv = 1;
5161                 options->flags.textconv_set_via_cmdline = 1;
5162         }
5163         return 0;
5164 }
5165
5166 static int diff_opt_unified(const struct option *opt,
5167                             const char *arg, int unset)
5168 {
5169         struct diff_options *options = opt->value;
5170         char *s;
5171
5172         BUG_ON_OPT_NEG(unset);
5173
5174         options->context = strtol(arg, &s, 10);
5175         if (*s)
5176                 return error(_("%s expects a numerical value"), "--unified");
5177         enable_patch_output(&options->output_format);
5178
5179         return 0;
5180 }
5181
5182 static int diff_opt_word_diff(const struct option *opt,
5183                               const char *arg, int unset)
5184 {
5185         struct diff_options *options = opt->value;
5186
5187         BUG_ON_OPT_NEG(unset);
5188         if (arg) {
5189                 if (!strcmp(arg, "plain"))
5190                         options->word_diff = DIFF_WORDS_PLAIN;
5191                 else if (!strcmp(arg, "color")) {
5192                         options->use_color = 1;
5193                         options->word_diff = DIFF_WORDS_COLOR;
5194                 }
5195                 else if (!strcmp(arg, "porcelain"))
5196                         options->word_diff = DIFF_WORDS_PORCELAIN;
5197                 else if (!strcmp(arg, "none"))
5198                         options->word_diff = DIFF_WORDS_NONE;
5199                 else
5200                         return error(_("bad --word-diff argument: %s"), arg);
5201         } else {
5202                 if (options->word_diff == DIFF_WORDS_NONE)
5203                         options->word_diff = DIFF_WORDS_PLAIN;
5204         }
5205         return 0;
5206 }
5207
5208 static int diff_opt_word_diff_regex(const struct option *opt,
5209                                     const char *arg, int unset)
5210 {
5211         struct diff_options *options = opt->value;
5212
5213         BUG_ON_OPT_NEG(unset);
5214         if (options->word_diff == DIFF_WORDS_NONE)
5215                 options->word_diff = DIFF_WORDS_PLAIN;
5216         options->word_regex = arg;
5217         return 0;
5218 }
5219
5220 static void prep_parse_options(struct diff_options *options)
5221 {
5222         struct option parseopts[] = {
5223                 OPT_GROUP(N_("Diff output format options")),
5224                 OPT_BITOP('p', "patch", &options->output_format,
5225                           N_("generate patch"),
5226                           DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5227                 OPT_BIT_F('s', "no-patch", &options->output_format,
5228                           N_("suppress diff output"),
5229                           DIFF_FORMAT_NO_OUTPUT, PARSE_OPT_NONEG),
5230                 OPT_BITOP('u', NULL, &options->output_format,
5231                           N_("generate patch"),
5232                           DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
5233                 OPT_CALLBACK_F('U', "unified", options, N_("<n>"),
5234                                N_("generate diffs with <n> lines context"),
5235                                PARSE_OPT_NONEG, diff_opt_unified),
5236                 OPT_BOOL('W', "function-context", &options->flags.funccontext,
5237                          N_("generate diffs with <n> lines context")),
5238                 OPT_BIT_F(0, "raw", &options->output_format,
5239                           N_("generate the diff in raw format"),
5240                           DIFF_FORMAT_RAW, PARSE_OPT_NONEG),
5241                 OPT_BITOP(0, "patch-with-raw", &options->output_format,
5242                           N_("synonym for '-p --raw'"),
5243                           DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW,
5244                           DIFF_FORMAT_NO_OUTPUT),
5245                 OPT_BITOP(0, "patch-with-stat", &options->output_format,
5246                           N_("synonym for '-p --stat'"),
5247                           DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT,
5248                           DIFF_FORMAT_NO_OUTPUT),
5249                 OPT_BIT_F(0, "numstat", &options->output_format,
5250                           N_("machine friendly --stat"),
5251                           DIFF_FORMAT_NUMSTAT, PARSE_OPT_NONEG),
5252                 OPT_BIT_F(0, "shortstat", &options->output_format,
5253                           N_("output only the last line of --stat"),
5254                           DIFF_FORMAT_SHORTSTAT, PARSE_OPT_NONEG),
5255                 OPT_CALLBACK_F('X', "dirstat", options, N_("<param1,param2>..."),
5256                                N_("output the distribution of relative amount of changes for each sub-directory"),
5257                                PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5258                                diff_opt_dirstat),
5259                 OPT_CALLBACK_F(0, "cumulative", options, NULL,
5260                                N_("synonym for --dirstat=cumulative"),
5261                                PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5262                                diff_opt_dirstat),
5263                 OPT_CALLBACK_F(0, "dirstat-by-file", options, N_("<param1,param2>..."),
5264                                N_("synonym for --dirstat=files,param1,param2..."),
5265                                PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5266                                diff_opt_dirstat),
5267                 OPT_BIT_F(0, "check", &options->output_format,
5268                           N_("warn if changes introduce conflict markers or whitespace errors"),
5269                           DIFF_FORMAT_CHECKDIFF, PARSE_OPT_NONEG),
5270                 OPT_BIT_F(0, "summary", &options->output_format,
5271                           N_("condensed summary such as creations, renames and mode changes"),
5272                           DIFF_FORMAT_SUMMARY, PARSE_OPT_NONEG),
5273                 OPT_BIT_F(0, "name-only", &options->output_format,
5274                           N_("show only names of changed files"),
5275                           DIFF_FORMAT_NAME, PARSE_OPT_NONEG),
5276                 OPT_BIT_F(0, "name-status", &options->output_format,
5277                           N_("show only names and status of changed files"),
5278                           DIFF_FORMAT_NAME_STATUS, PARSE_OPT_NONEG),
5279                 OPT_CALLBACK_F(0, "stat", options, N_("<width>[,<name-width>[,<count>]]"),
5280                                N_("generate diffstat"),
5281                                PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_stat),
5282                 OPT_CALLBACK_F(0, "stat-width", options, N_("<width>"),
5283                                N_("generate diffstat with a given width"),
5284                                PARSE_OPT_NONEG, diff_opt_stat),
5285                 OPT_CALLBACK_F(0, "stat-name-width", options, N_("<width>"),
5286                                N_("generate diffstat with a given name width"),
5287                                PARSE_OPT_NONEG, diff_opt_stat),
5288                 OPT_CALLBACK_F(0, "stat-graph-width", options, N_("<width>"),
5289                                N_("generate diffstat with a given graph width"),
5290                                PARSE_OPT_NONEG, diff_opt_stat),
5291                 OPT_CALLBACK_F(0, "stat-count", options, N_("<count>"),
5292                                N_("generate diffstat with limited lines"),
5293                                PARSE_OPT_NONEG, diff_opt_stat),
5294                 OPT_CALLBACK_F(0, "compact-summary", options, NULL,
5295                                N_("generate compact summary in diffstat"),
5296                                PARSE_OPT_NOARG, diff_opt_compact_summary),
5297                 OPT_CALLBACK_F(0, "binary", options, NULL,
5298                                N_("output a binary diff that can be applied"),
5299                                PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_binary),
5300                 OPT_BOOL(0, "full-index", &options->flags.full_index,
5301                          N_("show full pre- and post-image object names on the \"index\" lines")),
5302                 OPT_COLOR_FLAG(0, "color", &options->use_color,
5303                                N_("show colored diff")),
5304                 OPT_CALLBACK_F(0, "output-indicator-new",
5305                                &options->output_indicators[OUTPUT_INDICATOR_NEW],
5306                                N_("<char>"),
5307                                N_("specify the character to indicate a new line instead of '+'"),
5308                                PARSE_OPT_NONEG, diff_opt_char),
5309                 OPT_CALLBACK_F(0, "output-indicator-old",
5310                                &options->output_indicators[OUTPUT_INDICATOR_OLD],
5311                                N_("<char>"),
5312                                N_("specify the character to indicate an old line instead of '-'"),
5313                                PARSE_OPT_NONEG, diff_opt_char),
5314                 OPT_CALLBACK_F(0, "output-indicator-context",
5315                                &options->output_indicators[OUTPUT_INDICATOR_CONTEXT],
5316                                N_("<char>"),
5317                                N_("specify the character to indicate a context instead of ' '"),
5318                                PARSE_OPT_NONEG, diff_opt_char),
5319
5320                 OPT_GROUP(N_("Diff rename options")),
5321                 OPT_CALLBACK_F('B', "break-rewrites", &options->break_opt, N_("<n>[/<m>]"),
5322                                N_("break complete rewrite changes into pairs of delete and create"),
5323                                PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5324                                diff_opt_break_rewrites),
5325                 OPT_CALLBACK_F('M', "find-renames", options, N_("<n>"),
5326                                N_("detect renames"),
5327                                PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5328                                diff_opt_find_renames),
5329                 OPT_SET_INT_F('D', "irreversible-delete", &options->irreversible_delete,
5330                               N_("omit the preimage for deletes"),
5331                               1, PARSE_OPT_NONEG),
5332                 OPT_CALLBACK_F('C', "find-copies", options, N_("<n>"),
5333                                N_("detect copies"),
5334                                PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5335                                diff_opt_find_copies),
5336                 OPT_BOOL(0, "find-copies-harder", &options->flags.find_copies_harder,
5337                          N_("use unmodified files as source to find copies")),
5338                 OPT_SET_INT_F(0, "no-renames", &options->detect_rename,
5339                               N_("disable rename detection"),
5340                               0, PARSE_OPT_NONEG),
5341                 OPT_BOOL(0, "rename-empty", &options->flags.rename_empty,
5342                          N_("use empty blobs as rename source")),
5343                 OPT_CALLBACK_F(0, "follow", options, NULL,
5344                                N_("continue listing the history of a file beyond renames"),
5345                                PARSE_OPT_NOARG, diff_opt_follow),
5346
5347                 OPT_GROUP(N_("Diff algorithm options")),
5348                 OPT_BIT(0, "minimal", &options->xdl_opts,
5349                         N_("produce the smallest possible diff"),
5350                         XDF_NEED_MINIMAL),
5351                 OPT_BIT_F('w', "ignore-all-space", &options->xdl_opts,
5352                           N_("ignore whitespace when comparing lines"),
5353                           XDF_IGNORE_WHITESPACE, PARSE_OPT_NONEG),
5354                 OPT_BIT_F('b', "ignore-space-change", &options->xdl_opts,
5355                           N_("ignore changes in amount of whitespace"),
5356                           XDF_IGNORE_WHITESPACE_CHANGE, PARSE_OPT_NONEG),
5357                 OPT_BIT_F(0, "ignore-space-at-eol", &options->xdl_opts,
5358                           N_("ignore changes in whitespace at EOL"),
5359                           XDF_IGNORE_WHITESPACE_AT_EOL, PARSE_OPT_NONEG),
5360                 OPT_BIT_F(0, "ignore-cr-at-eol", &options->xdl_opts,
5361                           N_("ignore carrier-return at the end of line"),
5362                           XDF_IGNORE_CR_AT_EOL, PARSE_OPT_NONEG),
5363                 OPT_BIT_F(0, "ignore-blank-lines", &options->xdl_opts,
5364                           N_("ignore changes whose lines are all blank"),
5365                           XDF_IGNORE_BLANK_LINES, PARSE_OPT_NONEG),
5366                 OPT_BIT(0, "indent-heuristic", &options->xdl_opts,
5367                         N_("heuristic to shift diff hunk boundaries for easy reading"),
5368                         XDF_INDENT_HEURISTIC),
5369                 OPT_CALLBACK_F(0, "patience", options, NULL,
5370                                N_("generate diff using the \"patience diff\" algorithm"),
5371                                PARSE_OPT_NONEG | PARSE_OPT_NOARG,
5372                                diff_opt_patience),
5373                 OPT_BITOP(0, "histogram", &options->xdl_opts,
5374                           N_("generate diff using the \"histogram diff\" algorithm"),
5375                           XDF_HISTOGRAM_DIFF, XDF_DIFF_ALGORITHM_MASK),
5376                 OPT_CALLBACK_F(0, "diff-algorithm", options, N_("<algorithm>"),
5377                                N_("choose a diff algorithm"),
5378                                PARSE_OPT_NONEG, diff_opt_diff_algorithm),
5379                 OPT_CALLBACK_F(0, "anchored", options, N_("<text>"),
5380                                N_("generate diff using the \"anchored diff\" algorithm"),
5381                                PARSE_OPT_NONEG, diff_opt_anchored),
5382                 OPT_CALLBACK_F(0, "word-diff", options, N_("<mode>"),
5383                                N_("show word diff, using <mode> to delimit changed words"),
5384                                PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_word_diff),
5385                 OPT_CALLBACK_F(0, "word-diff-regex", options, N_("<regex>"),
5386                                N_("use <regex> to decide what a word is"),
5387                                PARSE_OPT_NONEG, diff_opt_word_diff_regex),
5388                 OPT_CALLBACK_F(0, "color-words", options, N_("<regex>"),
5389                                N_("equivalent to --word-diff=color --word-diff-regex=<regex>"),
5390                                PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_color_words),
5391
5392                 OPT_GROUP(N_("Diff other options")),
5393                 OPT_CALLBACK_F(0, "relative", options, N_("<prefix>"),
5394                                N_("when run from subdir, exclude changes outside and show relative paths"),
5395                                PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5396                                diff_opt_relative),
5397                 OPT_BOOL('a', "text", &options->flags.text,
5398                          N_("treat all files as text")),
5399                 OPT_BOOL('R', NULL, &options->flags.reverse_diff,
5400                          N_("swap two inputs, reverse the diff")),
5401                 OPT_BOOL(0, "exit-code", &options->flags.exit_with_status,
5402                          N_("exit with 1 if there were differences, 0 otherwise")),
5403                 OPT_BOOL(0, "quiet", &options->flags.quick,
5404                          N_("disable all output of the program")),
5405                 OPT_BOOL(0, "ext-diff", &options->flags.allow_external,
5406                          N_("allow an external diff helper to be executed")),
5407                 OPT_CALLBACK_F(0, "textconv", options, NULL,
5408                                N_("run external text conversion filters when comparing binary files"),
5409                                PARSE_OPT_NOARG, diff_opt_textconv),
5410                 OPT_CALLBACK_F(0, "ignore-submodules", options, N_("<when>"),
5411                                N_("ignore changes to submodules in the diff generation"),
5412                                PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5413                                diff_opt_ignore_submodules),
5414                 OPT_CALLBACK_F(0, "submodule", options, N_("<format>"),
5415                                N_("specify how differences in submodules are shown"),
5416                                PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
5417                                diff_opt_submodule),
5418                 { OPTION_CALLBACK, 0, "output", options, N_("<file>"),
5419                   N_("Output to a specific file"),
5420                   PARSE_OPT_NONEG, NULL, 0, diff_opt_output },
5421
5422                 OPT_END()
5423         };
5424
5425         ALLOC_ARRAY(options->parseopts, ARRAY_SIZE(parseopts));
5426         memcpy(options->parseopts, parseopts, sizeof(parseopts));
5427 }
5428
5429 int diff_opt_parse(struct diff_options *options,
5430                    const char **av, int ac, const char *prefix)
5431 {
5432         const char *arg = av[0];
5433         const char *optarg;
5434         int argcount;
5435
5436         if (!prefix)
5437                 prefix = "";
5438
5439         ac = parse_options(ac, av, prefix, options->parseopts, NULL,
5440                            PARSE_OPT_KEEP_DASHDASH |
5441                            PARSE_OPT_KEEP_UNKNOWN |
5442                            PARSE_OPT_NO_INTERNAL_HELP |
5443                            PARSE_OPT_ONE_SHOT |
5444                            PARSE_OPT_STOP_AT_NON_OPTION);
5445
5446         if (ac)
5447                 return ac;
5448
5449         /* flags options */
5450         if (!strcmp(arg, "--color-moved")) {
5451                 if (diff_color_moved_default)
5452                         options->color_moved = diff_color_moved_default;
5453                 if (options->color_moved == COLOR_MOVED_NO)
5454                         options->color_moved = COLOR_MOVED_DEFAULT;
5455         } else if (!strcmp(arg, "--no-color-moved"))
5456                 options->color_moved = COLOR_MOVED_NO;
5457         else if (skip_prefix(arg, "--color-moved=", &arg)) {
5458                 int cm = parse_color_moved(arg);
5459                 if (cm < 0)
5460                         return error("bad --color-moved argument: %s", arg);
5461                 options->color_moved = cm;
5462         } else if (!strcmp(arg, "--no-color-moved-ws")) {
5463                 options->color_moved_ws_handling = 0;
5464         } else if (skip_prefix(arg, "--color-moved-ws=", &arg)) {
5465                 unsigned cm = parse_color_moved_ws(arg);
5466                 if (cm & COLOR_MOVED_WS_ERROR)
5467                         return -1;
5468                 options->color_moved_ws_handling = cm;
5469         } else if (skip_prefix(arg, "--ws-error-highlight=", &arg))
5470                 return parse_ws_error_highlight_opt(options, arg);
5471         else if (!strcmp(arg, "--ita-invisible-in-index"))
5472                 options->ita_invisible_in_index = 1;
5473         else if (!strcmp(arg, "--ita-visible-in-index"))
5474                 options->ita_invisible_in_index = 0;
5475
5476         /* misc options */
5477         else if (!strcmp(arg, "-z"))
5478                 options->line_termination = 0;
5479         else if ((argcount = short_opt('l', av, &optarg))) {
5480                 options->rename_limit = strtoul(optarg, NULL, 10);
5481                 return argcount;
5482         }
5483         else if ((argcount = short_opt('S', av, &optarg))) {
5484                 options->pickaxe = optarg;
5485                 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
5486                 return argcount;
5487         } else if ((argcount = short_opt('G', av, &optarg))) {
5488                 options->pickaxe = optarg;
5489                 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
5490                 return argcount;
5491         }
5492         else if (!strcmp(arg, "--pickaxe-all"))
5493                 options->pickaxe_opts |= DIFF_PICKAXE_ALL;
5494         else if (!strcmp(arg, "--pickaxe-regex"))
5495                 options->pickaxe_opts |= DIFF_PICKAXE_REGEX;
5496         else if ((argcount = short_opt('O', av, &optarg))) {
5497                 options->orderfile = prefix_filename(prefix, optarg);
5498                 return argcount;
5499         } else if (skip_prefix(arg, "--find-object=", &arg))
5500                 return parse_objfind_opt(options, arg);
5501         else if ((argcount = parse_long_opt("diff-filter", av, &optarg))) {
5502                 int offending = parse_diff_filter_opt(optarg, options);
5503                 if (offending)
5504                         die("unknown change class '%c' in --diff-filter=%s",
5505                             offending, optarg);
5506                 return argcount;
5507         }
5508         else if (!strcmp(arg, "--no-abbrev"))
5509                 options->abbrev = 0;
5510         else if (!strcmp(arg, "--abbrev"))
5511                 options->abbrev = DEFAULT_ABBREV;
5512         else if (skip_prefix(arg, "--abbrev=", &arg)) {
5513                 options->abbrev = strtoul(arg, NULL, 10);
5514                 if (options->abbrev < MINIMUM_ABBREV)
5515                         options->abbrev = MINIMUM_ABBREV;
5516                 else if (the_hash_algo->hexsz < options->abbrev)
5517                         options->abbrev = the_hash_algo->hexsz;
5518         }
5519         else if ((argcount = parse_long_opt("src-prefix", av, &optarg))) {
5520                 options->a_prefix = optarg;
5521                 return argcount;
5522         }
5523         else if ((argcount = parse_long_opt("line-prefix", av, &optarg))) {
5524                 options->line_prefix = optarg;
5525                 options->line_prefix_length = strlen(options->line_prefix);
5526                 graph_setup_line_prefix(options);
5527                 return argcount;
5528         }
5529         else if ((argcount = parse_long_opt("dst-prefix", av, &optarg))) {
5530                 options->b_prefix = optarg;
5531                 return argcount;
5532         }
5533         else if (!strcmp(arg, "--no-prefix"))
5534                 options->a_prefix = options->b_prefix = "";
5535         else if (opt_arg(arg, '\0', "inter-hunk-context",
5536                          &options->interhunkcontext))
5537                 ;
5538         else
5539                 return 0;
5540         return 1;
5541 }
5542
5543 int parse_rename_score(const char **cp_p)
5544 {
5545         unsigned long num, scale;
5546         int ch, dot;
5547         const char *cp = *cp_p;
5548
5549         num = 0;
5550         scale = 1;
5551         dot = 0;
5552         for (;;) {
5553                 ch = *cp;
5554                 if ( !dot && ch == '.' ) {
5555                         scale = 1;
5556                         dot = 1;
5557                 } else if ( ch == '%' ) {
5558                         scale = dot ? scale*100 : 100;
5559                         cp++;   /* % is always at the end */
5560                         break;
5561                 } else if ( ch >= '0' && ch <= '9' ) {
5562                         if ( scale < 100000 ) {
5563                                 scale *= 10;
5564                                 num = (num*10) + (ch-'0');
5565                         }
5566                 } else {
5567                         break;
5568                 }
5569                 cp++;
5570         }
5571         *cp_p = cp;
5572
5573         /* user says num divided by scale and we say internally that
5574          * is MAX_SCORE * num / scale.
5575          */
5576         return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
5577 }
5578
5579 struct diff_queue_struct diff_queued_diff;
5580
5581 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
5582 {
5583         ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
5584         queue->queue[queue->nr++] = dp;
5585 }
5586
5587 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
5588                                  struct diff_filespec *one,
5589                                  struct diff_filespec *two)
5590 {
5591         struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
5592         dp->one = one;
5593         dp->two = two;
5594         if (queue)
5595                 diff_q(queue, dp);
5596         return dp;
5597 }
5598
5599 void diff_free_filepair(struct diff_filepair *p)
5600 {
5601         free_filespec(p->one);
5602         free_filespec(p->two);
5603         free(p);
5604 }
5605
5606 const char *diff_aligned_abbrev(const struct object_id *oid, int len)
5607 {
5608         int abblen;
5609         const char *abbrev;
5610
5611         /* Do we want all 40 hex characters? */
5612         if (len == the_hash_algo->hexsz)
5613                 return oid_to_hex(oid);
5614
5615         /* An abbreviated value is fine, possibly followed by an ellipsis. */
5616         abbrev = diff_abbrev_oid(oid, len);
5617
5618         if (!print_sha1_ellipsis())
5619                 return abbrev;
5620
5621         abblen = strlen(abbrev);
5622
5623         /*
5624          * In well-behaved cases, where the abbreviated result is the
5625          * same as the requested length, append three dots after the
5626          * abbreviation (hence the whole logic is limited to the case
5627          * where abblen < 37); when the actual abbreviated result is a
5628          * bit longer than the requested length, we reduce the number
5629          * of dots so that they match the well-behaved ones.  However,
5630          * if the actual abbreviation is longer than the requested
5631          * length by more than three, we give up on aligning, and add
5632          * three dots anyway, to indicate that the output is not the
5633          * full object name.  Yes, this may be suboptimal, but this
5634          * appears only in "diff --raw --abbrev" output and it is not
5635          * worth the effort to change it now.  Note that this would
5636          * likely to work fine when the automatic sizing of default
5637          * abbreviation length is used--we would be fed -1 in "len" in
5638          * that case, and will end up always appending three-dots, but
5639          * the automatic sizing is supposed to give abblen that ensures
5640          * uniqueness across all objects (statistically speaking).
5641          */
5642         if (abblen < the_hash_algo->hexsz - 3) {
5643                 static char hex[GIT_MAX_HEXSZ + 1];
5644                 if (len < abblen && abblen <= len + 2)
5645                         xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
5646                 else
5647                         xsnprintf(hex, sizeof(hex), "%s...", abbrev);
5648                 return hex;
5649         }
5650
5651         return oid_to_hex(oid);
5652 }
5653
5654 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
5655 {
5656         int line_termination = opt->line_termination;
5657         int inter_name_termination = line_termination ? '\t' : '\0';
5658
5659         fprintf(opt->file, "%s", diff_line_prefix(opt));
5660         if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
5661                 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
5662                         diff_aligned_abbrev(&p->one->oid, opt->abbrev));
5663                 fprintf(opt->file, "%s ",
5664                         diff_aligned_abbrev(&p->two->oid, opt->abbrev));
5665         }
5666         if (p->score) {
5667                 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
5668                         inter_name_termination);
5669         } else {
5670                 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
5671         }
5672
5673         if (p->status == DIFF_STATUS_COPIED ||
5674             p->status == DIFF_STATUS_RENAMED) {
5675                 const char *name_a, *name_b;
5676                 name_a = p->one->path;
5677                 name_b = p->two->path;
5678                 strip_prefix(opt->prefix_length, &name_a, &name_b);
5679                 write_name_quoted(name_a, opt->file, inter_name_termination);
5680                 write_name_quoted(name_b, opt->file, line_termination);
5681         } else {
5682                 const char *name_a, *name_b;
5683                 name_a = p->one->mode ? p->one->path : p->two->path;
5684                 name_b = NULL;
5685                 strip_prefix(opt->prefix_length, &name_a, &name_b);
5686                 write_name_quoted(name_a, opt->file, line_termination);
5687         }
5688 }
5689
5690 int diff_unmodified_pair(struct diff_filepair *p)
5691 {
5692         /* This function is written stricter than necessary to support
5693          * the currently implemented transformers, but the idea is to
5694          * let transformers to produce diff_filepairs any way they want,
5695          * and filter and clean them up here before producing the output.
5696          */
5697         struct diff_filespec *one = p->one, *two = p->two;
5698
5699         if (DIFF_PAIR_UNMERGED(p))
5700                 return 0; /* unmerged is interesting */
5701
5702         /* deletion, addition, mode or type change
5703          * and rename are all interesting.
5704          */
5705         if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
5706             DIFF_PAIR_MODE_CHANGED(p) ||
5707             strcmp(one->path, two->path))
5708                 return 0;
5709
5710         /* both are valid and point at the same path.  that is, we are
5711          * dealing with a change.
5712          */
5713         if (one->oid_valid && two->oid_valid &&
5714             oideq(&one->oid, &two->oid) &&
5715             !one->dirty_submodule && !two->dirty_submodule)
5716                 return 1; /* no change */
5717         if (!one->oid_valid && !two->oid_valid)
5718                 return 1; /* both look at the same file on the filesystem. */
5719         return 0;
5720 }
5721
5722 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
5723 {
5724         if (diff_unmodified_pair(p))
5725                 return;
5726
5727         if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5728             (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5729                 return; /* no tree diffs in patch format */
5730
5731         run_diff(p, o);
5732 }
5733
5734 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
5735                             struct diffstat_t *diffstat)
5736 {
5737         if (diff_unmodified_pair(p))
5738                 return;
5739
5740         if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5741             (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5742                 return; /* no useful stat for tree diffs */
5743
5744         run_diffstat(p, o, diffstat);
5745 }
5746
5747 static void diff_flush_checkdiff(struct diff_filepair *p,
5748                 struct diff_options *o)
5749 {
5750         if (diff_unmodified_pair(p))
5751                 return;
5752
5753         if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
5754             (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
5755                 return; /* nothing to check in tree diffs */
5756
5757         run_checkdiff(p, o);
5758 }
5759
5760 int diff_queue_is_empty(void)
5761 {
5762         struct diff_queue_struct *q = &diff_queued_diff;
5763         int i;
5764         for (i = 0; i < q->nr; i++)
5765                 if (!diff_unmodified_pair(q->queue[i]))
5766                         return 0;
5767         return 1;
5768 }
5769
5770 #if DIFF_DEBUG
5771 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
5772 {
5773         fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
5774                 x, one ? one : "",
5775                 s->path,
5776                 DIFF_FILE_VALID(s) ? "valid" : "invalid",
5777                 s->mode,
5778                 s->oid_valid ? oid_to_hex(&s->oid) : "");
5779         fprintf(stderr, "queue[%d] %s size %lu\n",
5780                 x, one ? one : "",
5781                 s->size);
5782 }
5783
5784 void diff_debug_filepair(const struct diff_filepair *p, int i)
5785 {
5786         diff_debug_filespec(p->one, i, "one");
5787         diff_debug_filespec(p->two, i, "two");
5788         fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
5789                 p->score, p->status ? p->status : '?',
5790                 p->one->rename_used, p->broken_pair);
5791 }
5792
5793 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
5794 {
5795         int i;
5796         if (msg)
5797                 fprintf(stderr, "%s\n", msg);
5798         fprintf(stderr, "q->nr = %d\n", q->nr);
5799         for (i = 0; i < q->nr; i++) {
5800                 struct diff_filepair *p = q->queue[i];
5801                 diff_debug_filepair(p, i);
5802         }
5803 }
5804 #endif
5805
5806 static void diff_resolve_rename_copy(void)
5807 {
5808         int i;
5809         struct diff_filepair *p;
5810         struct diff_queue_struct *q = &diff_queued_diff;
5811
5812         diff_debug_queue("resolve-rename-copy", q);
5813
5814         for (i = 0; i < q->nr; i++) {
5815                 p = q->queue[i];
5816                 p->status = 0; /* undecided */
5817                 if (DIFF_PAIR_UNMERGED(p))
5818                         p->status = DIFF_STATUS_UNMERGED;
5819                 else if (!DIFF_FILE_VALID(p->one))
5820                         p->status = DIFF_STATUS_ADDED;
5821                 else if (!DIFF_FILE_VALID(p->two))
5822                         p->status = DIFF_STATUS_DELETED;
5823                 else if (DIFF_PAIR_TYPE_CHANGED(p))
5824                         p->status = DIFF_STATUS_TYPE_CHANGED;
5825
5826                 /* from this point on, we are dealing with a pair
5827                  * whose both sides are valid and of the same type, i.e.
5828                  * either in-place edit or rename/copy edit.
5829                  */
5830                 else if (DIFF_PAIR_RENAME(p)) {
5831                         /*
5832                          * A rename might have re-connected a broken
5833                          * pair up, causing the pathnames to be the
5834                          * same again. If so, that's not a rename at
5835                          * all, just a modification..
5836                          *
5837                          * Otherwise, see if this source was used for
5838                          * multiple renames, in which case we decrement
5839                          * the count, and call it a copy.
5840                          */
5841                         if (!strcmp(p->one->path, p->two->path))
5842                                 p->status = DIFF_STATUS_MODIFIED;
5843                         else if (--p->one->rename_used > 0)
5844                                 p->status = DIFF_STATUS_COPIED;
5845                         else
5846                                 p->status = DIFF_STATUS_RENAMED;
5847                 }
5848                 else if (!oideq(&p->one->oid, &p->two->oid) ||
5849                          p->one->mode != p->two->mode ||
5850                          p->one->dirty_submodule ||
5851                          p->two->dirty_submodule ||
5852                          is_null_oid(&p->one->oid))
5853                         p->status = DIFF_STATUS_MODIFIED;
5854                 else {
5855                         /* This is a "no-change" entry and should not
5856                          * happen anymore, but prepare for broken callers.
5857                          */
5858                         error("feeding unmodified %s to diffcore",
5859                               p->one->path);
5860                         p->status = DIFF_STATUS_UNKNOWN;
5861                 }
5862         }
5863         diff_debug_queue("resolve-rename-copy done", q);
5864 }
5865
5866 static int check_pair_status(struct diff_filepair *p)
5867 {
5868         switch (p->status) {
5869         case DIFF_STATUS_UNKNOWN:
5870                 return 0;
5871         case 0:
5872                 die("internal error in diff-resolve-rename-copy");
5873         default:
5874                 return 1;
5875         }
5876 }
5877
5878 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
5879 {
5880         int fmt = opt->output_format;
5881
5882         if (fmt & DIFF_FORMAT_CHECKDIFF)
5883                 diff_flush_checkdiff(p, opt);
5884         else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
5885                 diff_flush_raw(p, opt);
5886         else if (fmt & DIFF_FORMAT_NAME) {
5887                 const char *name_a, *name_b;
5888                 name_a = p->two->path;
5889                 name_b = NULL;
5890                 strip_prefix(opt->prefix_length, &name_a, &name_b);
5891                 fprintf(opt->file, "%s", diff_line_prefix(opt));
5892                 write_name_quoted(name_a, opt->file, opt->line_termination);
5893         }
5894 }
5895
5896 static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
5897 {
5898         struct strbuf sb = STRBUF_INIT;
5899         if (fs->mode)
5900                 strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
5901         else
5902                 strbuf_addf(&sb, " %s ", newdelete);
5903
5904         quote_c_style(fs->path, &sb, NULL, 0);
5905         strbuf_addch(&sb, '\n');
5906         emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5907                          sb.buf, sb.len, 0);
5908         strbuf_release(&sb);
5909 }
5910
5911 static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
5912                 int show_name)
5913 {
5914         if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
5915                 struct strbuf sb = STRBUF_INIT;
5916                 strbuf_addf(&sb, " mode change %06o => %06o",
5917                             p->one->mode, p->two->mode);
5918                 if (show_name) {
5919                         strbuf_addch(&sb, ' ');
5920                         quote_c_style(p->two->path, &sb, NULL, 0);
5921                 }
5922                 strbuf_addch(&sb, '\n');
5923                 emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5924                                  sb.buf, sb.len, 0);
5925                 strbuf_release(&sb);
5926         }
5927 }
5928
5929 static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
5930                 struct diff_filepair *p)
5931 {
5932         struct strbuf sb = STRBUF_INIT;
5933         struct strbuf names = STRBUF_INIT;
5934
5935         pprint_rename(&names, p->one->path, p->two->path);
5936         strbuf_addf(&sb, " %s %s (%d%%)\n",
5937                     renamecopy, names.buf, similarity_index(p));
5938         strbuf_release(&names);
5939         emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5940                                  sb.buf, sb.len, 0);
5941         show_mode_change(opt, p, 0);
5942         strbuf_release(&sb);
5943 }
5944
5945 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
5946 {
5947         switch(p->status) {
5948         case DIFF_STATUS_DELETED:
5949                 show_file_mode_name(opt, "delete", p->one);
5950                 break;
5951         case DIFF_STATUS_ADDED:
5952                 show_file_mode_name(opt, "create", p->two);
5953                 break;
5954         case DIFF_STATUS_COPIED:
5955                 show_rename_copy(opt, "copy", p);
5956                 break;
5957         case DIFF_STATUS_RENAMED:
5958                 show_rename_copy(opt, "rename", p);
5959                 break;
5960         default:
5961                 if (p->score) {
5962                         struct strbuf sb = STRBUF_INIT;
5963                         strbuf_addstr(&sb, " rewrite ");
5964                         quote_c_style(p->two->path, &sb, NULL, 0);
5965                         strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
5966                         emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
5967                                          sb.buf, sb.len, 0);
5968                         strbuf_release(&sb);
5969                 }
5970                 show_mode_change(opt, p, !p->score);
5971                 break;
5972         }
5973 }
5974
5975 struct patch_id_t {
5976         git_SHA_CTX *ctx;
5977         int patchlen;
5978 };
5979
5980 static int remove_space(char *line, int len)
5981 {
5982         int i;
5983         char *dst = line;
5984         unsigned char c;
5985
5986         for (i = 0; i < len; i++)
5987                 if (!isspace((c = line[i])))
5988                         *dst++ = c;
5989
5990         return dst - line;
5991 }
5992
5993 static void patch_id_consume(void *priv, char *line, unsigned long len)
5994 {
5995         struct patch_id_t *data = priv;
5996         int new_len;
5997
5998         new_len = remove_space(line, len);
5999
6000         git_SHA1_Update(data->ctx, line, new_len);
6001         data->patchlen += new_len;
6002 }
6003
6004 static void patch_id_add_string(git_SHA_CTX *ctx, const char *str)
6005 {
6006         git_SHA1_Update(ctx, str, strlen(str));
6007 }
6008
6009 static void patch_id_add_mode(git_SHA_CTX *ctx, unsigned mode)
6010 {
6011         /* large enough for 2^32 in octal */
6012         char buf[12];
6013         int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
6014         git_SHA1_Update(ctx, buf, len);
6015 }
6016
6017 /* returns 0 upon success, and writes result into sha1 */
6018 static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6019 {
6020         struct diff_queue_struct *q = &diff_queued_diff;
6021         int i;
6022         git_SHA_CTX ctx;
6023         struct patch_id_t data;
6024
6025         git_SHA1_Init(&ctx);
6026         memset(&data, 0, sizeof(struct patch_id_t));
6027         data.ctx = &ctx;
6028
6029         for (i = 0; i < q->nr; i++) {
6030                 xpparam_t xpp;
6031                 xdemitconf_t xecfg;
6032                 mmfile_t mf1, mf2;
6033                 struct diff_filepair *p = q->queue[i];
6034                 int len1, len2;
6035
6036                 memset(&xpp, 0, sizeof(xpp));
6037                 memset(&xecfg, 0, sizeof(xecfg));
6038                 if (p->status == 0)
6039                         return error("internal diff status error");
6040                 if (p->status == DIFF_STATUS_UNKNOWN)
6041                         continue;
6042                 if (diff_unmodified_pair(p))
6043                         continue;
6044                 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
6045                     (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
6046                         continue;
6047                 if (DIFF_PAIR_UNMERGED(p))
6048                         continue;
6049
6050                 diff_fill_oid_info(p->one, options->repo->index);
6051                 diff_fill_oid_info(p->two, options->repo->index);
6052
6053                 len1 = remove_space(p->one->path, strlen(p->one->path));
6054                 len2 = remove_space(p->two->path, strlen(p->two->path));
6055                 patch_id_add_string(&ctx, "diff--git");
6056                 patch_id_add_string(&ctx, "a/");
6057                 git_SHA1_Update(&ctx, p->one->path, len1);
6058                 patch_id_add_string(&ctx, "b/");
6059                 git_SHA1_Update(&ctx, p->two->path, len2);
6060
6061                 if (p->one->mode == 0) {
6062                         patch_id_add_string(&ctx, "newfilemode");
6063                         patch_id_add_mode(&ctx, p->two->mode);
6064                         patch_id_add_string(&ctx, "---/dev/null");
6065                         patch_id_add_string(&ctx, "+++b/");
6066                         git_SHA1_Update(&ctx, p->two->path, len2);
6067                 } else if (p->two->mode == 0) {
6068                         patch_id_add_string(&ctx, "deletedfilemode");
6069                         patch_id_add_mode(&ctx, p->one->mode);
6070                         patch_id_add_string(&ctx, "---a/");
6071                         git_SHA1_Update(&ctx, p->one->path, len1);
6072                         patch_id_add_string(&ctx, "+++/dev/null");
6073                 } else {
6074                         patch_id_add_string(&ctx, "---a/");
6075                         git_SHA1_Update(&ctx, p->one->path, len1);
6076                         patch_id_add_string(&ctx, "+++b/");
6077                         git_SHA1_Update(&ctx, p->two->path, len2);
6078                 }
6079
6080                 if (diff_header_only)
6081                         continue;
6082
6083                 if (fill_mmfile(options->repo, &mf1, p->one) < 0 ||
6084                     fill_mmfile(options->repo, &mf2, p->two) < 0)
6085                         return error("unable to read files to diff");
6086
6087                 if (diff_filespec_is_binary(options->repo, p->one) ||
6088                     diff_filespec_is_binary(options->repo, p->two)) {
6089                         git_SHA1_Update(&ctx, oid_to_hex(&p->one->oid),
6090                                         GIT_SHA1_HEXSZ);
6091                         git_SHA1_Update(&ctx, oid_to_hex(&p->two->oid),
6092                                         GIT_SHA1_HEXSZ);
6093                         continue;
6094                 }
6095
6096                 xpp.flags = 0;
6097                 xecfg.ctxlen = 3;
6098                 xecfg.flags = 0;
6099                 if (xdi_diff_outf(&mf1, &mf2, discard_hunk_line,
6100                                   patch_id_consume, &data, &xpp, &xecfg))
6101                         return error("unable to generate patch-id diff for %s",
6102                                      p->one->path);
6103         }
6104
6105         git_SHA1_Final(oid->hash, &ctx);
6106         return 0;
6107 }
6108
6109 int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only)
6110 {
6111         struct diff_queue_struct *q = &diff_queued_diff;
6112         int i;
6113         int result = diff_get_patch_id(options, oid, diff_header_only);
6114
6115         for (i = 0; i < q->nr; i++)
6116                 diff_free_filepair(q->queue[i]);
6117
6118         free(q->queue);
6119         DIFF_QUEUE_CLEAR(q);
6120
6121         return result;
6122 }
6123
6124 static int is_summary_empty(const struct diff_queue_struct *q)
6125 {
6126         int i;
6127
6128         for (i = 0; i < q->nr; i++) {
6129                 const struct diff_filepair *p = q->queue[i];
6130
6131                 switch (p->status) {
6132                 case DIFF_STATUS_DELETED:
6133                 case DIFF_STATUS_ADDED:
6134                 case DIFF_STATUS_COPIED:
6135                 case DIFF_STATUS_RENAMED:
6136                         return 0;
6137                 default:
6138                         if (p->score)
6139                                 return 0;
6140                         if (p->one->mode && p->two->mode &&
6141                             p->one->mode != p->two->mode)
6142                                 return 0;
6143                         break;
6144                 }
6145         }
6146         return 1;
6147 }
6148
6149 static const char rename_limit_warning[] =
6150 N_("inexact rename detection was skipped due to too many files.");
6151
6152 static const char degrade_cc_to_c_warning[] =
6153 N_("only found copies from modified paths due to too many files.");
6154
6155 static const char rename_limit_advice[] =
6156 N_("you may want to set your %s variable to at least "
6157    "%d and retry the command.");
6158
6159 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
6160 {
6161         fflush(stdout);
6162         if (degraded_cc)
6163                 warning(_(degrade_cc_to_c_warning));
6164         else if (needed)
6165                 warning(_(rename_limit_warning));
6166         else
6167                 return;
6168         if (0 < needed)
6169                 warning(_(rename_limit_advice), varname, needed);
6170 }
6171
6172 static void diff_flush_patch_all_file_pairs(struct diff_options *o)
6173 {
6174         int i;
6175         static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
6176         struct diff_queue_struct *q = &diff_queued_diff;
6177
6178         if (WSEH_NEW & WS_RULE_MASK)
6179                 BUG("WS rules bit mask overlaps with diff symbol flags");
6180
6181         if (o->color_moved)
6182                 o->emitted_symbols = &esm;
6183
6184         for (i = 0; i < q->nr; i++) {
6185                 struct diff_filepair *p = q->queue[i];
6186                 if (check_pair_status(p))
6187                         diff_flush_patch(p, o);
6188         }
6189
6190         if (o->emitted_symbols) {
6191                 if (o->color_moved) {
6192                         struct hashmap add_lines, del_lines;
6193
6194                         if (o->color_moved_ws_handling &
6195                             COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
6196                                 o->color_moved_ws_handling |= XDF_IGNORE_WHITESPACE;
6197
6198                         hashmap_init(&del_lines, moved_entry_cmp, o, 0);
6199                         hashmap_init(&add_lines, moved_entry_cmp, o, 0);
6200
6201                         add_lines_to_move_detection(o, &add_lines, &del_lines);
6202                         mark_color_as_moved(o, &add_lines, &del_lines);
6203                         if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
6204                                 dim_moved_lines(o);
6205
6206                         hashmap_free(&add_lines, 1);
6207                         hashmap_free(&del_lines, 1);
6208                 }
6209
6210                 for (i = 0; i < esm.nr; i++)
6211                         emit_diff_symbol_from_struct(o, &esm.buf[i]);
6212
6213                 for (i = 0; i < esm.nr; i++)
6214                         free((void *)esm.buf[i].line);
6215                 esm.nr = 0;
6216
6217                 o->emitted_symbols = NULL;
6218         }
6219 }
6220
6221 void diff_flush(struct diff_options *options)
6222 {
6223         struct diff_queue_struct *q = &diff_queued_diff;
6224         int i, output_format = options->output_format;
6225         int separator = 0;
6226         int dirstat_by_line = 0;
6227
6228         /*
6229          * Order: raw, stat, summary, patch
6230          * or:    name/name-status/checkdiff (other bits clear)
6231          */
6232         if (!q->nr)
6233                 goto free_queue;
6234
6235         if (output_format & (DIFF_FORMAT_RAW |
6236                              DIFF_FORMAT_NAME |
6237                              DIFF_FORMAT_NAME_STATUS |
6238                              DIFF_FORMAT_CHECKDIFF)) {
6239                 for (i = 0; i < q->nr; i++) {
6240                         struct diff_filepair *p = q->queue[i];
6241                         if (check_pair_status(p))
6242                                 flush_one_pair(p, options);
6243                 }
6244                 separator++;
6245         }
6246
6247         if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
6248                 dirstat_by_line = 1;
6249
6250         if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
6251             dirstat_by_line) {
6252                 struct diffstat_t diffstat;
6253
6254                 memset(&diffstat, 0, sizeof(struct diffstat_t));
6255                 for (i = 0; i < q->nr; i++) {
6256                         struct diff_filepair *p = q->queue[i];
6257                         if (check_pair_status(p))
6258                                 diff_flush_stat(p, options, &diffstat);
6259                 }
6260                 if (output_format & DIFF_FORMAT_NUMSTAT)
6261                         show_numstat(&diffstat, options);
6262                 if (output_format & DIFF_FORMAT_DIFFSTAT)
6263                         show_stats(&diffstat, options);
6264                 if (output_format & DIFF_FORMAT_SHORTSTAT)
6265                         show_shortstats(&diffstat, options);
6266                 if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
6267                         show_dirstat_by_line(&diffstat, options);
6268                 free_diffstat_info(&diffstat);
6269                 separator++;
6270         }
6271         if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
6272                 show_dirstat(options);
6273
6274         if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
6275                 for (i = 0; i < q->nr; i++) {
6276                         diff_summary(options, q->queue[i]);
6277                 }
6278                 separator++;
6279         }
6280
6281         if (output_format & DIFF_FORMAT_NO_OUTPUT &&
6282             options->flags.exit_with_status &&
6283             options->flags.diff_from_contents) {
6284                 /*
6285                  * run diff_flush_patch for the exit status. setting
6286                  * options->file to /dev/null should be safe, because we
6287                  * aren't supposed to produce any output anyway.
6288                  */
6289                 if (options->close_file)
6290                         fclose(options->file);
6291                 options->file = xfopen("/dev/null", "w");
6292                 options->close_file = 1;
6293                 options->color_moved = 0;
6294                 for (i = 0; i < q->nr; i++) {
6295                         struct diff_filepair *p = q->queue[i];
6296                         if (check_pair_status(p))
6297                                 diff_flush_patch(p, options);
6298                         if (options->found_changes)
6299                                 break;
6300                 }
6301         }
6302
6303         if (output_format & DIFF_FORMAT_PATCH) {
6304                 if (separator) {
6305                         emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
6306                         if (options->stat_sep)
6307                                 /* attach patch instead of inline */
6308                                 emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
6309                                                  NULL, 0, 0);
6310                 }
6311
6312                 diff_flush_patch_all_file_pairs(options);
6313         }
6314
6315         if (output_format & DIFF_FORMAT_CALLBACK)
6316                 options->format_callback(q, options, options->format_callback_data);
6317
6318         for (i = 0; i < q->nr; i++)
6319                 diff_free_filepair(q->queue[i]);
6320 free_queue:
6321         free(q->queue);
6322         DIFF_QUEUE_CLEAR(q);
6323         if (options->close_file)
6324                 fclose(options->file);
6325
6326         /*
6327          * Report the content-level differences with HAS_CHANGES;
6328          * diff_addremove/diff_change does not set the bit when
6329          * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
6330          */
6331         if (options->flags.diff_from_contents) {
6332                 if (options->found_changes)
6333                         options->flags.has_changes = 1;
6334                 else
6335                         options->flags.has_changes = 0;
6336         }
6337 }
6338
6339 static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
6340 {
6341         return (((p->status == DIFF_STATUS_MODIFIED) &&
6342                  ((p->score &&
6343                    filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
6344                   (!p->score &&
6345                    filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
6346                 ((p->status != DIFF_STATUS_MODIFIED) &&
6347                  filter_bit_tst(p->status, options)));
6348 }
6349
6350 static void diffcore_apply_filter(struct diff_options *options)
6351 {
6352         int i;
6353         struct diff_queue_struct *q = &diff_queued_diff;
6354         struct diff_queue_struct outq;
6355
6356         DIFF_QUEUE_CLEAR(&outq);
6357
6358         if (!options->filter)
6359                 return;
6360
6361         if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
6362                 int found;
6363                 for (i = found = 0; !found && i < q->nr; i++) {
6364                         if (match_filter(options, q->queue[i]))
6365                                 found++;
6366                 }
6367                 if (found)
6368                         return;
6369
6370                 /* otherwise we will clear the whole queue
6371                  * by copying the empty outq at the end of this
6372                  * function, but first clear the current entries
6373                  * in the queue.
6374                  */
6375                 for (i = 0; i < q->nr; i++)
6376                         diff_free_filepair(q->queue[i]);
6377         }
6378         else {
6379                 /* Only the matching ones */
6380                 for (i = 0; i < q->nr; i++) {
6381                         struct diff_filepair *p = q->queue[i];
6382                         if (match_filter(options, p))
6383                                 diff_q(&outq, p);
6384                         else
6385                                 diff_free_filepair(p);
6386                 }
6387         }
6388         free(q->queue);
6389         *q = outq;
6390 }
6391
6392 /* Check whether two filespecs with the same mode and size are identical */
6393 static int diff_filespec_is_identical(struct repository *r,
6394                                       struct diff_filespec *one,
6395                                       struct diff_filespec *two)
6396 {
6397         if (S_ISGITLINK(one->mode))
6398                 return 0;
6399         if (diff_populate_filespec(r, one, 0))
6400                 return 0;
6401         if (diff_populate_filespec(r, two, 0))
6402                 return 0;
6403         return !memcmp(one->data, two->data, one->size);
6404 }
6405
6406 static int diff_filespec_check_stat_unmatch(struct repository *r,
6407                                             struct diff_filepair *p)
6408 {
6409         if (p->done_skip_stat_unmatch)
6410                 return p->skip_stat_unmatch_result;
6411
6412         p->done_skip_stat_unmatch = 1;
6413         p->skip_stat_unmatch_result = 0;
6414         /*
6415          * 1. Entries that come from stat info dirtiness
6416          *    always have both sides (iow, not create/delete),
6417          *    one side of the object name is unknown, with
6418          *    the same mode and size.  Keep the ones that
6419          *    do not match these criteria.  They have real
6420          *    differences.
6421          *
6422          * 2. At this point, the file is known to be modified,
6423          *    with the same mode and size, and the object
6424          *    name of one side is unknown.  Need to inspect
6425          *    the identical contents.
6426          */
6427         if (!DIFF_FILE_VALID(p->one) || /* (1) */
6428             !DIFF_FILE_VALID(p->two) ||
6429             (p->one->oid_valid && p->two->oid_valid) ||
6430             (p->one->mode != p->two->mode) ||
6431             diff_populate_filespec(r, p->one, CHECK_SIZE_ONLY) ||
6432             diff_populate_filespec(r, p->two, CHECK_SIZE_ONLY) ||
6433             (p->one->size != p->two->size) ||
6434             !diff_filespec_is_identical(r, p->one, p->two)) /* (2) */
6435                 p->skip_stat_unmatch_result = 1;
6436         return p->skip_stat_unmatch_result;
6437 }
6438
6439 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
6440 {
6441         int i;
6442         struct diff_queue_struct *q = &diff_queued_diff;
6443         struct diff_queue_struct outq;
6444         DIFF_QUEUE_CLEAR(&outq);
6445
6446         for (i = 0; i < q->nr; i++) {
6447                 struct diff_filepair *p = q->queue[i];
6448
6449                 if (diff_filespec_check_stat_unmatch(diffopt->repo, p))
6450                         diff_q(&outq, p);
6451                 else {
6452                         /*
6453                          * The caller can subtract 1 from skip_stat_unmatch
6454                          * to determine how many paths were dirty only
6455                          * due to stat info mismatch.
6456                          */
6457                         if (!diffopt->flags.no_index)
6458                                 diffopt->skip_stat_unmatch++;
6459                         diff_free_filepair(p);
6460                 }
6461         }
6462         free(q->queue);
6463         *q = outq;
6464 }
6465
6466 static int diffnamecmp(const void *a_, const void *b_)
6467 {
6468         const struct diff_filepair *a = *((const struct diff_filepair **)a_);
6469         const struct diff_filepair *b = *((const struct diff_filepair **)b_);
6470         const char *name_a, *name_b;
6471
6472         name_a = a->one ? a->one->path : a->two->path;
6473         name_b = b->one ? b->one->path : b->two->path;
6474         return strcmp(name_a, name_b);
6475 }
6476
6477 void diffcore_fix_diff_index(void)
6478 {
6479         struct diff_queue_struct *q = &diff_queued_diff;
6480         QSORT(q->queue, q->nr, diffnamecmp);
6481 }
6482
6483 void diffcore_std(struct diff_options *options)
6484 {
6485         /* NOTE please keep the following in sync with diff_tree_combined() */
6486         if (options->skip_stat_unmatch)
6487                 diffcore_skip_stat_unmatch(options);
6488         if (!options->found_follow) {
6489                 /* See try_to_follow_renames() in tree-diff.c */
6490                 if (options->break_opt != -1)
6491                         diffcore_break(options->repo,
6492                                        options->break_opt);
6493                 if (options->detect_rename)
6494                         diffcore_rename(options);
6495                 if (options->break_opt != -1)
6496                         diffcore_merge_broken();
6497         }
6498         if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
6499                 diffcore_pickaxe(options);
6500         if (options->orderfile)
6501                 diffcore_order(options->orderfile);
6502         if (!options->found_follow)
6503                 /* See try_to_follow_renames() in tree-diff.c */
6504                 diff_resolve_rename_copy();
6505         diffcore_apply_filter(options);
6506
6507         if (diff_queued_diff.nr && !options->flags.diff_from_contents)
6508                 options->flags.has_changes = 1;
6509         else
6510                 options->flags.has_changes = 0;
6511
6512         options->found_follow = 0;
6513 }
6514
6515 int diff_result_code(struct diff_options *opt, int status)
6516 {
6517         int result = 0;
6518
6519         diff_warn_rename_limit("diff.renameLimit",
6520                                opt->needed_rename_limit,
6521                                opt->degraded_cc_to_c);
6522         if (!opt->flags.exit_with_status &&
6523             !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
6524                 return status;
6525         if (opt->flags.exit_with_status &&
6526             opt->flags.has_changes)
6527                 result |= 01;
6528         if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
6529             opt->flags.check_failed)
6530                 result |= 02;
6531         return result;
6532 }
6533
6534 int diff_can_quit_early(struct diff_options *opt)
6535 {
6536         return (opt->flags.quick &&
6537                 !opt->filter &&
6538                 opt->flags.has_changes);
6539 }
6540
6541 /*
6542  * Shall changes to this submodule be ignored?
6543  *
6544  * Submodule changes can be configured to be ignored separately for each path,
6545  * but that configuration can be overridden from the command line.
6546  */
6547 static int is_submodule_ignored(const char *path, struct diff_options *options)
6548 {
6549         int ignored = 0;
6550         struct diff_flags orig_flags = options->flags;
6551         if (!options->flags.override_submodule_config)
6552                 set_diffopt_flags_from_submodule_config(options, path);
6553         if (options->flags.ignore_submodules)
6554                 ignored = 1;
6555         options->flags = orig_flags;
6556         return ignored;
6557 }
6558
6559 void diff_addremove(struct diff_options *options,
6560                     int addremove, unsigned mode,
6561                     const struct object_id *oid,
6562                     int oid_valid,
6563                     const char *concatpath, unsigned dirty_submodule)
6564 {
6565         struct diff_filespec *one, *two;
6566
6567         if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
6568                 return;
6569
6570         /* This may look odd, but it is a preparation for
6571          * feeding "there are unchanged files which should
6572          * not produce diffs, but when you are doing copy
6573          * detection you would need them, so here they are"
6574          * entries to the diff-core.  They will be prefixed
6575          * with something like '=' or '*' (I haven't decided
6576          * which but should not make any difference).
6577          * Feeding the same new and old to diff_change()
6578          * also has the same effect.
6579          * Before the final output happens, they are pruned after
6580          * merged into rename/copy pairs as appropriate.
6581          */
6582         if (options->flags.reverse_diff)
6583                 addremove = (addremove == '+' ? '-' :
6584                              addremove == '-' ? '+' : addremove);
6585
6586         if (options->prefix &&
6587             strncmp(concatpath, options->prefix, options->prefix_length))
6588                 return;
6589
6590         one = alloc_filespec(concatpath);
6591         two = alloc_filespec(concatpath);
6592
6593         if (addremove != '+')
6594                 fill_filespec(one, oid, oid_valid, mode);
6595         if (addremove != '-') {
6596                 fill_filespec(two, oid, oid_valid, mode);
6597                 two->dirty_submodule = dirty_submodule;
6598         }
6599
6600         diff_queue(&diff_queued_diff, one, two);
6601         if (!options->flags.diff_from_contents)
6602                 options->flags.has_changes = 1;
6603 }
6604
6605 void diff_change(struct diff_options *options,
6606                  unsigned old_mode, unsigned new_mode,
6607                  const struct object_id *old_oid,
6608                  const struct object_id *new_oid,
6609                  int old_oid_valid, int new_oid_valid,
6610                  const char *concatpath,
6611                  unsigned old_dirty_submodule, unsigned new_dirty_submodule)
6612 {
6613         struct diff_filespec *one, *two;
6614         struct diff_filepair *p;
6615
6616         if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
6617             is_submodule_ignored(concatpath, options))
6618                 return;
6619
6620         if (options->flags.reverse_diff) {
6621                 SWAP(old_mode, new_mode);
6622                 SWAP(old_oid, new_oid);
6623                 SWAP(old_oid_valid, new_oid_valid);
6624                 SWAP(old_dirty_submodule, new_dirty_submodule);
6625         }
6626
6627         if (options->prefix &&
6628             strncmp(concatpath, options->prefix, options->prefix_length))
6629                 return;
6630
6631         one = alloc_filespec(concatpath);
6632         two = alloc_filespec(concatpath);
6633         fill_filespec(one, old_oid, old_oid_valid, old_mode);
6634         fill_filespec(two, new_oid, new_oid_valid, new_mode);
6635         one->dirty_submodule = old_dirty_submodule;
6636         two->dirty_submodule = new_dirty_submodule;
6637         p = diff_queue(&diff_queued_diff, one, two);
6638
6639         if (options->flags.diff_from_contents)
6640                 return;
6641
6642         if (options->flags.quick && options->skip_stat_unmatch &&
6643             !diff_filespec_check_stat_unmatch(options->repo, p))
6644                 return;
6645
6646         options->flags.has_changes = 1;
6647 }
6648
6649 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
6650 {
6651         struct diff_filepair *pair;
6652         struct diff_filespec *one, *two;
6653
6654         if (options->prefix &&
6655             strncmp(path, options->prefix, options->prefix_length))
6656                 return NULL;
6657
6658         one = alloc_filespec(path);
6659         two = alloc_filespec(path);
6660         pair = diff_queue(&diff_queued_diff, one, two);
6661         pair->is_unmerged = 1;
6662         return pair;
6663 }
6664
6665 static char *run_textconv(struct repository *r,
6666                           const char *pgm,
6667                           struct diff_filespec *spec,
6668                           size_t *outsize)
6669 {
6670         struct diff_tempfile *temp;
6671         const char *argv[3];
6672         const char **arg = argv;
6673         struct child_process child = CHILD_PROCESS_INIT;
6674         struct strbuf buf = STRBUF_INIT;
6675         int err = 0;
6676
6677         temp = prepare_temp_file(r, spec->path, spec);
6678         *arg++ = pgm;
6679         *arg++ = temp->name;
6680         *arg = NULL;
6681
6682         child.use_shell = 1;
6683         child.argv = argv;
6684         child.out = -1;
6685         if (start_command(&child)) {
6686                 remove_tempfile();
6687                 return NULL;
6688         }
6689
6690         if (strbuf_read(&buf, child.out, 0) < 0)
6691                 err = error("error reading from textconv command '%s'", pgm);
6692         close(child.out);
6693
6694         if (finish_command(&child) || err) {
6695                 strbuf_release(&buf);
6696                 remove_tempfile();
6697                 return NULL;
6698         }
6699         remove_tempfile();
6700
6701         return strbuf_detach(&buf, outsize);
6702 }
6703
6704 size_t fill_textconv(struct repository *r,
6705                      struct userdiff_driver *driver,
6706                      struct diff_filespec *df,
6707                      char **outbuf)
6708 {
6709         size_t size;
6710
6711         if (!driver) {
6712                 if (!DIFF_FILE_VALID(df)) {
6713                         *outbuf = "";
6714                         return 0;
6715                 }
6716                 if (diff_populate_filespec(r, df, 0))
6717                         die("unable to read files to diff");
6718                 *outbuf = df->data;
6719                 return df->size;
6720         }
6721
6722         if (!driver->textconv)
6723                 BUG("fill_textconv called with non-textconv driver");
6724
6725         if (driver->textconv_cache && df->oid_valid) {
6726                 *outbuf = notes_cache_get(driver->textconv_cache,
6727                                           &df->oid,
6728                                           &size);
6729                 if (*outbuf)
6730                         return size;
6731         }
6732
6733         *outbuf = run_textconv(r, driver->textconv, df, &size);
6734         if (!*outbuf)
6735                 die("unable to read files to diff");
6736
6737         if (driver->textconv_cache && df->oid_valid) {
6738                 /* ignore errors, as we might be in a readonly repository */
6739                 notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
6740                                 size);
6741                 /*
6742                  * we could save up changes and flush them all at the end,
6743                  * but we would need an extra call after all diffing is done.
6744                  * Since generating a cache entry is the slow path anyway,
6745                  * this extra overhead probably isn't a big deal.
6746                  */
6747                 notes_cache_write(driver->textconv_cache);
6748         }
6749
6750         return size;
6751 }
6752
6753 int textconv_object(struct repository *r,
6754                     const char *path,
6755                     unsigned mode,
6756                     const struct object_id *oid,
6757                     int oid_valid,
6758                     char **buf,
6759                     unsigned long *buf_size)
6760 {
6761         struct diff_filespec *df;
6762         struct userdiff_driver *textconv;
6763
6764         df = alloc_filespec(path);
6765         fill_filespec(df, oid, oid_valid, mode);
6766         textconv = get_textconv(r, df);
6767         if (!textconv) {
6768                 free_filespec(df);
6769                 return 0;
6770         }
6771
6772         *buf_size = fill_textconv(r, textconv, df, buf);
6773         free_filespec(df);
6774         return 1;
6775 }
6776
6777 void setup_diff_pager(struct diff_options *opt)
6778 {
6779         /*
6780          * If the user asked for our exit code, then either they want --quiet
6781          * or --exit-code. We should definitely not bother with a pager in the
6782          * former case, as we will generate no output. Since we still properly
6783          * report our exit code even when a pager is run, we _could_ run a
6784          * pager with --exit-code. But since we have not done so historically,
6785          * and because it is easy to find people oneline advising "git diff
6786          * --exit-code" in hooks and other scripts, we do not do so.
6787          */
6788         if (!opt->flags.exit_with_status &&
6789             check_pager_config("diff") != 0)
6790                 setup_pager();
6791 }