documentation: help: add "man.<tool>.path" config variable
[gitweb.git] / diff.c
diff --git a/diff.c b/diff.c
index f780e3e8e67f4b1e07ef1d70ab3b9f101ff6b868..3632b552b2eae5bda3cdec3323f3a68907c6f09a 100644 (file)
--- a/diff.c
+++ b/diff.c
@@ -10,6 +10,7 @@
 #include "color.h"
 #include "attr.h"
 #include "run-command.h"
+#include "utf8.h"
 
 #ifdef NO_FAST_WORKING_DIRECTORY
 #define FAST_WORKING_DIRECTORY 0
@@ -19,7 +20,8 @@
 
 static int diff_detect_rename_default;
 static int diff_rename_limit_default = 100;
-static int diff_use_color_default;
+int diff_use_color_default = -1;
+static const char *external_diff_cmd_cfg;
 int diff_auto_refresh_index = 1;
 
 static char diff_colors[][COLOR_MAXLEN] = {
@@ -55,17 +57,9 @@ static int parse_diff_color_slot(const char *var, int ofs)
 static struct ll_diff_driver {
        const char *name;
        struct ll_diff_driver *next;
-       char *cmd;
+       const char *cmd;
 } *user_diff, **user_diff_tail;
 
-static void read_config_if_needed(void)
-{
-       if (!user_diff_tail) {
-               user_diff_tail = &user_diff;
-               git_config(git_diff_ui_config);
-       }
-}
-
 /*
  * Currently there is only "diff.<drivername>.command" variable;
  * because there are "diff.color.<slot>" variables, we are parsing
@@ -92,10 +86,7 @@ static int parse_lldiff_command(const char *var, const char *ep, const char *val
                user_diff_tail = &(drv->next);
        }
 
-       if (!value)
-               return error("%s: lacks value", var);
-       drv->cmd = strdup(value);
-       return 0;
+       return git_config_string(&(drv->cmd), var, value);
 }
 
 /*
@@ -127,8 +118,7 @@ static int parse_funcname_pattern(const char *var, const char *ep, const char *v
                pp->next = funcname_pattern_list;
                funcname_pattern_list = pp;
        }
-       if (pp->pattern)
-               free(pp->pattern);
+       free(pp->pattern);
        pp->pattern = xstrdup(value);
        return 0;
 }
@@ -163,23 +153,44 @@ int git_diff_ui_config(const char *var, const char *value)
                diff_auto_refresh_index = git_config_bool(var, value);
                return 0;
        }
+       if (!strcmp(var, "diff.external")) {
+               if (!value)
+                       return config_error_nonbool(var);
+               external_diff_cmd_cfg = xstrdup(value);
+               return 0;
+       }
        if (!prefixcmp(var, "diff.")) {
                const char *ep = strrchr(var, '.');
 
-               if (ep != var + 4) {
-                       if (!strcmp(ep, ".command"))
-                               return parse_lldiff_command(var, ep, value);
-                       if (!strcmp(ep, ".funcname"))
-                               return parse_funcname_pattern(var, ep, value);
-               }
+               if (ep != var + 4 && !strcmp(ep, ".command"))
+                       return parse_lldiff_command(var, ep, value);
        }
+
+       return git_diff_basic_config(var, value);
+}
+
+int git_diff_basic_config(const char *var, const char *value)
+{
        if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
                int slot = parse_diff_color_slot(var, 11);
+               if (!value)
+                       return config_error_nonbool(var);
                color_parse(value, var, diff_colors[slot]);
                return 0;
        }
 
-       return git_default_config(var, value);
+       if (!prefixcmp(var, "diff.")) {
+               const char *ep = strrchr(var, '.');
+               if (ep != var + 4) {
+                       if (!strcmp(ep, ".funcname")) {
+                               if (!value)
+                                       return config_error_nonbool(var);
+                               return parse_funcname_pattern(var, ep, value);
+                       }
+               }
+       }
+
+       return git_color_default_config(var, value);
 }
 
 static char *quote_two(const char *one, const char *two)
@@ -209,6 +220,8 @@ static const char *external_diff(void)
        if (done_preparing)
                return external_diff_cmd;
        external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
+       if (!external_diff_cmd)
+               external_diff_cmd = external_diff_cmd_cfg;
        done_preparing = 1;
        return external_diff_cmd;
 }
@@ -243,76 +256,85 @@ static int count_lines(const char *data, int size)
        return count;
 }
 
-static void print_line_count(int count)
+static void print_line_count(FILE *file, int count)
 {
        switch (count) {
        case 0:
-               printf("0,0");
+               fprintf(file, "0,0");
                break;
        case 1:
-               printf("1");
+               fprintf(file, "1");
                break;
        default:
-               printf("1,%d", count);
+               fprintf(file, "1,%d", count);
                break;
        }
 }
 
-static void copy_file(int prefix, const char *data, int size,
-               const char *set, const char *reset)
+static void copy_file_with_prefix(FILE *file,
+                                 int prefix, const char *data, int size,
+                                 const char *set, const char *reset)
 {
        int ch, nl_just_seen = 1;
        while (0 < size--) {
                ch = *data++;
                if (nl_just_seen) {
-                       fputs(set, stdout);
-                       putchar(prefix);
+                       fputs(set, file);
+                       putc(prefix, file);
                }
                if (ch == '\n') {
                        nl_just_seen = 1;
-                       fputs(reset, stdout);
+                       fputs(reset, file);
                } else
                        nl_just_seen = 0;
-               putchar(ch);
+               putc(ch, file);
        }
        if (!nl_just_seen)
-               printf("%s\n\\ No newline at end of file\n", reset);
+               fprintf(file, "%s\n\\ No newline at end of file\n", reset);
 }
 
 static void emit_rewrite_diff(const char *name_a,
                              const char *name_b,
                              struct diff_filespec *one,
                              struct diff_filespec *two,
-                             int color_diff)
+                             struct diff_options *o)
 {
        int lc_a, lc_b;
+       int color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
        const char *name_a_tab, *name_b_tab;
        const char *metainfo = diff_get_color(color_diff, DIFF_METAINFO);
        const char *fraginfo = diff_get_color(color_diff, DIFF_FRAGINFO);
        const char *old = diff_get_color(color_diff, DIFF_FILE_OLD);
        const char *new = diff_get_color(color_diff, DIFF_FILE_NEW);
        const char *reset = diff_get_color(color_diff, DIFF_RESET);
+       static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
 
        name_a += (*name_a == '/');
        name_b += (*name_b == '/');
        name_a_tab = strchr(name_a, ' ') ? "\t" : "";
        name_b_tab = strchr(name_b, ' ') ? "\t" : "";
 
+       strbuf_reset(&a_name);
+       strbuf_reset(&b_name);
+       quote_two_c_style(&a_name, o->a_prefix, name_a, 0);
+       quote_two_c_style(&b_name, o->b_prefix, name_b, 0);
+
        diff_populate_filespec(one, 0);
        diff_populate_filespec(two, 0);
        lc_a = count_lines(one->data, one->size);
        lc_b = count_lines(two->data, two->size);
-       printf("%s--- a/%s%s%s\n%s+++ b/%s%s%s\n%s@@ -",
-              metainfo, name_a, name_a_tab, reset,
-              metainfo, name_b, name_b_tab, reset, fraginfo);
-       print_line_count(lc_a);
-       printf(" +");
-       print_line_count(lc_b);
-       printf(" @@%s\n", reset);
+       fprintf(o->file,
+               "%s--- %s%s%s\n%s+++ %s%s%s\n%s@@ -",
+               metainfo, a_name.buf, name_a_tab, reset,
+               metainfo, b_name.buf, name_b_tab, reset, fraginfo);
+       print_line_count(o->file, lc_a);
+       fprintf(o->file, " +");
+       print_line_count(o->file, lc_b);
+       fprintf(o->file, " @@%s\n", reset);
        if (lc_a)
-               copy_file('-', one->data, one->size, old, reset);
+               copy_file_with_prefix(o->file, '-', one->data, one->size, old, reset);
        if (lc_b)
-               copy_file('+', two->data, two->size, new, reset);
+               copy_file_with_prefix(o->file, '+', two->data, two->size, new, reset);
 }
 
 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
@@ -352,9 +374,10 @@ static void diff_words_append(char *line, unsigned long len,
 struct diff_words_data {
        struct xdiff_emit_state xm;
        struct diff_words_buffer minus, plus;
+       FILE *file;
 };
 
-static void print_word(struct diff_words_buffer *buffer, int len, int color,
+static void print_word(FILE *file, struct diff_words_buffer *buffer, int len, int color,
                int suppress_newline)
 {
        const char *ptr;
@@ -371,15 +394,15 @@ static void print_word(struct diff_words_buffer *buffer, int len, int color,
                len--;
        }
 
-       fputs(diff_get_color(1, color), stdout);
-       fwrite(ptr, len, 1, stdout);
-       fputs(diff_get_color(1, DIFF_RESET), stdout);
+       fputs(diff_get_color(1, color), file);
+       fwrite(ptr, len, 1, file);
+       fputs(diff_get_color(1, DIFF_RESET), file);
 
        if (eol) {
                if (suppress_newline)
                        buffer->suppressed_newline = 1;
                else
-                       putchar('\n');
+                       putc('\n', file);
        }
 }
 
@@ -389,20 +412,23 @@ static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
 
        if (diff_words->minus.suppressed_newline) {
                if (line[0] != '+')
-                       putchar('\n');
+                       putc('\n', diff_words->file);
                diff_words->minus.suppressed_newline = 0;
        }
 
        len--;
        switch (line[0]) {
                case '-':
-                       print_word(&diff_words->minus, len, DIFF_FILE_OLD, 1);
+                       print_word(diff_words->file,
+                                  &diff_words->minus, len, DIFF_FILE_OLD, 1);
                        break;
                case '+':
-                       print_word(&diff_words->plus, len, DIFF_FILE_NEW, 0);
+                       print_word(diff_words->file,
+                                  &diff_words->plus, len, DIFF_FILE_NEW, 0);
                        break;
                case ' ':
-                       print_word(&diff_words->plus, len, DIFF_PLAIN, 0);
+                       print_word(diff_words->file,
+                                  &diff_words->plus, len, DIFF_PLAIN, 0);
                        diff_words->minus.current += len;
                        break;
        }
@@ -439,25 +465,29 @@ static void diff_words_show(struct diff_words_data *diff_words)
        ecb.outf = xdiff_outf;
        ecb.priv = diff_words;
        diff_words->xm.consume = fn_out_diff_words_aux;
-       xdl_diff(&minus, &plus, &xpp, &xecfg, &ecb);
+       xdi_diff(&minus, &plus, &xpp, &xecfg, &ecb);
 
        free(minus.ptr);
        free(plus.ptr);
        diff_words->minus.text.size = diff_words->plus.text.size = 0;
 
        if (diff_words->minus.suppressed_newline) {
-               putchar('\n');
+               putc('\n', diff_words->file);
                diff_words->minus.suppressed_newline = 0;
        }
 }
 
+typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
+
 struct emit_callback {
        struct xdiff_emit_state xm;
        int nparents, color_diff;
        unsigned ws_rule;
+       sane_truncate_fn truncate;
        const char **label_path;
        struct diff_words_data *diff_words;
        int *found_changesp;
+       FILE *file;
 };
 
 static void free_diff_words_data(struct emit_callback *ecbdata)
@@ -468,10 +498,8 @@ static void free_diff_words_data(struct emit_callback *ecbdata)
                                ecbdata->diff_words->plus.text.size)
                        diff_words_show(ecbdata->diff_words);
 
-               if (ecbdata->diff_words->minus.text.ptr)
-                       free (ecbdata->diff_words->minus.text.ptr);
-               if (ecbdata->diff_words->plus.text.ptr)
-                       free (ecbdata->diff_words->plus.text.ptr);
+               free (ecbdata->diff_words->minus.text.ptr);
+               free (ecbdata->diff_words->plus.text.ptr);
                free(ecbdata->diff_words);
                ecbdata->diff_words = NULL;
        }
@@ -484,90 +512,11 @@ const char *diff_get_color(int diff_use_color, enum color_diff ix)
        return "";
 }
 
-static void emit_line(const char *set, const char *reset, const char *line, int len)
+static void emit_line(FILE *file, const char *set, const char *reset, const char *line, int len)
 {
-       if (len > 0 && line[len-1] == '\n')
-               len--;
-       fputs(set, stdout);
-       fwrite(line, len, 1, stdout);
-       puts(reset);
-}
-
-static void emit_line_with_ws(int nparents,
-                             const char *set, const char *reset, const char *ws,
-                             const char *line, int len, unsigned ws_rule)
-{
-       int col0 = nparents;
-       int last_tab_in_indent = -1;
-       int last_space_in_indent = -1;
-       int i;
-       int tail = len;
-       int need_highlight_leading_space = 0;
-       /*
-        * The line is a newly added line.  Does it have funny leading
-        * whitespaces?  In indent, SP should never precede a TAB.  In
-        * addition, under "indent with non tab" rule, there should not
-        * be more than 8 consecutive spaces.
-        */
-       for (i = col0; i < len; i++) {
-               if (line[i] == '\t') {
-                       last_tab_in_indent = i;
-                       if ((ws_rule & WS_SPACE_BEFORE_TAB) &&
-                           0 <= last_space_in_indent)
-                               need_highlight_leading_space = 1;
-               }
-               else if (line[i] == ' ')
-                       last_space_in_indent = i;
-               else
-                       break;
-       }
-       if ((ws_rule & WS_INDENT_WITH_NON_TAB) &&
-           0 <= last_space_in_indent &&
-           last_tab_in_indent < 0 &&
-           8 <= (i - col0)) {
-               last_tab_in_indent = i;
-               need_highlight_leading_space = 1;
-       }
-       fputs(set, stdout);
-       fwrite(line, col0, 1, stdout);
-       fputs(reset, stdout);
-       if (((i == len) || line[i] == '\n') && i != col0) {
-               /* The whole line was indent */
-               emit_line(ws, reset, line + col0, len - col0);
-               return;
-       }
-       i = col0;
-       if (need_highlight_leading_space) {
-               while (i < last_tab_in_indent) {
-                       if (line[i] == ' ') {
-                               fputs(ws, stdout);
-                               putchar(' ');
-                               fputs(reset, stdout);
-                       }
-                       else
-                               putchar(line[i]);
-                       i++;
-               }
-       }
-       tail = len - 1;
-       if (line[tail] == '\n' && i < tail)
-               tail--;
-       if (ws_rule & WS_TRAILING_SPACE) {
-               while (i < tail) {
-                       if (!isspace(line[tail]))
-                               break;
-                       tail--;
-               }
-       }
-       if ((i < tail && line[tail + 1] != '\n')) {
-               /* This has whitespace between tail+1..len */
-               fputs(set, stdout);
-               fwrite(line + i, tail - i + 1, 1, stdout);
-               fputs(reset, stdout);
-               emit_line(ws, reset, line + tail + 1, len - tail - 1);
-       }
-       else
-               emit_line(set, reset, line + i, len - i);
+       fputs(set, file);
+       fwrite(line, len, 1, file);
+       fputs(reset, file);
 }
 
 static void emit_add_line(const char *reset, struct emit_callback *ecbdata, const char *line, int len)
