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