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