@@ -576,10 +525,32 @@ static void emit_add_line(const char *reset, struct emit_callback *ecbdata, cons
        const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
 
        if (!*ws)
-               emit_line(set, reset, line, len);
-       else
-               emit_line_with_ws(ecbdata->nparents, set, reset, ws,
-                                 line, len, ecbdata->ws_rule);
+               emit_line(ecbdata->file, set, reset, line, len);
+       else {
+               /* Emit just the prefix, then the rest. */
+               emit_line(ecbdata->file, set, reset, line, ecbdata->nparents);
+               (void)check_and_emit_line(line + ecbdata->nparents,
+                   len - ecbdata->nparents, ecbdata->ws_rule,
+                   ecbdata->file, set, reset, ws);
+       }
+}
+
+static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
+{
+       const char *cp;
+       unsigned long allot;
+       size_t l = len;
+
+       if (ecb->truncate)
+               return ecb->truncate(line, len);
+       cp = line;
+       allot = l;
+       while (0 < l) {
+               (void) utf8_width(&cp, &l);
+               if (!cp)
+                       break; /* truncated in the middle? */
+       }
+       return allot - l;
 }
 
 static void fn_out_consume(void *priv, char *line, unsigned long len)
@@ -587,7 +558,8 @@ static void fn_out_consume(void *priv, char *line, unsigned long len)
        int i;
        int color;
        struct emit_callback *ecbdata = priv;
