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