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