-       const char *set = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
+       const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
+       const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
        const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
 
        *(ecbdata->found_changesp) = 1;
@@ -598,10 +570,10 @@ static void fn_out_consume(void *priv, char *line, unsigned long len)
                name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
                name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
 
-               printf("%s--- %s%s%s\n",
-                      set, ecbdata->label_path[0], reset, name_a_tab);
-               printf("%s+++ %s%s%s\n",
-                      set, ecbdata->label_path[1], reset, name_b_tab);
+               fprintf(ecbdata->file, "%s--- %s%s%s\n",
+                       meta, ecbdata->label_path[0], reset, name_a_tab);
+               fprintf(ecbdata->file, "%s+++ %s%s%s\n",
+                       meta, ecbdata->label_path[1], reset, name_b_tab);
                ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
        }
 
@@ -612,14 +584,17 @@ static void fn_out_consume(void *priv, char *line, unsigned long len)
                ;
        if (2 <= i && i < len && line[i] == ' ') {
                ecbdata->nparents = i - 1;
-               emit_line(diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO),
+               len = sane_truncate_line(ecbdata, line, len);
+               emit_line(ecbdata->file,
+                         diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO),
                          reset, line, len);
+               if (line[len-1] != '\n')
+                       putc('\n', ecbdata->file);
                return;
        }
 
        if (len < ecbdata->nparents) {
-               set = reset;
-               emit_line(reset, reset, line, len);
+               emit_line(ecbdata->file, reset, reset, line, len);
                return;
        }
 
@@ -642,7 +617,7 @@ static void fn_out_consume(void *priv, char *line, unsigned long len)
                        diff_words_show(ecbdata->diff_words);
                line++;
                len--;
-               emit_line(set, reset, line, len);
+               emit_line(ecbdata->file, plain, reset, line, len);
                return;
        }
        for (i = 0; i < ecbdata->nparents && len; i++) {
@@ -653,7 +628,8 @@ static void fn_out_consume(void *priv, char *line, unsigned long len)
        }
 
        if (color != DIFF_FILE_NEW) {
-               emit_line(diff_get_color(ecbdata->color_diff, color),
+               emit_line(ecbdata->file,
+                         diff_get_color(ecbdata->color_diff, color),
                          reset, line, len);
                return;
        }
@@ -734,7 +710,9 @@ struct diffstat_t {
        int nr;
        int alloc;
        struct diffstat_file {
+               char *from_name;
                char *name;
+               char *print_name;
                unsigned is_unmerged:1;
                unsigned is_binary:1;
                unsigned is_renamed:1;
@@ -755,11 +733,14 @@ static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
        }
        diffstat->files[diffstat->nr++] = x;
        if (name_b) {
-               x->name = pprint_rename(name_a, name_b);
+               x->from_name = xstrdup(name_a);
+               x->name = xstrdup(name_b);
                x->is_renamed = 1;
        }
-       else
+       else {
+               x->from_name = NULL;
                x->name = xstrdup(name_a);
+       }
        return x;
 }
 
@@ -787,20 +768,43 @@ static int scale_linear(int it, int width, int max_change)
        return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
 }
 
