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