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