-static void show_name(const char *prefix, const char *name, int len,
+static void show_name(FILE *file,
+                     const char *prefix, const char *name, int len,
                      const char *reset, const char *set)
 {
-       printf(" %s%s%-*s%s |", set, prefix, len, name, reset);
+       fprintf(file, " %s%s%-*s%s |", set, prefix, len, name, reset);
 }
 
-static void show_graph(char ch, int cnt, const char *set, const char *reset)
+static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
 {
        if (cnt <= 0)
                return;
-       printf("%s", set);
+       fprintf(file, "%s", set);
        while (cnt--)
-               putchar(ch);
-       printf("%s", reset);
+               putc(ch, file);
+       fprintf(file, "%s", reset);
+}
+
+static void fill_print_name(struct diffstat_file *file)
+{
+       char *pname;
+
+       if (file->print_name)
+               return;
+
+       if (!file->is_renamed) {
+               struct strbuf buf;
+               strbuf_init(&buf, 0);
+               if (quote_c_style(file->name, &buf, NULL, 0)) {
+                       pname = strbuf_detach(&buf, NULL);
+               } else {
+                       pname = file->name;
+                       strbuf_release(&buf);
+               }
+       } else {
+               pname = pprint_rename(file->from_name, file->name);
+       }
+       file->print_name = pname;
 }
 
 static void show_stats(struct diffstat_t* data, struct diff_options *options)
@@ -836,19 +840,8 @@ static void show_stats(struct diffstat_t* data, struct diff_options *options)
        for (i = 0; i < data->nr; i++) {
                struct diffstat_file *file = data->files[i];
                int change = file->added + file->deleted;
-
-               if (!file->is_renamed) {  /* renames are already quoted by pprint_rename */
-                       struct strbuf buf;
-                       strbuf_init(&buf, 0);
-                       if (quote_c_style(file->name, &buf, NULL, 0)) {
-                               free(file->name);
-                               file->name = strbuf_detach(&buf, NULL);
-                       } else {
-                               strbuf_release(&buf);
-                       }
-               }
-
-               len = strlen(file->name);
+               fill_print_name(file);
+               len = strlen(file->print_name);
                if (max_len < len)
                        max_len = len;
 
@@ -873,7 +866,7 @@ static void show_stats(struct diffstat_t* data, struct diff_options *options)
 
        for (i = 0; i < data->nr; i++) {
                const char *prefix = "";
-               char *name = data->files[i]->name;
+               char *name = data->files[i]->print_name;
                int added = data->files[i]->added;
                int deleted = data->files[i]->deleted;
                int name_len;
@@ -894,24 +887,24 @@ static void show_stats(struct diffstat_t* data, struct diff_options *options)
                }
 
                if (data->files[i]->is_binary) {
-                       show_name(prefix, name, len, reset, set);
-                       printf("  Bin ");
-                       printf("%s%d%s", del_c, deleted, reset);
-                       printf(" -> ");
-                       printf("%s%d%s", add_c, added, reset);
-                       printf(" bytes");
-                       printf("\n");
-                       goto free_diffstat_file;
+                       show_name(options->file, prefix, name, len, reset, set);
+                       fprintf(options->file, "  Bin ");
+                       fprintf(options->file, "%s%d%s", del_c, deleted, reset);
+                       fprintf(options->file, " -> ");
+                       fprintf(options->file, "%s%d%s", add_c, added, reset);
+                       fprintf(options->file, " bytes");
+                       fprintf(options->file, "\n");
+                       continue;
                }
                else if (data->files[i]->is_unmerged) {
-                       show_name(prefix, name, len, reset, set);
-                       printf("  Unmerged\n");
-                       goto free_diffstat_file;
+                       show_name(options->file, prefix, name, len, reset, set);
+                       fprintf(options->file, "  Unmerged\n");
+                       continue;
                }
                else if (!data->files[i]->is_renamed &&
                         (added + deleted == 0)) {
                        total_files--;
-                       goto free_diffstat_file;
+                       continue;
                }
 
                /*
@@ -928,21 +921,18 @@ static void show_stats(struct diffstat_t* data, struct diff_options *options)
                        del = scale_linear(del, width, max_change);
                        total = add + del;
                }
-               show_name(prefix, name, len, reset, set);
-               printf("%5d ", added + deleted);
-               show_graph('+', add, add_c, reset);
-               show_graph('-', del, del_c, reset);
-               putchar('\n');
-       free_diffstat_file:
-               free(data->files[i]->name);
-               free(data->files[i]);
-       }
-       free(data->files);
-       printf("%s %d files changed, %d insertions(+), %d deletions(-)%s\n",
+               show_name(options->file, prefix, name, len, reset, set);
+               fprintf(options->file, "%5d ", added + deleted);
+               show_graph(options->file, '+', add, add_c, reset);
+               show_graph(options->file, '-', del, del_c, reset);
+               fprintf(options->file, "\n");
+       }
+       fprintf(options->file,
+              "%s %d files changed, %d insertions(+), %d deletions(-)%s\n",
               set, total_files, adds, dels, reset);
 }
 
-static void show_shortstats(struct diffstat_t* data)
+static void show_shortstats(struct diffstat_t* data, struct diff_options *options)
 {
        int i, adds = 0, dels = 0, total_files = data->nr;
 
@@ -962,12 +952,8 @@ static void show_shortstats(struct diffstat_t* data)
                                dels += deleted;
                        }
                }
-               free(data->files[i]->name);
-               free(data->files[i]);
        }
-       free(data->files);
-
-       printf(" %d files changed, %d insertions(+), %d deletions(-)\n",
+       fprintf(options->file, " %d files changed, %d insertions(+), %d deletions(-)\n",
               total_files, adds, dels);
 }
 
@@ -975,20 +961,169 @@ static void show_numstat(struct diffstat_t* data, struct diff_options *options)
 {
        int i;
 
+       if (data->nr == 0)
+               return;
+
        for (i = 0; i < data->nr; i++) {
                struct diffstat_file *file = data->files[i];
 
                if (file->is_binary)
-                       printf("-\t-\t");
+                       fprintf(options->file, "-\t-\t");
                else
-                       printf("%d\t%d\t", file->added, file->deleted);
-               if (!file->is_renamed) {
-                       write_name_quoted(file->name, stdout, options->line_termination);
+                       fprintf(options->file,
+                               "%d\t%d\t", file->added, file->deleted);
+               if (options->line_termination) {
+                       fill_print_name(file);
+                       if (!file->is_renamed)
+                               write_name_quoted(file->name, options->file,
+                                                 options->line_termination);
+                       else {
+                               fputs(file->print_name, options->file);
+                               putc(options->line_termination, options->file);
+                       }
+               } else {
+                       if (file->is_renamed) {
+                               putc('\0', options->file);
+                               write_name_quoted(file->from_name, options->file, '\0');
+                       }
+                       write_name_quoted(file->name, options->file, '\0');
+               }
+       }
+}
+
+struct dirstat_file {
+       const char *name;
+       unsigned long changed;
+};
+
+struct dirstat_dir {
+       struct dirstat_file *files;
+       int alloc, nr, percent, cumulative;
+};
+
+static long gather_dirstat(FILE *file, struct dirstat_dir *dir, unsigned long changed, const char *base, int baselen)
+{
+       unsigned long this_dir = 0;
+       unsigned int sources = 0;
+
+       while (dir->nr) {
+               struct dirstat_file *f = dir->files;
+               int namelen = strlen(f->name);
+               unsigned long this;
+               char *slash;
+
+               if (namelen < baselen)
+                       break;
+               if (memcmp(f->name, base, baselen))
+                       break;
+               slash = strchr(f->name + baselen, '/');
+               if (slash) {
+                       int newbaselen = slash + 1 - f->name;
+                       this = gather_dirstat(file, dir, changed, f->name, newbaselen);
+                       sources++;
                } else {
-                       fputs(file->name, stdout);
-                       putchar(options->line_termination);
+                       this = f->changed;
+                       dir->files++;
+                       dir->nr--;
+                       sources += 2;
                }
+               this_dir += this;
        }
+
+       /*
+        * We don't report dirstat's for
+        *  - the top level
+        *  - or cases where everything came from a single directory
+        *    under this directory (sources == 1).
+        */
+       if (baselen && sources != 1) {
+               int permille = this_dir * 1000 / changed;
+               if (permille) {
+                       int percent = permille / 10;
+                       if (percent >= dir->percent) {
+                               fprintf(file, "%4d.%01d%% %.*s\n", percent, permille % 10, baselen, base);
+                               if (!dir->cumulative)
+                                       return 0;
+                       }
+               }
+       }
+       return this_dir;
+}
+
+static void show_dirstat(struct diff_options *options)
+{
+       int i;
+       unsigned long changed;
+       struct dirstat_dir dir;
+       struct diff_queue_struct *q = &diff_queued_diff;
+
+       dir.files = NULL;
+       dir.alloc = 0;
+       dir.nr = 0;
+       dir.percent = options->dirstat_percent;
+       dir.cumulative = options->output_format & DIFF_FORMAT_CUMULATIVE;
+
+       changed = 0;
+       for (i = 0; i < q->nr; i++) {
+               struct diff_filepair *p = q->queue[i];
+               const char *name;
+               unsigned long copied, added, damage;
+
+               name = p->one->path ? p->one->path : p->two->path;
+
+               if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
+                       diff_populate_filespec(p->one, 0);
+                       diff_populate_filespec(p->two, 0);
+                       diffcore_count_changes(p->one, p->two, NULL, NULL, 0,
+                                              &copied, &added);
+                       diff_free_filespec_data(p->one);
+                       diff_free_filespec_data(p->two);
+               } else if (DIFF_FILE_VALID(p->one)) {
+                       diff_populate_filespec(p->one, 1);
+                       copied = added = 0;
+                       diff_free_filespec_data(p->one);
+               } else if (DIFF_FILE_VALID(p->two)) {
+                       diff_populate_filespec(p->two, 1);
+                       copied = 0;
+                       added = p->two->size;
+                       diff_free_filespec_data(p->two);
+               } else
+                       continue;
+
+               /*
+                * Original minus copied is the removed material,
+                * added is the new material.  They are both damages
+                * made to the preimage.
+                */
+               damage = (p->one->size - copied) + added;
+
+               ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
+               dir.files[dir.nr].name = name;
+               dir.files[dir.nr].changed = damage;
+               changed += damage;
+               dir.nr++;
+       }
+
+       /* This can happen even with many files, if everything was renames */
+       if (!changed)
+               return;
+
+       /* Show all directories with more than x% of the changes */
+       gather_dirstat(options->file, &dir, changed, "", 0);
+}
+
+static void free_diffstat_info(struct diffstat_t *diffstat)
+{
+       int i;
+       for (i = 0; i < diffstat->nr; i++) {
+               struct diffstat_file *f = diffstat->files[i];
+               if (f->name != f->print_name)
+                       free(f->print_name);
+               free(f->name);
+               free(f->from_name);
+               free(f);
+       }
+       free(diffstat->files);
 }
 
 struct checkdiff_t {
@@ -996,6 +1131,8 @@ struct checkdiff_t {
        const char *filename;
        int lineno, color_diff;
        unsigned ws_rule;
+       unsigned status;
+       FILE *file;
 };
 
 static void checkdiff_consume(void *priv, char *line, unsigned long len)
@@ -1004,44 +1141,26 @@ static void checkdiff_consume(void *priv, char *line, unsigned long len)
        const char *ws = diff_get_color(data->color_diff, DIFF_WHITESPACE);
        const char *reset = diff_get_color(data->color_diff, DIFF_RESET);
        const char *set = diff_get_color(data->color_diff, DIFF_FILE_NEW);
+       char *err;
 
        if (line[0] == '+') {
-               int i, spaces = 0, space_before_tab = 0, white_space_at_end = 0;
-
-               /* check space before tab */
-               for (i = 1; i < len && (line[i] == ' ' || line[i] == '\t'); i++)
-                       if (line[i] == ' ')
-                               spaces++;
-               if (line[i - 1] == '\t' && spaces)
-                       space_before_tab = 1;
-
-               /* check white space at line end */
-               if (line[len - 1] == '\n')
-                       len--;
-               if (isspace(line[len - 1]))
-                       white_space_at_end = 1;
-
-               if (space_before_tab || white_space_at_end) {
-                       printf("%s:%d: %s", data->filename, data->lineno, ws);
-                       if (space_before_tab) {
-                               printf("space before tab");
-                               if (white_space_at_end)
-                                       putchar(',');
-                       }
-                       if (white_space_at_end)
-                               printf("white space at end");
-                       printf(":%s ", reset);
-                       emit_line_with_ws(1, set, reset, ws, line, len,
-                                         data->ws_rule);
-               }
-
                data->lineno++;
+               data->status = check_and_emit_line(line + 1, len - 1,
+                   data->ws_rule, NULL, NULL, NULL, NULL);
+               if (!data->status)
+                       return;
+               err = whitespace_error_string(data->status);
+               fprintf(data->file, "%s:%d: %s.\n", data->filename, data->lineno, err);
+               free(err);
+               emit_line(data->file, set, reset, line, 1);
+               (void)check_and_emit_line(line + 1, len - 1, data->ws_rule,
+                   data->file, set, reset, ws);
        } else if (line[0] == ' ')
                data->lineno++;
        else if (line[0] == '@') {
                char *plus = strchr(line, '+');
                if (plus)
-                       data->lineno = strtol(plus, NULL, 10);
+                       data->lineno = strtol(plus, NULL, 10) - 1;
                else
                        die("invalid diff");
        }
@@ -1071,7 +1190,7 @@ static unsigned char *deflate_it(char *data,
        return deflated;
 }
 
-static void emit_binary_diff_body(mmfile_t *one, mmfile_t *two)
+static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two)
 {
        void *cp;
        void *delta;
@@ -1100,13 +1219,13 @@ static void emit_binary_diff_body(mmfile_t *one, mmfile_t *two)
        }
 
        if (delta && delta_size < deflate_size) {
-               printf("delta %lu\n", orig_size);
+               fprintf(file, "delta %lu\n", orig_size);
                free(deflated);
                data = delta;
                data_size = delta_size;
        }
        else {
-               printf("literal %lu\n", two->size);
+               fprintf(file, "literal %lu\n", two->size);
                free(delta);
                data = deflated;
                data_size = deflate_size;
@@ -1124,17 +1243,18 @@ static void emit_binary_diff_body(mmfile_t *one, mmfile_t *two)
                        line[0] = bytes - 26 + 'a' - 1;
                encode_85(line + 1, cp, bytes);
                cp = (char *) cp + bytes;
-               puts(line);
+               fputs(line, file);
+               fputc('\n', file);
        }
