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