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