-       printf("\n");
+       fprintf(file, "\n");
        free(data);
 }
 
-static void emit_binary_diff(mmfile_t *one, mmfile_t *two)
+static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two)
 {
-       printf("GIT binary patch\n");
-       emit_binary_diff_body(one, two);
-       emit_binary_diff_body(two, one);
+       fprintf(file, "GIT binary patch\n");
+       emit_binary_diff_body(file, one, two);
+       emit_binary_diff_body(file, two, one);
 }
 
 static void setup_diff_attr_check(struct git_attr_check *check)
@@ -1197,7 +1317,6 @@ static const char *funcname_pattern(const char *ident)
 {
        struct funcname_pattern *pp;
 
-       read_config_if_needed();
        for (pp = funcname_pattern_list; pp; pp = pp->next)
                if (!strcmp(ident, pp->name))
                        return pp->pattern;
@@ -1212,7 +1331,7 @@ static struct builtin_funcname_pattern {
                        "new\\|return\\|switch\\|throw\\|while\\)\n"
                        "^[     ]*\\(\\([       ]*"
                        "[A-Za-z_][A-Za-z_0-9]*\\)\\{2,\\}"
-                       "[      ]*([^;]*$\\)" },
+                       "[      ]*([^;]*\\)$" },
        { "tex", "^\\(\\\\\\(sub\\)*section{.*\\)$" },
 };
 
@@ -1239,7 +1358,7 @@ static const char *diff_funcname_pattern(struct diff_filespec *one)
 
        /*
         * And define built-in fallback patterns here.  Note that
-        * these can be overriden by the user's config settings.
+        * these can be overridden by the user's config settings.
         */
        for (i = 0; i < ARRAY_SIZE(builtin_funcname_pattern); i++)
                if (!strcmp(ident, builtin_funcname_pattern[i].name))
