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