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