@@ -1262,29 +1381,29 @@ static void builtin_diff(const char *name_a,
        const char *set = diff_get_color_opt(o, DIFF_METAINFO);
        const char *reset = diff_get_color_opt(o, DIFF_RESET);
 
-       a_one = quote_two("a/", name_a + (*name_a == '/'));
-       b_two = quote_two("b/", name_b + (*name_b == '/'));
+       a_one = quote_two(o->a_prefix, name_a + (*name_a == '/'));
+       b_two = quote_two(o->b_prefix, name_b + (*name_b == '/'));
        lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
        lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
-       printf("%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
+       fprintf(o->file, "%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
        if (lbl[0][0] == '/') {
                /* /dev/null */
-               printf("%snew file mode %06o%s\n", set, two->mode, reset);
+               fprintf(o->file, "%snew file mode %06o%s\n", set, two->mode, reset);
                if (xfrm_msg && xfrm_msg[0])
-                       printf("%s%s%s\n", set, xfrm_msg, reset);
+                       fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
        }
        else if (lbl[1][0] == '/') {
-               printf("%sdeleted file mode %06o%s\n", set, one->mode, reset);
+               fprintf(o->file, "%sdeleted file mode %06o%s\n", set, one->mode, reset);
                if (xfrm_msg && xfrm_msg[0])
-                       printf("%s%s%s\n", set, xfrm_msg, reset);
+                       fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
        }
        else {
                if (one->mode != two->mode) {
-                       printf("%sold mode %06o%s\n", set, one->mode, reset);
-                       printf("%snew mode %06o%s\n", set, two->mode, reset);
+                       fprintf(o->file, "%sold mode %06o%s\n", set, one->mode, reset);
+                       fprintf(o->file, "%snew mode %06o%s\n", set, two->mode, reset);
                }
                if (xfrm_msg && xfrm_msg[0])
-                       printf("%s%s%s\n", set, xfrm_msg, reset);
+                       fprintf(o->file, "%s%s%s\n", set, xfrm_msg, reset);
                /*
                 * we do not run diff between different kind
                 * of objects.
@@ -1292,8 +1411,7 @@ static void builtin_diff(const char *name_a,
                if ((one->mode ^ two->mode) & S_IFMT)
                        goto free_ab_and_return;
                if (complete_rewrite) {
-                       emit_rewrite_diff(name_a, name_b, one, two,
-                                       DIFF_OPT_TST(o, COLOR_DIFF));
+                       emit_rewrite_diff(name_a, name_b, one, two, o);
                        o->found_changes = 1;
                        goto free_ab_and_return;
                }
@@ -1309,10 +1427,10 @@ static void builtin_diff(const char *name_a,
                    !memcmp(mf1.ptr, mf2.ptr, mf1.size))
                        goto free_ab_and_return;
                if (DIFF_OPT_TST(o, BINARY))
-                       emit_binary_diff(&mf1, &mf2);
+                       emit_binary_diff(o->file, &mf1, &mf2);
                else
-                       printf("Binary files %s and %s differ\n",
-                              lbl[0], lbl[1]);
+                       fprintf(o->file, "Binary files %s and %s differ\n",
+                               lbl[0], lbl[1]);
                o->found_changes = 1;
        }
        else {
@@ -1334,6 +1452,7 @@ static void builtin_diff(const char *name_a,
                ecbdata.color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
                ecbdata.found_changesp = &o->found_changes;
                ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
+               ecbdata.file = o->file;
                xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
                xecfg.ctxlen = o->context;
                xecfg.flags = XDL_EMIT_FUNCNAMES;
@@ -1348,10 +1467,12 @@ static void builtin_diff(const char *name_a,
                ecb.outf = xdiff_outf;
                ecb.priv = &ecbdata;
                ecbdata.xm.consume = fn_out_consume;
-               if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS))
+               if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS)) {
                        ecbdata.diff_words =
                                xcalloc(1, sizeof(struct diff_words_data));
-               xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
+                       ecbdata.diff_words->file = o->file;
+               }
+               xdi_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
                if (DIFF_OPT_TST(o, COLOR_DIFF_WORDS))
                        free_diff_words_data(&ecbdata);
        }
@@ -1404,7 +1525,7 @@ static void builtin_diffstat(const char *name_a, const char *name_b,
                xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
                ecb.outf = xdiff_outf;
                ecb.priv = diffstat;
-               xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
+               xdi_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
        }
 
  free_and_return:
@@ -1413,6 +1534,7 @@ static void builtin_diffstat(const char *name_a, const char *name_b,
 }
 
 static void builtin_checkdiff(const char *name_a, const char *name_b,
+                             const char *attr_path,
                             struct diff_filespec *one,
                             struct diff_filespec *two, struct diff_options *o)
 {
@@ -1427,7 +1549,8 @@ static void builtin_checkdiff(const char *name_a, const char *name_b,
        data.filename = name_b ? name_b : name_a;
        data.lineno = 0;
        data.color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
-       data.ws_rule = whitespace_rule(data.filename);
+       data.ws_rule = whitespace_rule(attr_path);
+       data.file = o->file;
 
        if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
                die("unable to read files to diff");
@@ -1444,11 +1567,13 @@ static void builtin_checkdiff(const char *name_a, const char *name_b,
                xpp.flags = XDF_NEED_MINIMAL;
                ecb.outf = xdiff_outf;
                ecb.priv = &data;
-               xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
+               xdi_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
        }
  free_and_return:
        diff_free_filespec_data(one);
        diff_free_filespec_data(two);
+       if (data.status)
+               DIFF_OPT_SET(o, CHECK_FAILED);
 }
 
 struct diff_filespec *alloc_filespec(const char *path)
@@ -1524,17 +1649,22 @@ static int reuse_worktree_file(const char *name, const unsigned char *sha1, int
        if (pos < 0)
                return 0;
        ce = active_cache[pos];
-       if ((lstat(name, &st) < 0) ||
-           !S_ISREG(st.st_mode) || /* careful! */
-           ce_match_stat(ce, &st, 0) ||
-           hashcmp(sha1, ce->sha1))
+
+       /*
+        * This is not the sha1 we are looking for, or
+        * unreusable because it is not a regular file.
+        */
+       if (hashcmp(sha1, ce->sha1) || !S_ISREG(ce->ce_mode))
                return 0;
-       /* we return 1 only when we can stat, it is a regular file,
-        * stat information matches, and sha1 recorded in the cache
-        * matches.  I.e. we know the file in the work tree really is
-        * the same as the <name, sha1> pair.
+
+       /*
+        * If ce matches the file in the work tree, we can reuse it.
         */
-       return 1;
+       if (ce_uptodate(ce) ||
+           (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
+               return 1;
+
+       return 0;
 }
 
 static int populate_from_stdin(struct diff_filespec *s)
@@ -1638,7 +1768,7 @@ int diff_populate_filespec(struct diff_filespec *s, int size_only)
                 * Convert from working tree format to canonical git format
                 */
                strbuf_init(&buf, 0);
-               if (convert_to_git(s->path, s->data, s->size, &buf)) {
+               if (convert_to_git(s->path, s->data, s->size, &buf, safe_crlf)) {
                        size_t size = 0;
                        munmap(s->data, s->size);
                        s->should_munmap = 0;
@@ -1845,6 +1975,9 @@ static const char *external_diff_attr(const char *name)
 {
        struct git_attr_check attr_diff_check;
 
+       if (!name)
+               return NULL;
+
        setup_diff_attr_check(&attr_diff_check);
        if (!git_checkattr(name, 1, &attr_diff_check)) {
                const char *value = attr_diff_check.value;
@@ -1853,7 +1986,6 @@ static const char *external_diff_attr(const char *name)
                    !ATTR_UNSET(value)) {
                        struct ll_diff_driver *drv;
 
-                       read_config_if_needed();
                        for (drv = user_diff; drv; drv = drv->next)
                                if (!strcmp(drv->name, value))
                                        return drv->cmd;
@@ -1865,6 +1997,7 @@ static const char *external_diff_attr(const char *name)
 static void run_diff_cmd(const char *pgm,
                         const char *name,
                         const char *other,
+                        const char *attr_path,
                         struct diff_filespec *one,
                         struct diff_filespec *two,
                         const char *xfrm_msg,
@@ -1874,7 +2007,7 @@ static void run_diff_cmd(const char *pgm,
        if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
                pgm = NULL;
        else {
-               const char *cmd = external_diff_attr(name);
+               const char *cmd = external_diff_attr(attr_path);
                if (cmd)
                        pgm = cmd;
        }
@@ -1888,7 +2021,7 @@ static void run_diff_cmd(const char *pgm,
                builtin_diff(name, other ? other : name,
                             one, two, xfrm_msg, o, complete_rewrite);
        else
-               printf("* Unmerged path %s\n", name);
+               fprintf(o->file, "* Unmerged path %s\n", name);
 }
 
 static void diff_fill_sha1_info(struct diff_filespec *one)
@@ -1915,6 +2048,15 @@ static int similarity_index(struct diff_filepair *p)
        return p->score * 100 / MAX_SCORE;
 }
 
+static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
+{
+       /* Strip the prefix but do not molest /dev/null and absolute paths */
+       if (*namep && **namep != '/')
+               *namep += prefix_length;
+       if (*otherp && **otherp != '/')
+               *otherp += prefix_length;
+}
+
 static void run_diff(struct diff_filepair *p, struct diff_options *o)
 {
        const char *pgm = external_diff();
@@ -1924,16 +2066,21 @@ static void run_diff(struct diff_filepair *p, struct diff_options *o)
        struct diff_filespec *two = p->two;
        const char *name;
        const char *other;
+       const char *attr_path;
        int complete_rewrite = 0;
 
+       name  = p->one->path;
+       other = (strcmp(name, p->two->path) ? p->two->path : NULL);
+       attr_path = name;
+       if (o->prefix_length)
+               strip_prefix(o->prefix_length, &name, &other);
 
        if (DIFF_PAIR_UNMERGED(p)) {
-               run_diff_cmd(pgm, p->one->path, NULL, NULL, NULL, NULL, o, 0);
+               run_diff_cmd(pgm, name, NULL, attr_path,
+                            NULL, NULL, NULL, o, 0);
                return;
        }
 
-       name  = p->one->path;
-       other = (strcmp(name, p->two->path) ? p->two->path : NULL);
        diff_fill_sha1_info(one);
        diff_fill_sha1_info(two);
 
@@ -1996,15 +2143,17 @@ static void run_diff(struct diff_filepair *p, struct diff_options *o)
                 * needs to be split into deletion and creation.
                 */
                struct diff_filespec *null = alloc_filespec(two->path);
-               run_diff_cmd(NULL, name, other, one, null, xfrm_msg, o, 0);
+               run_diff_cmd(NULL, name, other, attr_path,
+                            one, null, xfrm_msg, o, 0);
                free(null);
                null = alloc_filespec(one->path);
-               run_diff_cmd(NULL, name, other, null, two, xfrm_msg, o, 0);
+               run_diff_cmd(NULL, name, other, attr_path,
+                            null, two, xfrm_msg, o, 0);
                free(null);
        }
        else
-               run_diff_cmd(pgm, name, other, one, two, xfrm_msg, o,
-                            complete_rewrite);
+               run_diff_cmd(pgm, name, other, attr_path,
+                            one, two, xfrm_msg, o, complete_rewrite);
 
        strbuf_release(&msg);
 }
@@ -2025,6 +2174,9 @@ static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
        name = p->one->path;
        other = (strcmp(name, p->two->path) ? p->two->path : NULL);
 
+       if (o->prefix_length)
+               strip_prefix(o->prefix_length, &name, &other);
+
        diff_fill_sha1_info(p->one);
        diff_fill_sha1_info(p->two);
 
@@ -2037,6 +2189,7 @@ static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
 {
        const char *name;
        const char *other;
+       const char *attr_path;
 
        if (DIFF_PAIR_UNMERGED(p)) {
                /* unmerged */
@@ -2045,29 +2198,40 @@ static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
 
        name = p->one->path;
        other = (strcmp(name, p->two->path) ? p->two->path : NULL);
+       attr_path = other ? other : name;
+
+       if (o->prefix_length)
+               strip_prefix(o->prefix_length, &name, &other);
 
        diff_fill_sha1_info(p->one);
        diff_fill_sha1_info(p->two);
 
-       builtin_checkdiff(name, other, p->one, p->two, o);
+       builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
 }
 
 void diff_setup(struct diff_options *options)
 {
        memset(options, 0, sizeof(*options));
+
+       options->file = stdout;
+
        options->line_termination = '\n';
        options->break_opt = -1;
        options->rename_limit = -1;
+       options->dirstat_percent = 3;
        options->context = 3;
        options->msg_sep = "";
 
        options->change = diff_change;
        options->add_remove = diff_addremove;
-       if (diff_use_color_default)
+       if (diff_use_color_default > 0)
                DIFF_OPT_SET(options, COLOR_DIFF);
        else
                DIFF_OPT_CLR(options, COLOR_DIFF);
        options->detect_rename = diff_detect_rename_default;
+
+       options->a_prefix = "a/";
+       options->b_prefix = "b/";
 }
 
 int diff_setup_done(struct diff_options *options)
@@ -2088,6 +2252,13 @@ int diff_setup_done(struct diff_options *options)
        if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
                options->detect_rename = DIFF_DETECT_COPY;
 
+       if (!DIFF_OPT_TST(options, RELATIVE_NAME))
+               options->prefix = NULL;
+       if (options->prefix)
+               options->prefix_length = strlen(options->prefix);
+       else
+               options->prefix_length = 0;
+
        if (options->output_format & (DIFF_FORMAT_NAME |
                                      DIFF_FORMAT_NAME_STATUS |
                                      DIFF_FORMAT_CHECKDIFF |
@@ -2096,6 +2267,7 @@ int diff_setup_done(struct diff_options *options)
                                            DIFF_FORMAT_NUMSTAT |
                                            DIFF_FORMAT_DIFFSTAT |
                                            DIFF_FORMAT_SHORTSTAT |
+                                           DIFF_FORMAT_DIRSTAT |
                                            DIFF_FORMAT_SUMMARY |
                                            DIFF_FORMAT_PATCH);
 
@@ -2107,6 +2279,7 @@ int diff_setup_done(struct diff_options *options)
                                      DIFF_FORMAT_NUMSTAT |
                                      DIFF_FORMAT_DIFFSTAT |
                                      DIFF_FORMAT_SHORTSTAT |
+                                     DIFF_FORMAT_DIRSTAT |
                                      DIFF_FORMAT_SUMMARY |
                                      DIFF_FORMAT_CHECKDIFF))
                DIFF_OPT_SET(options, RECURSIVE);
@@ -2217,6 +2390,10 @@ int diff_opt_parse(struct diff_options *options, const char **av, int ac)
                options->output_format |= DIFF_FORMAT_NUMSTAT;
        else if (!strcmp(arg, "--shortstat"))
                options->output_format |= DIFF_FORMAT_SHORTSTAT;
+       else if (opt_arg(arg, 'X', "dirstat", &options->dirstat_percent))
+               options->output_format |= DIFF_FORMAT_DIRSTAT;
+       else if (!strcmp(arg, "--cumulative"))
+               options->output_format |= DIFF_FORMAT_CUMULATIVE;
        else if (!strcmp(arg, "--check"))
                options->output_format |= DIFF_FORMAT_CHECKDIFF;
        else if (!strcmp(arg, "--summary"))
@@ -2276,6 +2453,12 @@ int diff_opt_parse(struct diff_options *options, const char **av, int ac)
        }
        else if (!strcmp(arg, "--no-renames"))
                options->detect_rename = 0;
+       else if (!strcmp(arg, "--relative"))
+               DIFF_OPT_SET(options, RELATIVE_NAME);
+       else if (!prefixcmp(arg, "--relative=")) {
+               DIFF_OPT_SET(options, RELATIVE_NAME);
+               options->prefix = arg + 11;
+       }
 
        /* xdiff options */
        else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
@@ -2339,7 +2522,16 @@ int diff_opt_parse(struct diff_options *options, const char **av, int ac)
                else if (40 < options->abbrev)
                        options->abbrev = 40;
        }
-       else
+       else if (!prefixcmp(arg, "--src-prefix="))
+               options->a_prefix = arg + 13;
+       else if (!prefixcmp(arg, "--dst-prefix="))
+               options->b_prefix = arg + 13;
+       else if (!strcmp(arg, "--no-prefix"))
+               options->a_prefix = options->b_prefix = "";
+       else if (!prefixcmp(arg, "--output=")) {
+               options->file = fopen(arg + strlen("--output="), "w");
+               options->close_file = 1;
+       } else
                return 0;
        return 1;
 }
@@ -2450,8 +2642,6 @@ const char *diff_unique_abbrev(const unsigned char *sha1, int len)
                return sha1_to_hex(sha1);
 
        abbrev = find_unique_abbrev(sha1, len);
-       if (!abbrev)
-               return sha1_to_hex(sha1);
        abblen = strlen(abbrev);
        if (abblen < 37) {
                static char hex[41];
@@ -2470,23 +2660,31 @@ static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
        int inter_name_termination = line_termination ? '\t' : '\0';
 
        if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
-               printf(":%06o %06o %s ", p->one->mode, p->two->mode,
-                      diff_unique_abbrev(p->one->sha1, opt->abbrev));
-               printf("%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
+               fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
+                       diff_unique_abbrev(p->one->sha1, opt->abbrev));
+               fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
        }
        if (p->score) {
-               printf("%c%03d%c", p->status, similarity_index(p),
-                          inter_name_termination);
+               fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
+                       inter_name_termination);
        } else {
-               printf("%c%c", p->status, inter_name_termination);
+               fprintf(opt->file, "%c%c", p->status, inter_name_termination);
        }
 
-       if (p->status == DIFF_STATUS_COPIED || p->status == DIFF_STATUS_RENAMED) {
-               write_name_quoted(p->one->path, stdout, inter_name_termination);
-               write_name_quoted(p->two->path, stdout, line_termination);
+       if (p->status == DIFF_STATUS_COPIED ||
+           p->status == DIFF_STATUS_RENAMED) {
+               const char *name_a, *name_b;
+               name_a = p->one->path;
+               name_b = p->two->path;
+               strip_prefix(opt->prefix_length, &name_a, &name_b);
+               write_name_quoted(name_a, opt->file, inter_name_termination);
+               write_name_quoted(name_b, opt->file, line_termination);
        } else {
-               const char *path = p->one->mode ? p->one->path : p->two->path;
-               write_name_quoted(path, stdout, line_termination);
+               const char *name_a, *name_b;
+               name_a = p->one->mode ? p->one->path : p->two->path;
+               name_b = NULL;
+               strip_prefix(opt->prefix_length, &name_a, &name_b);
+               write_name_quoted(name_a, opt->file, line_termination);
        }
 }
 
@@ -2683,62 +2881,67 @@ static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
                diff_flush_checkdiff(p, opt);
        else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
                diff_flush_raw(p, opt);
-       else if (fmt & DIFF_FORMAT_NAME)
-               write_name_quoted(p->two->path, stdout, opt->line_termination);
+       else if (fmt & DIFF_FORMAT_NAME) {
+               const char *name_a, *name_b;
+               name_a = p->two->path;
+               name_b = NULL;
+               strip_prefix(opt->prefix_length, &name_a, &name_b);
+               write_name_quoted(name_a, opt->file, opt->line_termination);
+       }
 }
 
-static void show_file_mode_name(const char *newdelete, struct diff_filespec *fs)
+static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
 {
        if (fs->mode)
-               printf(" %s mode %06o ", newdelete, fs->mode);
+               fprintf(file, " %s mode %06o ", newdelete, fs->mode);
        else
-               printf(" %s ", newdelete);
-       write_name_quoted(fs->path, stdout, '\n');
+               fprintf(file, " %s ", newdelete);
+       write_name_quoted(fs->path, file, '\n');
 }
 
 
-static void show_mode_change(struct diff_filepair *p, int show_name)
+static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name)
 {
        if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
-               printf(" mode change %06o => %06o%c", p->one->mode, p->two->mode,
+               fprintf(file, " mode change %06o => %06o%c", p->one->mode, p->two->mode,
                        show_name ? ' ' : '\n');
                if (show_name) {
-                       write_name_quoted(p->two->path, stdout, '\n');
+                       write_name_quoted(p->two->path, file, '\n');
                }
        }
 }
 
-static void show_rename_copy(const char *renamecopy, struct diff_filepair *p)
+static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p)
 {
        char *names = pprint_rename(p->one->path, p->two->path);
 
-       printf(" %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
+       fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
        free(names);
-       show_mode_change(p, 0);
+       show_mode_change(file, p, 0);
 }
 
-static void diff_summary(struct diff_filepair *p)
+static void diff_summary(FILE *file, struct diff_filepair *p)
 {
        switch(p->status) {
        case DIFF_STATUS_DELETED:
-               show_file_mode_name("delete", p->one);
+               show_file_mode_name(file, "delete", p->one);
                break;
        case DIFF_STATUS_ADDED:
-               show_file_mode_name("create", p->two);
+               show_file_mode_name(file, "create", p->two);
                break;
        case DIFF_STATUS_COPIED:
-               show_rename_copy("copy", p);
+               show_rename_copy(file, "copy", p);
                break;
        case DIFF_STATUS_RENAMED:
-               show_rename_copy("rename", p);
+               show_rename_copy(file, "rename", p);
                break;
        default:
                if (p->score) {
-                       fputs(" rewrite ", stdout);
-                       write_name_quoted(p->two->path, stdout, ' ');
-                       printf("(%d%%)\n", similarity_index(p));
+                       fputs(" rewrite ", file);
+                       write_name_quoted(p->two->path, file, ' ');
+                       fprintf(file, "(%d%%)\n", similarity_index(p));
                }
-               show_mode_change(p, !p->score);
+               show_mode_change(file, p, !p->score);
                break;
        }
 }
@@ -2856,7 +3059,7 @@ static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
                xecfg.flags = XDL_EMIT_FUNCNAMES;
                ecb.outf = xdiff_outf;
                ecb.priv = &data;
-               xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
+               xdi_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
        }
 
        SHA1_Final(sha1, &ctx);
@@ -2943,14 +3146,17 @@ void diff_flush(struct diff_options *options)
                        show_numstat(&diffstat, options);
                if (output_format & DIFF_FORMAT_DIFFSTAT)
                        show_stats(&diffstat, options);
-               else if (output_format & DIFF_FORMAT_SHORTSTAT)
-                       show_shortstats(&diffstat);
+               if (output_format & DIFF_FORMAT_SHORTSTAT)
+                       show_shortstats(&diffstat, options);
+               free_diffstat_info(&diffstat);
                separator++;
        }
