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