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