+       if (output_format & DIFF_FORMAT_DIRSTAT)
+               show_dirstat(options);
 
        if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
                for (i = 0; i < q->nr; i++)
-                       diff_summary(q->queue[i]);
+                       diff_summary(options->file, q->queue[i]);
                separator++;
        }
 
@@ -2958,9 +3164,9 @@ void diff_flush(struct diff_options *options)
                if (separator) {
                        if (options->stat_sep) {
                                /* attach patch instead of inline */
-                               fputs(options->stat_sep, stdout);
+                               fputs(options->stat_sep, options->file);
                        } else {
-                               putchar(options->line_termination);
+                               putc(options->line_termination, options->file);
                        }
                }
 
@@ -2980,6 +3186,8 @@ void diff_flush(struct diff_options *options)
        free(q->queue);
        q->queue = NULL;
        q->nr = q->alloc = 0;
+       if (options->close_file)
+               fclose(options->file);
 }
 
 static void diffcore_apply_filter(const char *filter)
@@ -3042,11 +3250,8 @@ static void diffcore_apply_filter(const char *filter)
 static int diff_filespec_is_identical(struct diff_filespec *one,
                                      struct diff_filespec *two)
 {
-       if (S_ISGITLINK(one->mode)) {
-               diff_fill_sha1_info(one);
-               diff_fill_sha1_info(two);
-               return !hashcmp(one->sha1, two->sha1);
-       }
+       if (S_ISGITLINK(one->mode))
+               return 0;
        if (diff_populate_filespec(one, 0))
                return 0;
        if (diff_populate_filespec(two, 0))
@@ -3128,6 +3333,20 @@ void diffcore_std(struct diff_options *options)
                DIFF_OPT_CLR(options, HAS_CHANGES);
 }
 
