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