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