+int diff_result_code(struct diff_options *opt, int status)
+{
+       int result = 0;
+       if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
+           !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
+               return status;
+       if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
+           DIFF_OPT_TST(opt, HAS_CHANGES))
+               result |= 01;
+       if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
+           DIFF_OPT_TST(opt, CHECK_FAILED))
+               result |= 02;
+       return result;
+}
 
 void diff_addremove(struct diff_options *options,
                    int addremove, unsigned mode,
@@ -3155,6 +3374,11 @@ void diff_addremove(struct diff_options *options,
 
        if (!path) path = "";
        sprintf(concatpath, "%s%s", base, path);
+
+       if (options->prefix &&
+           strncmp(concatpath, options->prefix, options->prefix_length))
+               return;
+
        one = alloc_filespec(concatpath);
        two = alloc_filespec(concatpath);
 
@@ -3184,6 +3408,11 @@ void diff_change(struct diff_options *options,
        }
        if (!path) path = "";
        sprintf(concatpath, "%s%s", base, path);
+
+       if (options->prefix &&
+           strncmp(concatpath, options->prefix, options->prefix_length))
+               return;
+
        one = alloc_filespec(concatpath);
        two = alloc_filespec(concatpath);
        fill_filespec(one, old_sha1, old_mode);
@@ -3198,6 +3427,11 @@ void diff_unmerge(struct diff_options *options,
                  unsigned mode, const unsigned char *sha1)
 {
        struct diff_filespec *one, *two;
+
+       if (options->prefix &&
+           strncmp(path, options->prefix, options->prefix_length))
+               return;
+
        one = alloc_filespec(path);
        two = alloc_filespec(path);
        fill_filespec(one, sha1, mode);