THIS IS A TEST INSTANCE ONLY! REPOSITORIES CAN BE DELETED AT ANY TIME!

Git Source Code Mirror - This is a publish-only repository and all pull requests are ignored. Please follow Documentation/SubmittingPatches procedure for any of your improvements.
git
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

6850 lines
188KB

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