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.

6857 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. struct diffstat_t {
  2241. int nr;
  2242. int alloc;
  2243. struct diffstat_file {
  2244. char *from_name;
  2245. char *name;
  2246. char *print_name;
  2247. const char *comments;
  2248. unsigned is_unmerged:1;
  2249. unsigned is_binary:1;
  2250. unsigned is_renamed:1;
  2251. unsigned is_interesting:1;
  2252. uintmax_t added, deleted;
  2253. } **files;
  2254. };
  2255. static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
  2256. const char *name_a,
  2257. const char *name_b)
  2258. {
  2259. struct diffstat_file *x;
  2260. x = xcalloc(1, sizeof(*x));
  2261. ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
  2262. diffstat->files[diffstat->nr++] = x;
  2263. if (name_b) {
  2264. x->from_name = xstrdup(name_a);
  2265. x->name = xstrdup(name_b);
  2266. x->is_renamed = 1;
  2267. }
  2268. else {
  2269. x->from_name = NULL;
  2270. x->name = xstrdup(name_a);
  2271. }
  2272. return x;
  2273. }
  2274. static void diffstat_consume(void *priv, char *line, unsigned long len)
  2275. {
  2276. struct diffstat_t *diffstat = priv;
  2277. struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
  2278. if (line[0] == '+')
  2279. x->added++;
  2280. else if (line[0] == '-')
  2281. x->deleted++;
  2282. }
  2283. const char mime_boundary_leader[] = "------------";
  2284. static int scale_linear(int it, int width, int max_change)
  2285. {
  2286. if (!it)
  2287. return 0;
  2288. /*
  2289. * make sure that at least one '-' or '+' is printed if
  2290. * there is any change to this path. The easiest way is to
  2291. * scale linearly as if the alloted width is one column shorter
  2292. * than it is, and then add 1 to the result.
  2293. */
  2294. return 1 + (it * (width - 1) / max_change);
  2295. }
  2296. static void show_graph(struct strbuf *out, char ch, int cnt,
  2297. const char *set, const char *reset)
  2298. {
  2299. if (cnt <= 0)
  2300. return;
  2301. strbuf_addstr(out, set);
  2302. strbuf_addchars(out, ch, cnt);
  2303. strbuf_addstr(out, reset);
  2304. }
  2305. static void fill_print_name(struct diffstat_file *file)
  2306. {
  2307. struct strbuf pname = STRBUF_INIT;
  2308. if (file->print_name)
  2309. return;
  2310. if (file->is_renamed)
  2311. pprint_rename(&pname, file->from_name, file->name);
  2312. else
  2313. quote_c_style(file->name, &pname, NULL, 0);
  2314. if (file->comments)
  2315. strbuf_addf(&pname, " (%s)", file->comments);
  2316. file->print_name = strbuf_detach(&pname, NULL);
  2317. }
  2318. static void print_stat_summary_inserts_deletes(struct diff_options *options,
  2319. int files, int insertions, int deletions)
  2320. {
  2321. struct strbuf sb = STRBUF_INIT;
  2322. if (!files) {
  2323. assert(insertions == 0 && deletions == 0);
  2324. emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_NO_FILES,
  2325. NULL, 0, 0);
  2326. return;
  2327. }
  2328. strbuf_addf(&sb,
  2329. (files == 1) ? " %d file changed" : " %d files changed",
  2330. files);
  2331. /*
  2332. * For binary diff, the caller may want to print "x files
  2333. * changed" with insertions == 0 && deletions == 0.
  2334. *
  2335. * Not omitting "0 insertions(+), 0 deletions(-)" in this case
  2336. * is probably less confusing (i.e skip over "2 files changed
  2337. * but nothing about added/removed lines? Is this a bug in Git?").
  2338. */
  2339. if (insertions || deletions == 0) {
  2340. strbuf_addf(&sb,
  2341. (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
  2342. insertions);
  2343. }
  2344. if (deletions || insertions == 0) {
  2345. strbuf_addf(&sb,
  2346. (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
  2347. deletions);
  2348. }
  2349. strbuf_addch(&sb, '\n');
  2350. emit_diff_symbol(options, DIFF_SYMBOL_STATS_SUMMARY_INSERTS_DELETES,
  2351. sb.buf, sb.len, 0);
  2352. strbuf_release(&sb);
  2353. }
  2354. void print_stat_summary(FILE *fp, int files,
  2355. int insertions, int deletions)
  2356. {
  2357. struct diff_options o;
  2358. memset(&o, 0, sizeof(o));
  2359. o.file = fp;
  2360. print_stat_summary_inserts_deletes(&o, files, insertions, deletions);
  2361. }
  2362. static void show_stats(struct diffstat_t *data, struct diff_options *options)
  2363. {
  2364. int i, len, add, del, adds = 0, dels = 0;
  2365. uintmax_t max_change = 0, max_len = 0;
  2366. int total_files = data->nr, count;
  2367. int width, name_width, graph_width, number_width = 0, bin_width = 0;
  2368. const char *reset, *add_c, *del_c;
  2369. int extra_shown = 0;
  2370. const char *line_prefix = diff_line_prefix(options);
  2371. struct strbuf out = STRBUF_INIT;
  2372. if (data->nr == 0)
  2373. return;
  2374. count = options->stat_count ? options->stat_count : data->nr;
  2375. reset = diff_get_color_opt(options, DIFF_RESET);
  2376. add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
  2377. del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
  2378. /*
  2379. * Find the longest filename and max number of changes
  2380. */
  2381. for (i = 0; (i < count) && (i < data->nr); i++) {
  2382. struct diffstat_file *file = data->files[i];
  2383. uintmax_t change = file->added + file->deleted;
  2384. if (!file->is_interesting && (change == 0)) {
  2385. count++; /* not shown == room for one more */
  2386. continue;
  2387. }
  2388. fill_print_name(file);
  2389. len = strlen(file->print_name);
  2390. if (max_len < len)
  2391. max_len = len;
  2392. if (file->is_unmerged) {
  2393. /* "Unmerged" is 8 characters */
  2394. bin_width = bin_width < 8 ? 8 : bin_width;
  2395. continue;
  2396. }
  2397. if (file->is_binary) {
  2398. /* "Bin XXX -> YYY bytes" */
  2399. int w = 14 + decimal_width(file->added)
  2400. + decimal_width(file->deleted);
  2401. bin_width = bin_width < w ? w : bin_width;
  2402. /* Display change counts aligned with "Bin" */
  2403. number_width = 3;
  2404. continue;
  2405. }
  2406. if (max_change < change)
  2407. max_change = change;
  2408. }
  2409. count = i; /* where we can stop scanning in data->files[] */
  2410. /*
  2411. * We have width = stat_width or term_columns() columns total.
  2412. * We want a maximum of min(max_len, stat_name_width) for the name part.
  2413. * We want a maximum of min(max_change, stat_graph_width) for the +- part.
  2414. * We also need 1 for " " and 4 + decimal_width(max_change)
  2415. * for " | NNNN " and one the empty column at the end, altogether
  2416. * 6 + decimal_width(max_change).
  2417. *
  2418. * If there's not enough space, we will use the smaller of
  2419. * stat_name_width (if set) and 5/8*width for the filename,
  2420. * and the rest for constant elements + graph part, but no more
  2421. * than stat_graph_width for the graph part.
  2422. * (5/8 gives 50 for filename and 30 for the constant parts + graph
  2423. * for the standard terminal size).
  2424. *
  2425. * In other words: stat_width limits the maximum width, and
  2426. * stat_name_width fixes the maximum width of the filename,
  2427. * and is also used to divide available columns if there
  2428. * aren't enough.
  2429. *
  2430. * Binary files are displayed with "Bin XXX -> YYY bytes"
  2431. * instead of the change count and graph. This part is treated
  2432. * similarly to the graph part, except that it is not
  2433. * "scaled". If total width is too small to accommodate the
  2434. * guaranteed minimum width of the filename part and the
  2435. * separators and this message, this message will "overflow"
  2436. * making the line longer than the maximum width.
  2437. */
  2438. if (options->stat_width == -1)
  2439. width = term_columns() - strlen(line_prefix);
  2440. else
  2441. width = options->stat_width ? options->stat_width : 80;
  2442. number_width = decimal_width(max_change) > number_width ?
  2443. decimal_width(max_change) : number_width;
  2444. if (options->stat_graph_width == -1)
  2445. options->stat_graph_width = diff_stat_graph_width;
  2446. /*
  2447. * Guarantee 3/8*16==6 for the graph part
  2448. * and 5/8*16==10 for the filename part
  2449. */
  2450. if (width < 16 + 6 + number_width)
  2451. width = 16 + 6 + number_width;
  2452. /*
  2453. * First assign sizes that are wanted, ignoring available width.
  2454. * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
  2455. * starting from "XXX" should fit in graph_width.
  2456. */
  2457. graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
  2458. if (options->stat_graph_width &&
  2459. options->stat_graph_width < graph_width)
  2460. graph_width = options->stat_graph_width;
  2461. name_width = (options->stat_name_width > 0 &&
  2462. options->stat_name_width < max_len) ?
  2463. options->stat_name_width : max_len;
  2464. /*
  2465. * Adjust adjustable widths not to exceed maximum width
  2466. */
  2467. if (name_width + number_width + 6 + graph_width > width) {
  2468. if (graph_width > width * 3/8 - number_width - 6) {
  2469. graph_width = width * 3/8 - number_width - 6;
  2470. if (graph_width < 6)
  2471. graph_width = 6;
  2472. }
  2473. if (options->stat_graph_width &&
  2474. graph_width > options->stat_graph_width)
  2475. graph_width = options->stat_graph_width;
  2476. if (name_width > width - number_width - 6 - graph_width)
  2477. name_width = width - number_width - 6 - graph_width;
  2478. else
  2479. graph_width = width - number_width - 6 - name_width;
  2480. }
  2481. /*
  2482. * From here name_width is the width of the name area,
  2483. * and graph_width is the width of the graph area.
  2484. * max_change is used to scale graph properly.
  2485. */
  2486. for (i = 0; i < count; i++) {
  2487. const char *prefix = "";
  2488. struct diffstat_file *file = data->files[i];
  2489. char *name = file->print_name;
  2490. uintmax_t added = file->added;
  2491. uintmax_t deleted = file->deleted;
  2492. int name_len;
  2493. if (!file->is_interesting && (added + deleted == 0))
  2494. continue;
  2495. /*
  2496. * "scale" the filename
  2497. */
  2498. len = name_width;
  2499. name_len = strlen(name);
  2500. if (name_width < name_len) {
  2501. char *slash;
  2502. prefix = "...";
  2503. len -= 3;
  2504. name += name_len - len;
  2505. slash = strchr(name, '/');
  2506. if (slash)
  2507. name = slash;
  2508. }
  2509. if (file->is_binary) {
  2510. strbuf_addf(&out, " %s%-*s |", prefix, len, name);
  2511. strbuf_addf(&out, " %*s", number_width, "Bin");
  2512. if (!added && !deleted) {
  2513. strbuf_addch(&out, '\n');
  2514. emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
  2515. out.buf, out.len, 0);
  2516. strbuf_reset(&out);
  2517. continue;
  2518. }
  2519. strbuf_addf(&out, " %s%"PRIuMAX"%s",
  2520. del_c, deleted, reset);
  2521. strbuf_addstr(&out, " -> ");
  2522. strbuf_addf(&out, "%s%"PRIuMAX"%s",
  2523. add_c, added, reset);
  2524. strbuf_addstr(&out, " bytes\n");
  2525. emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
  2526. out.buf, out.len, 0);
  2527. strbuf_reset(&out);
  2528. continue;
  2529. }
  2530. else if (file->is_unmerged) {
  2531. strbuf_addf(&out, " %s%-*s |", prefix, len, name);
  2532. strbuf_addstr(&out, " Unmerged\n");
  2533. emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
  2534. out.buf, out.len, 0);
  2535. strbuf_reset(&out);
  2536. continue;
  2537. }
  2538. /*
  2539. * scale the add/delete
  2540. */
  2541. add = added;
  2542. del = deleted;
  2543. if (graph_width <= max_change) {
  2544. int total = scale_linear(add + del, graph_width, max_change);
  2545. if (total < 2 && add && del)
  2546. /* width >= 2 due to the sanity check */
  2547. total = 2;
  2548. if (add < del) {
  2549. add = scale_linear(add, graph_width, max_change);
  2550. del = total - add;
  2551. } else {
  2552. del = scale_linear(del, graph_width, max_change);
  2553. add = total - del;
  2554. }
  2555. }
  2556. strbuf_addf(&out, " %s%-*s |", prefix, len, name);
  2557. strbuf_addf(&out, " %*"PRIuMAX"%s",
  2558. number_width, added + deleted,
  2559. added + deleted ? " " : "");
  2560. show_graph(&out, '+', add, add_c, reset);
  2561. show_graph(&out, '-', del, del_c, reset);
  2562. strbuf_addch(&out, '\n');
  2563. emit_diff_symbol(options, DIFF_SYMBOL_STATS_LINE,
  2564. out.buf, out.len, 0);
  2565. strbuf_reset(&out);
  2566. }
  2567. for (i = 0; i < data->nr; i++) {
  2568. struct diffstat_file *file = data->files[i];
  2569. uintmax_t added = file->added;
  2570. uintmax_t deleted = file->deleted;
  2571. if (file->is_unmerged ||
  2572. (!file->is_interesting && (added + deleted == 0))) {
  2573. total_files--;
  2574. continue;
  2575. }
  2576. if (!file->is_binary) {
  2577. adds += added;
  2578. dels += deleted;
  2579. }
  2580. if (i < count)
  2581. continue;
  2582. if (!extra_shown)
  2583. emit_diff_symbol(options,
  2584. DIFF_SYMBOL_STATS_SUMMARY_ABBREV,
  2585. NULL, 0, 0);
  2586. extra_shown = 1;
  2587. }
  2588. print_stat_summary_inserts_deletes(options, total_files, adds, dels);
  2589. strbuf_release(&out);
  2590. }
  2591. static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
  2592. {
  2593. int i, adds = 0, dels = 0, total_files = data->nr;
  2594. if (data->nr == 0)
  2595. return;
  2596. for (i = 0; i < data->nr; i++) {
  2597. int added = data->files[i]->added;
  2598. int deleted = data->files[i]->deleted;
  2599. if (data->files[i]->is_unmerged ||
  2600. (!data->files[i]->is_interesting && (added + deleted == 0))) {
  2601. total_files--;
  2602. } else if (!data->files[i]->is_binary) { /* don't count bytes */
  2603. adds += added;
  2604. dels += deleted;
  2605. }
  2606. }
  2607. print_stat_summary_inserts_deletes(options, total_files, adds, dels);
  2608. }
  2609. static void show_numstat(struct diffstat_t *data, struct diff_options *options)
  2610. {
  2611. int i;
  2612. if (data->nr == 0)
  2613. return;
  2614. for (i = 0; i < data->nr; i++) {
  2615. struct diffstat_file *file = data->files[i];
  2616. fprintf(options->file, "%s", diff_line_prefix(options));
  2617. if (file->is_binary)
  2618. fprintf(options->file, "-\t-\t");
  2619. else
  2620. fprintf(options->file,
  2621. "%"PRIuMAX"\t%"PRIuMAX"\t",
  2622. file->added, file->deleted);
  2623. if (options->line_termination) {
  2624. fill_print_name(file);
  2625. if (!file->is_renamed)
  2626. write_name_quoted(file->name, options->file,
  2627. options->line_termination);
  2628. else {
  2629. fputs(file->print_name, options->file);
  2630. putc(options->line_termination, options->file);
  2631. }
  2632. } else {
  2633. if (file->is_renamed) {
  2634. putc('\0', options->file);
  2635. write_name_quoted(file->from_name, options->file, '\0');
  2636. }
  2637. write_name_quoted(file->name, options->file, '\0');
  2638. }
  2639. }
  2640. }
  2641. struct dirstat_file {
  2642. const char *name;
  2643. unsigned long changed;
  2644. };
  2645. struct dirstat_dir {
  2646. struct dirstat_file *files;
  2647. int alloc, nr, permille, cumulative;
  2648. };
  2649. static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
  2650. unsigned long changed, const char *base, int baselen)
  2651. {
  2652. unsigned long sum_changes = 0;
  2653. unsigned int sources = 0;
  2654. const char *line_prefix = diff_line_prefix(opt);
  2655. while (dir->nr) {
  2656. struct dirstat_file *f = dir->files;
  2657. int namelen = strlen(f->name);
  2658. unsigned long changes;
  2659. char *slash;
  2660. if (namelen < baselen)
  2661. break;
  2662. if (memcmp(f->name, base, baselen))
  2663. break;
  2664. slash = strchr(f->name + baselen, '/');
  2665. if (slash) {
  2666. int newbaselen = slash + 1 - f->name;
  2667. changes = gather_dirstat(opt, dir, changed, f->name, newbaselen);
  2668. sources++;
  2669. } else {
  2670. changes = f->changed;
  2671. dir->files++;
  2672. dir->nr--;
  2673. sources += 2;
  2674. }
  2675. sum_changes += changes;
  2676. }
  2677. /*
  2678. * We don't report dirstat's for
  2679. * - the top level
  2680. * - or cases where everything came from a single directory
  2681. * under this directory (sources == 1).
  2682. */
  2683. if (baselen && sources != 1) {
  2684. if (sum_changes) {
  2685. int permille = sum_changes * 1000 / changed;
  2686. if (permille >= dir->permille) {
  2687. fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
  2688. permille / 10, permille % 10, baselen, base);
  2689. if (!dir->cumulative)
  2690. return 0;
  2691. }
  2692. }
  2693. }
  2694. return sum_changes;
  2695. }
  2696. static int dirstat_compare(const void *_a, const void *_b)
  2697. {
  2698. const struct dirstat_file *a = _a;
  2699. const struct dirstat_file *b = _b;
  2700. return strcmp(a->name, b->name);
  2701. }
  2702. static void show_dirstat(struct diff_options *options)
  2703. {
  2704. int i;
  2705. unsigned long changed;
  2706. struct dirstat_dir dir;
  2707. struct diff_queue_struct *q = &diff_queued_diff;
  2708. dir.files = NULL;
  2709. dir.alloc = 0;
  2710. dir.nr = 0;
  2711. dir.permille = options->dirstat_permille;
  2712. dir.cumulative = options->flags.dirstat_cumulative;
  2713. changed = 0;
  2714. for (i = 0; i < q->nr; i++) {
  2715. struct diff_filepair *p = q->queue[i];
  2716. const char *name;
  2717. unsigned long copied, added, damage;
  2718. name = p->two->path ? p->two->path : p->one->path;
  2719. if (p->one->oid_valid && p->two->oid_valid &&
  2720. oideq(&p->one->oid, &p->two->oid)) {
  2721. /*
  2722. * The SHA1 has not changed, so pre-/post-content is
  2723. * identical. We can therefore skip looking at the
  2724. * file contents altogether.
  2725. */
  2726. damage = 0;
  2727. goto found_damage;
  2728. }
  2729. if (options->flags.dirstat_by_file) {
  2730. /*
  2731. * In --dirstat-by-file mode, we don't really need to
  2732. * look at the actual file contents at all.
  2733. * The fact that the SHA1 changed is enough for us to
  2734. * add this file to the list of results
  2735. * (with each file contributing equal damage).
  2736. */
  2737. damage = 1;
  2738. goto found_damage;
  2739. }
  2740. if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
  2741. diff_populate_filespec(options->repo, p->one, 0);
  2742. diff_populate_filespec(options->repo, p->two, 0);
  2743. diffcore_count_changes(options->repo,
  2744. p->one, p->two, NULL, NULL,
  2745. &copied, &added);
  2746. diff_free_filespec_data(p->one);
  2747. diff_free_filespec_data(p->two);
  2748. } else if (DIFF_FILE_VALID(p->one)) {
  2749. diff_populate_filespec(options->repo, p->one, CHECK_SIZE_ONLY);
  2750. copied = added = 0;
  2751. diff_free_filespec_data(p->one);
  2752. } else if (DIFF_FILE_VALID(p->two)) {
  2753. diff_populate_filespec(options->repo, p->two, CHECK_SIZE_ONLY);
  2754. copied = 0;
  2755. added = p->two->size;
  2756. diff_free_filespec_data(p->two);
  2757. } else
  2758. continue;
  2759. /*
  2760. * Original minus copied is the removed material,
  2761. * added is the new material. They are both damages
  2762. * made to the preimage.
  2763. * If the resulting damage is zero, we know that
  2764. * diffcore_count_changes() considers the two entries to
  2765. * be identical, but since the oid changed, we
  2766. * know that there must have been _some_ kind of change,
  2767. * so we force all entries to have damage > 0.
  2768. */
  2769. damage = (p->one->size - copied) + added;
  2770. if (!damage)
  2771. damage = 1;
  2772. found_damage:
  2773. ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
  2774. dir.files[dir.nr].name = name;
  2775. dir.files[dir.nr].changed = damage;
  2776. changed += damage;
  2777. dir.nr++;
  2778. }
  2779. /* This can happen even with many files, if everything was renames */
  2780. if (!changed)
  2781. return;
  2782. /* Show all directories with more than x% of the changes */
  2783. QSORT(dir.files, dir.nr, dirstat_compare);
  2784. gather_dirstat(options, &dir, changed, "", 0);
  2785. }
  2786. static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
  2787. {
  2788. int i;
  2789. unsigned long changed;
  2790. struct dirstat_dir dir;
  2791. if (data->nr == 0)
  2792. return;
  2793. dir.files = NULL;
  2794. dir.alloc = 0;
  2795. dir.nr = 0;
  2796. dir.permille = options->dirstat_permille;
  2797. dir.cumulative = options->flags.dirstat_cumulative;
  2798. changed = 0;
  2799. for (i = 0; i < data->nr; i++) {
  2800. struct diffstat_file *file = data->files[i];
  2801. unsigned long damage = file->added + file->deleted;
  2802. if (file->is_binary)
  2803. /*
  2804. * binary files counts bytes, not lines. Must find some
  2805. * way to normalize binary bytes vs. textual lines.
  2806. * The following heuristic assumes that there are 64
  2807. * bytes per "line".
  2808. * This is stupid and ugly, but very cheap...
  2809. */
  2810. damage = DIV_ROUND_UP(damage, 64);
  2811. ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
  2812. dir.files[dir.nr].name = file->name;
  2813. dir.files[dir.nr].changed = damage;
  2814. changed += damage;
  2815. dir.nr++;
  2816. }
  2817. /* This can happen even with many files, if everything was renames */
  2818. if (!changed)
  2819. return;
  2820. /* Show all directories with more than x% of the changes */
  2821. QSORT(dir.files, dir.nr, dirstat_compare);
  2822. gather_dirstat(options, &dir, changed, "", 0);
  2823. }
  2824. static void free_diffstat_info(struct diffstat_t *diffstat)
  2825. {
  2826. int i;
  2827. for (i = 0; i < diffstat->nr; i++) {
  2828. struct diffstat_file *f = diffstat->files[i];
  2829. free(f->print_name);
  2830. free(f->name);
  2831. free(f->from_name);
  2832. free(f);
  2833. }
  2834. free(diffstat->files);
  2835. }
  2836. struct checkdiff_t {
  2837. const char *filename;
  2838. int lineno;
  2839. int conflict_marker_size;
  2840. struct diff_options *o;
  2841. unsigned ws_rule;
  2842. unsigned status;
  2843. };
  2844. static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
  2845. {
  2846. char firstchar;
  2847. int cnt;
  2848. if (len < marker_size + 1)
  2849. return 0;
  2850. firstchar = line[0];
  2851. switch (firstchar) {
  2852. case '=': case '>': case '<': case '|':
  2853. break;
  2854. default:
  2855. return 0;
  2856. }
  2857. for (cnt = 1; cnt < marker_size; cnt++)
  2858. if (line[cnt] != firstchar)
  2859. return 0;
  2860. /* line[1] thru line[marker_size-1] are same as firstchar */
  2861. if (len < marker_size + 1 || !isspace(line[marker_size]))
  2862. return 0;
  2863. return 1;
  2864. }
  2865. static void checkdiff_consume_hunk(void *priv,
  2866. long ob, long on, long nb, long nn,
  2867. const char *func, long funclen)
  2868. {
  2869. struct checkdiff_t *data = priv;
  2870. data->lineno = nb - 1;
  2871. }
  2872. static void checkdiff_consume(void *priv, char *line, unsigned long len)
  2873. {
  2874. struct checkdiff_t *data = priv;
  2875. int marker_size = data->conflict_marker_size;
  2876. const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
  2877. const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
  2878. const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
  2879. char *err;
  2880. const char *line_prefix;
  2881. assert(data->o);
  2882. line_prefix = diff_line_prefix(data->o);
  2883. if (line[0] == '+') {
  2884. unsigned bad;
  2885. data->lineno++;
  2886. if (is_conflict_marker(line + 1, marker_size, len - 1)) {
  2887. data->status |= 1;
  2888. fprintf(data->o->file,
  2889. "%s%s:%d: leftover conflict marker\n",
  2890. line_prefix, data->filename, data->lineno);
  2891. }
  2892. bad = ws_check(line + 1, len - 1, data->ws_rule);
  2893. if (!bad)
  2894. return;
  2895. data->status |= bad;
  2896. err = whitespace_error_string(bad);
  2897. fprintf(data->o->file, "%s%s:%d: %s.\n",
  2898. line_prefix, data->filename, data->lineno, err);
  2899. free(err);
  2900. emit_line(data->o, set, reset, line, 1);
  2901. ws_check_emit(line + 1, len - 1, data->ws_rule,
  2902. data->o->file, set, reset, ws);
  2903. } else if (line[0] == ' ') {
  2904. data->lineno++;
  2905. }
  2906. }
  2907. static unsigned char *deflate_it(char *data,
  2908. unsigned long size,
  2909. unsigned long *result_size)
  2910. {
  2911. int bound;
  2912. unsigned char *deflated;
  2913. git_zstream stream;
  2914. git_deflate_init(&stream, zlib_compression_level);
  2915. bound = git_deflate_bound(&stream, size);
  2916. deflated = xmalloc(bound);
  2917. stream.next_out = deflated;
  2918. stream.avail_out = bound;
  2919. stream.next_in = (unsigned char *)data;
  2920. stream.avail_in = size;
  2921. while (git_deflate(&stream, Z_FINISH) == Z_OK)
  2922. ; /* nothing */
  2923. git_deflate_end(&stream);
  2924. *result_size = stream.total_out;
  2925. return deflated;
  2926. }
  2927. static void emit_binary_diff_body(struct diff_options *o,
  2928. mmfile_t *one, mmfile_t *two)
  2929. {
  2930. void *cp;
  2931. void *delta;
  2932. void *deflated;
  2933. void *data;
  2934. unsigned long orig_size;
  2935. unsigned long delta_size;
  2936. unsigned long deflate_size;
  2937. unsigned long data_size;
  2938. /* We could do deflated delta, or we could do just deflated two,
  2939. * whichever is smaller.
  2940. */
  2941. delta = NULL;
  2942. deflated = deflate_it(two->ptr, two->size, &deflate_size);
  2943. if (one->size && two->size) {
  2944. delta = diff_delta(one->ptr, one->size,
  2945. two->ptr, two->size,
  2946. &delta_size, deflate_size);
  2947. if (delta) {
  2948. void *to_free = delta;
  2949. orig_size = delta_size;
  2950. delta = deflate_it(delta, delta_size, &delta_size);
  2951. free(to_free);
  2952. }
  2953. }
  2954. if (delta && delta_size < deflate_size) {
  2955. char *s = xstrfmt("%"PRIuMAX , (uintmax_t)orig_size);
  2956. emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_DELTA,
  2957. s, strlen(s), 0);
  2958. free(s);
  2959. free(deflated);
  2960. data = delta;
  2961. data_size = delta_size;
  2962. } else {
  2963. char *s = xstrfmt("%lu", two->size);
  2964. emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER_LITERAL,
  2965. s, strlen(s), 0);
  2966. free(s);
  2967. free(delta);
  2968. data = deflated;
  2969. data_size = deflate_size;
  2970. }
  2971. /* emit data encoded in base85 */
  2972. cp = data;
  2973. while (data_size) {
  2974. int len;
  2975. int bytes = (52 < data_size) ? 52 : data_size;
  2976. char line[71];
  2977. data_size -= bytes;
  2978. if (bytes <= 26)
  2979. line[0] = bytes + 'A' - 1;
  2980. else
  2981. line[0] = bytes - 26 + 'a' - 1;
  2982. encode_85(line + 1, cp, bytes);
  2983. cp = (char *) cp + bytes;
  2984. len = strlen(line);
  2985. line[len++] = '\n';
  2986. line[len] = '\0';
  2987. emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_BODY,
  2988. line, len, 0);
  2989. }
  2990. emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_FOOTER, NULL, 0, 0);
  2991. free(data);
  2992. }
  2993. static void emit_binary_diff(struct diff_options *o,
  2994. mmfile_t *one, mmfile_t *two)
  2995. {
  2996. emit_diff_symbol(o, DIFF_SYMBOL_BINARY_DIFF_HEADER, NULL, 0, 0);
  2997. emit_binary_diff_body(o, one, two);
  2998. emit_binary_diff_body(o, two, one);
  2999. }
  3000. int diff_filespec_is_binary(struct repository *r,
  3001. struct diff_filespec *one)
  3002. {
  3003. if (one->is_binary == -1) {
  3004. diff_filespec_load_driver(one, r->index);
  3005. if (one->driver->binary != -1)
  3006. one->is_binary = one->driver->binary;
  3007. else {
  3008. if (!one->data && DIFF_FILE_VALID(one))
  3009. diff_populate_filespec(r, one, CHECK_BINARY);
  3010. if (one->is_binary == -1 && one->data)
  3011. one->is_binary = buffer_is_binary(one->data,
  3012. one->size);
  3013. if (one->is_binary == -1)
  3014. one->is_binary = 0;
  3015. }
  3016. }
  3017. return one->is_binary;
  3018. }
  3019. static const struct userdiff_funcname *
  3020. diff_funcname_pattern(struct diff_options *o, struct diff_filespec *one)
  3021. {
  3022. diff_filespec_load_driver(one, o->repo->index);
  3023. return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
  3024. }
  3025. void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
  3026. {
  3027. if (!options->a_prefix)
  3028. options->a_prefix = a;
  3029. if (!options->b_prefix)
  3030. options->b_prefix = b;
  3031. }
  3032. struct userdiff_driver *get_textconv(struct repository *r,
  3033. struct diff_filespec *one)
  3034. {
  3035. if (!DIFF_FILE_VALID(one))
  3036. return NULL;
  3037. diff_filespec_load_driver(one, r->index);
  3038. return userdiff_get_textconv(r, one->driver);
  3039. }
  3040. static void builtin_diff(const char *name_a,
  3041. const char *name_b,
  3042. struct diff_filespec *one,
  3043. struct diff_filespec *two,
  3044. const char *xfrm_msg,
  3045. int must_show_header,
  3046. struct diff_options *o,
  3047. int complete_rewrite)
  3048. {
  3049. mmfile_t mf1, mf2;
  3050. const char *lbl[2];
  3051. char *a_one, *b_two;
  3052. const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
  3053. const char *reset = diff_get_color_opt(o, DIFF_RESET);
  3054. const char *a_prefix, *b_prefix;
  3055. struct userdiff_driver *textconv_one = NULL;
  3056. struct userdiff_driver *textconv_two = NULL;
  3057. struct strbuf header = STRBUF_INIT;
  3058. const char *line_prefix = diff_line_prefix(o);
  3059. diff_set_mnemonic_prefix(o, "a/", "b/");
  3060. if (o->flags.reverse_diff) {
  3061. a_prefix = o->b_prefix;
  3062. b_prefix = o->a_prefix;
  3063. } else {
  3064. a_prefix = o->a_prefix;
  3065. b_prefix = o->b_prefix;
  3066. }
  3067. if (o->submodule_format == DIFF_SUBMODULE_LOG &&
  3068. (!one->mode || S_ISGITLINK(one->mode)) &&
  3069. (!two->mode || S_ISGITLINK(two->mode))) {
  3070. show_submodule_summary(o, one->path ? one->path : two->path,
  3071. &one->oid, &two->oid,
  3072. two->dirty_submodule);
  3073. return;
  3074. } else if (o->submodule_format == DIFF_SUBMODULE_INLINE_DIFF &&
  3075. (!one->mode || S_ISGITLINK(one->mode)) &&
  3076. (!two->mode || S_ISGITLINK(two->mode))) {
  3077. show_submodule_inline_diff(o, one->path ? one->path : two->path,
  3078. &one->oid, &two->oid,
  3079. two->dirty_submodule);
  3080. return;
  3081. }
  3082. if (o->flags.allow_textconv) {
  3083. textconv_one = get_textconv(o->repo, one);
  3084. textconv_two = get_textconv(o->repo, two);
  3085. }
  3086. /* Never use a non-valid filename anywhere if at all possible */
  3087. name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
  3088. name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
  3089. a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
  3090. b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
  3091. lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
  3092. lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
  3093. strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
  3094. if (lbl[0][0] == '/') {
  3095. /* /dev/null */
  3096. strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
  3097. if (xfrm_msg)
  3098. strbuf_addstr(&header, xfrm_msg);
  3099. must_show_header = 1;
  3100. }
  3101. else if (lbl[1][0] == '/') {
  3102. strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
  3103. if (xfrm_msg)
  3104. strbuf_addstr(&header, xfrm_msg);
  3105. must_show_header = 1;
  3106. }
  3107. else {
  3108. if (one->mode != two->mode) {
  3109. strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
  3110. strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
  3111. must_show_header = 1;
  3112. }
  3113. if (xfrm_msg)
  3114. strbuf_addstr(&header, xfrm_msg);
  3115. /*
  3116. * we do not run diff between different kind
  3117. * of objects.
  3118. */
  3119. if ((one->mode ^ two->mode) & S_IFMT)
  3120. goto free_ab_and_return;
  3121. if (complete_rewrite &&
  3122. (textconv_one || !diff_filespec_is_binary(o->repo, one)) &&
  3123. (textconv_two || !diff_filespec_is_binary(o->repo, two))) {
  3124. emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
  3125. header.buf, header.len, 0);
  3126. strbuf_reset(&header);
  3127. emit_rewrite_diff(name_a, name_b, one, two,
  3128. textconv_one, textconv_two, o);
  3129. o->found_changes = 1;
  3130. goto free_ab_and_return;
  3131. }
  3132. }
  3133. if (o->irreversible_delete && lbl[1][0] == '/') {
  3134. emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf,
  3135. header.len, 0);
  3136. strbuf_reset(&header);
  3137. goto free_ab_and_return;
  3138. } else if (!o->flags.text &&
  3139. ( (!textconv_one && diff_filespec_is_binary(o->repo, one)) ||
  3140. (!textconv_two && diff_filespec_is_binary(o->repo, two)) )) {
  3141. struct strbuf sb = STRBUF_INIT;
  3142. if (!one->data && !two->data &&
  3143. S_ISREG(one->mode) && S_ISREG(two->mode) &&
  3144. !o->flags.binary) {
  3145. if (oideq(&one->oid, &two->oid)) {
  3146. if (must_show_header)
  3147. emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
  3148. header.buf, header.len,
  3149. 0);
  3150. goto free_ab_and_return;
  3151. }
  3152. emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
  3153. header.buf, header.len, 0);
  3154. strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
  3155. diff_line_prefix(o), lbl[0], lbl[1]);
  3156. emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
  3157. sb.buf, sb.len, 0);
  3158. strbuf_release(&sb);
  3159. goto free_ab_and_return;
  3160. }
  3161. if (fill_mmfile(o->repo, &mf1, one) < 0 ||
  3162. fill_mmfile(o->repo, &mf2, two) < 0)
  3163. die("unable to read files to diff");
  3164. /* Quite common confusing case */
  3165. if (mf1.size == mf2.size &&
  3166. !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
  3167. if (must_show_header)
  3168. emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
  3169. header.buf, header.len, 0);
  3170. goto free_ab_and_return;
  3171. }
  3172. emit_diff_symbol(o, DIFF_SYMBOL_HEADER, header.buf, header.len, 0);
  3173. strbuf_reset(&header);
  3174. if (o->flags.binary)
  3175. emit_binary_diff(o, &mf1, &mf2);
  3176. else {
  3177. strbuf_addf(&sb, "%sBinary files %s and %s differ\n",
  3178. diff_line_prefix(o), lbl[0], lbl[1]);
  3179. emit_diff_symbol(o, DIFF_SYMBOL_BINARY_FILES,
  3180. sb.buf, sb.len, 0);
  3181. strbuf_release(&sb);
  3182. }
  3183. o->found_changes = 1;
  3184. } else {
  3185. /* Crazy xdl interfaces.. */
  3186. const char *diffopts;
  3187. const char *v;
  3188. xpparam_t xpp;
  3189. xdemitconf_t xecfg;
  3190. struct emit_callback ecbdata;
  3191. const struct userdiff_funcname *pe;
  3192. if (must_show_header) {
  3193. emit_diff_symbol(o, DIFF_SYMBOL_HEADER,
  3194. header.buf, header.len, 0);
  3195. strbuf_reset(&header);
  3196. }
  3197. mf1.size = fill_textconv(o->repo, textconv_one, one, &mf1.ptr);
  3198. mf2.size = fill_textconv(o->repo, textconv_two, two, &mf2.ptr);
  3199. pe = diff_funcname_pattern(o, one);
  3200. if (!pe)
  3201. pe = diff_funcname_pattern(o, two);
  3202. memset(&xpp, 0, sizeof(xpp));
  3203. memset(&xecfg, 0, sizeof(xecfg));
  3204. memset(&ecbdata, 0, sizeof(ecbdata));
  3205. if (o->flags.suppress_diff_headers)
  3206. lbl[0] = NULL;
  3207. ecbdata.label_path = lbl;
  3208. ecbdata.color_diff = want_color(o->use_color);
  3209. ecbdata.ws_rule = whitespace_rule(o->repo->index, name_b);
  3210. if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
  3211. check_blank_at_eof(&mf1, &mf2, &ecbdata);
  3212. ecbdata.opt = o;
  3213. if (header.len && !o->flags.suppress_diff_headers)
  3214. ecbdata.header = &header;
  3215. xpp.flags = o->xdl_opts;
  3216. xpp.anchors = o->anchors;
  3217. xpp.anchors_nr = o->anchors_nr;
  3218. xecfg.ctxlen = o->context;
  3219. xecfg.interhunkctxlen = o->interhunkcontext;
  3220. xecfg.flags = XDL_EMIT_FUNCNAMES;
  3221. if (o->flags.funccontext)
  3222. xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
  3223. if (pe)
  3224. xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
  3225. diffopts = getenv("GIT_DIFF_OPTS");
  3226. if (!diffopts)
  3227. ;
  3228. else if (skip_prefix(diffopts, "--unified=", &v))
  3229. xecfg.ctxlen = strtoul(v, NULL, 10);
  3230. else if (skip_prefix(diffopts, "-u", &v))
  3231. xecfg.ctxlen = strtoul(v, NULL, 10);
  3232. if (o->word_diff)
  3233. init_diff_words_data(&ecbdata, o, one, two);
  3234. if (xdi_diff_outf(&mf1, &mf2, NULL, fn_out_consume,
  3235. &ecbdata, &xpp, &xecfg))
  3236. die("unable to generate diff for %s", one->path);
  3237. if (o->word_diff)
  3238. free_diff_words_data(&ecbdata);
  3239. if (textconv_one)
  3240. free(mf1.ptr);
  3241. if (textconv_two)
  3242. free(mf2.ptr);
  3243. xdiff_clear_find_func(&xecfg);
  3244. }
  3245. free_ab_and_return:
  3246. strbuf_release(&header);
  3247. diff_free_filespec_data(one);
  3248. diff_free_filespec_data(two);
  3249. free(a_one);
  3250. free(b_two);
  3251. return;
  3252. }
  3253. static char *get_compact_summary(const struct diff_filepair *p, int is_renamed)
  3254. {
  3255. if (!is_renamed) {
  3256. if (p->status == DIFF_STATUS_ADDED) {
  3257. if (S_ISLNK(p->two->mode))
  3258. return "new +l";
  3259. else if ((p->two->mode & 0777) == 0755)
  3260. return "new +x";
  3261. else
  3262. return "new";
  3263. } else if (p->status == DIFF_STATUS_DELETED)
  3264. return "gone";
  3265. }
  3266. if (S_ISLNK(p->one->mode) && !S_ISLNK(p->two->mode))
  3267. return "mode -l";
  3268. else if (!S_ISLNK(p->one->mode) && S_ISLNK(p->two->mode))
  3269. return "mode +l";
  3270. else if ((p->one->mode & 0777) == 0644 &&
  3271. (p->two->mode & 0777) == 0755)
  3272. return "mode +x";
  3273. else if ((p->one->mode & 0777) == 0755 &&
  3274. (p->two->mode & 0777) == 0644)
  3275. return "mode -x";
  3276. return NULL;
  3277. }
  3278. static void builtin_diffstat(const char *name_a, const char *name_b,
  3279. struct diff_filespec *one,
  3280. struct diff_filespec *two,
  3281. struct diffstat_t *diffstat,
  3282. struct diff_options *o,
  3283. struct diff_filepair *p)
  3284. {
  3285. mmfile_t mf1, mf2;
  3286. struct diffstat_file *data;
  3287. int same_contents;
  3288. int complete_rewrite = 0;
  3289. if (!DIFF_PAIR_UNMERGED(p)) {
  3290. if (p->status == DIFF_STATUS_MODIFIED && p->score)
  3291. complete_rewrite = 1;
  3292. }
  3293. data = diffstat_add(diffstat, name_a, name_b);
  3294. data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
  3295. if (o->flags.stat_with_summary)
  3296. data->comments = get_compact_summary(p, data->is_renamed);
  3297. if (!one || !two) {
  3298. data->is_unmerged = 1;
  3299. return;
  3300. }
  3301. same_contents = oideq(&one->oid, &two->oid);
  3302. if (diff_filespec_is_binary(o->repo, one) ||
  3303. diff_filespec_is_binary(o->repo, two)) {
  3304. data->is_binary = 1;
  3305. if (same_contents) {
  3306. data->added = 0;
  3307. data->deleted = 0;
  3308. } else {
  3309. data->added = diff_filespec_size(o->repo, two);
  3310. data->deleted = diff_filespec_size(o->repo, one);
  3311. }
  3312. }
  3313. else if (complete_rewrite) {
  3314. diff_populate_filespec(o->repo, one, 0);
  3315. diff_populate_filespec(o->repo, two, 0);
  3316. data->deleted = count_lines(one->data, one->size);
  3317. data->added = count_lines(two->data, two->size);
  3318. }
  3319. else if (!same_contents) {
  3320. /* Crazy xdl interfaces.. */
  3321. xpparam_t xpp;
  3322. xdemitconf_t xecfg;
  3323. if (fill_mmfile(o->repo, &mf1, one) < 0 ||
  3324. fill_mmfile(o->repo, &mf2, two) < 0)
  3325. die("unable to read files to diff");
  3326. memset(&xpp, 0, sizeof(xpp));
  3327. memset(&xecfg, 0, sizeof(xecfg));
  3328. xpp.flags = o->xdl_opts;
  3329. xpp.anchors = o->anchors;
  3330. xpp.anchors_nr = o->anchors_nr;
  3331. xecfg.ctxlen = o->context;
  3332. xecfg.interhunkctxlen = o->interhunkcontext;
  3333. if (xdi_diff_outf(&mf1, &mf2, discard_hunk_line,
  3334. diffstat_consume, diffstat, &xpp, &xecfg))
  3335. die("unable to generate diffstat for %s", one->path);
  3336. }
  3337. diff_free_filespec_data(one);
  3338. diff_free_filespec_data(two);
  3339. }
  3340. static void builtin_checkdiff(const char *name_a, const char *name_b,
  3341. const char *attr_path,
  3342. struct diff_filespec *one,
  3343. struct diff_filespec *two,
  3344. struct diff_options *o)
  3345. {
  3346. mmfile_t mf1, mf2;
  3347. struct checkdiff_t data;
  3348. if (!two)
  3349. return;
  3350. memset(&data, 0, sizeof(data));
  3351. data.filename = name_b ? name_b : name_a;
  3352. data.lineno = 0;
  3353. data.o = o;
  3354. data.ws_rule = whitespace_rule(o->repo->index, attr_path);
  3355. data.conflict_marker_size = ll_merge_marker_size(o->repo->index, attr_path);
  3356. if (fill_mmfile(o->repo, &mf1, one) < 0 ||
  3357. fill_mmfile(o->repo, &mf2, two) < 0)
  3358. die("unable to read files to diff");
  3359. /*
  3360. * All the other codepaths check both sides, but not checking
  3361. * the "old" side here is deliberate. We are checking the newly
  3362. * introduced changes, and as long as the "new" side is text, we
  3363. * can and should check what it introduces.
  3364. */
  3365. if (diff_filespec_is_binary(o->repo, two))
  3366. goto free_and_return;
  3367. else {
  3368. /* Crazy xdl interfaces.. */
  3369. xpparam_t xpp;
  3370. xdemitconf_t xecfg;
  3371. memset(&xpp, 0, sizeof(xpp));
  3372. memset(&xecfg, 0, sizeof(xecfg));
  3373. xecfg.ctxlen = 1; /* at least one context line */
  3374. xpp.flags = 0;
  3375. if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume_hunk,
  3376. checkdiff_consume, &data,
  3377. &xpp, &xecfg))
  3378. die("unable to generate checkdiff for %s", one->path);
  3379. if (data.ws_rule & WS_BLANK_AT_EOF) {
  3380. struct emit_callback ecbdata;
  3381. int blank_at_eof;
  3382. ecbdata.ws_rule = data.ws_rule;
  3383. check_blank_at_eof(&mf1, &mf2, &ecbdata);
  3384. blank_at_eof = ecbdata.blank_at_eof_in_postimage;
  3385. if (blank_at_eof) {
  3386. static char *err;
  3387. if (!err)
  3388. err = whitespace_error_string(WS_BLANK_AT_EOF);
  3389. fprintf(o->file, "%s:%d: %s.\n",
  3390. data.filename, blank_at_eof, err);
  3391. data.status = 1; /* report errors */
  3392. }
  3393. }
  3394. }
  3395. free_and_return:
  3396. diff_free_filespec_data(one);
  3397. diff_free_filespec_data(two);
  3398. if (data.status)
  3399. o->flags.check_failed = 1;
  3400. }
  3401. struct diff_filespec *alloc_filespec(const char *path)
  3402. {
  3403. struct diff_filespec *spec;
  3404. FLEXPTR_ALLOC_STR(spec, path, path);
  3405. spec->count = 1;
  3406. spec->is_binary = -1;
  3407. return spec;
  3408. }
  3409. void free_filespec(struct diff_filespec *spec)
  3410. {
  3411. if (!--spec->count) {
  3412. diff_free_filespec_data(spec);
  3413. free(spec);
  3414. }
  3415. }
  3416. void fill_filespec(struct diff_filespec *spec, const struct object_id *oid,
  3417. int oid_valid, unsigned short mode)
  3418. {
  3419. if (mode) {
  3420. spec->mode = canon_mode(mode);
  3421. oidcpy(&spec->oid, oid);
  3422. spec->oid_valid = oid_valid;
  3423. }
  3424. }
  3425. /*
  3426. * Given a name and sha1 pair, if the index tells us the file in
  3427. * the work tree has that object contents, return true, so that
  3428. * prepare_temp_file() does not have to inflate and extract.
  3429. */
  3430. static int reuse_worktree_file(struct index_state *istate,
  3431. const char *name,
  3432. const struct object_id *oid,
  3433. int want_file)
  3434. {
  3435. const struct cache_entry *ce;
  3436. struct stat st;
  3437. int pos, len;
  3438. /*
  3439. * We do not read the cache ourselves here, because the
  3440. * benchmark with my previous version that always reads cache
  3441. * shows that it makes things worse for diff-tree comparing
  3442. * two linux-2.6 kernel trees in an already checked out work
  3443. * tree. This is because most diff-tree comparisons deal with
  3444. * only a small number of files, while reading the cache is
  3445. * expensive for a large project, and its cost outweighs the
  3446. * savings we get by not inflating the object to a temporary
  3447. * file. Practically, this code only helps when we are used
  3448. * by diff-cache --cached, which does read the cache before
  3449. * calling us.
  3450. */
  3451. if (!istate->cache)
  3452. return 0;
  3453. /* We want to avoid the working directory if our caller
  3454. * doesn't need the data in a normal file, this system
  3455. * is rather slow with its stat/open/mmap/close syscalls,
  3456. * and the object is contained in a pack file. The pack
  3457. * is probably already open and will be faster to obtain
  3458. * the data through than the working directory. Loose
  3459. * objects however would tend to be slower as they need
  3460. * to be individually opened and inflated.
  3461. */
  3462. if (!FAST_WORKING_DIRECTORY && !want_file && has_object_pack(oid))
  3463. return 0;
  3464. /*
  3465. * Similarly, if we'd have to convert the file contents anyway, that
  3466. * makes the optimization not worthwhile.
  3467. */
  3468. if (!want_file && would_convert_to_git(istate, name))
  3469. return 0;
  3470. len = strlen(name);
  3471. pos = index_name_pos(istate, name, len);
  3472. if (pos < 0)
  3473. return 0;
  3474. ce = istate->cache[pos];
  3475. /*
  3476. * This is not the sha1 we are looking for, or
  3477. * unreusable because it is not a regular file.
  3478. */
  3479. if (!oideq(oid, &ce->oid) || !S_ISREG(ce->ce_mode))
  3480. return 0;
  3481. /*
  3482. * If ce is marked as "assume unchanged", there is no
  3483. * guarantee that work tree matches what we are looking for.
  3484. */
  3485. if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
  3486. return 0;
  3487. /*
  3488. * If ce matches the file in the work tree, we can reuse it.
  3489. */
  3490. if (ce_uptodate(ce) ||
  3491. (!lstat(name, &st) && !ie_match_stat(istate, ce, &st, 0)))
  3492. return 1;
  3493. return 0;
  3494. }
  3495. static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
  3496. {
  3497. struct strbuf buf = STRBUF_INIT;
  3498. char *dirty = "";
  3499. /* Are we looking at the work tree? */
  3500. if (s->dirty_submodule)
  3501. dirty = "-dirty";
  3502. strbuf_addf(&buf, "Subproject commit %s%s\n",
  3503. oid_to_hex(&s->oid), dirty);
  3504. s->size = buf.len;
  3505. if (size_only) {
  3506. s->data = NULL;
  3507. strbuf_release(&buf);
  3508. } else {
  3509. s->data = strbuf_detach(&buf, NULL);
  3510. s->should_free = 1;
  3511. }
  3512. return 0;
  3513. }
  3514. /*
  3515. * While doing rename detection and pickaxe operation, we may need to
  3516. * grab the data for the blob (or file) for our own in-core comparison.
  3517. * diff_filespec has data and size fields for this purpose.
  3518. */
  3519. int diff_populate_filespec(struct repository *r,
  3520. struct diff_filespec *s,
  3521. unsigned int flags)
  3522. {
  3523. int size_only = flags & CHECK_SIZE_ONLY;
  3524. int err = 0;
  3525. int conv_flags = global_conv_flags_eol;
  3526. /*
  3527. * demote FAIL to WARN to allow inspecting the situation
  3528. * instead of refusing.
  3529. */
  3530. if (conv_flags & CONV_EOL_RNDTRP_DIE)
  3531. conv_flags = CONV_EOL_RNDTRP_WARN;
  3532. if (!DIFF_FILE_VALID(s))
  3533. die("internal error: asking to populate invalid file.");
  3534. if (S_ISDIR(s->mode))
  3535. return -1;
  3536. if (s->data)
  3537. return 0;
  3538. if (size_only && 0 < s->size)
  3539. return 0;
  3540. if (S_ISGITLINK(s->mode))
  3541. return diff_populate_gitlink(s, size_only);
  3542. if (!s->oid_valid ||
  3543. reuse_worktree_file(r->index, s->path, &s->oid, 0)) {
  3544. struct strbuf buf = STRBUF_INIT;
  3545. struct stat st;
  3546. int fd;
  3547. if (lstat(s->path, &st) < 0) {
  3548. err_empty:
  3549. err = -1;
  3550. empty:
  3551. s->data = (char *)"";
  3552. s->size = 0;
  3553. return err;
  3554. }
  3555. s->size = xsize_t(st.st_size);
  3556. if (!s->size)
  3557. goto empty;
  3558. if (S_ISLNK(st.st_mode)) {
  3559. struct strbuf sb = STRBUF_INIT;
  3560. if (strbuf_readlink(&sb, s->path, s->size))
  3561. goto err_empty;
  3562. s->size = sb.len;
  3563. s->data = strbuf_detach(&sb, NULL);
  3564. s->should_free = 1;
  3565. return 0;
  3566. }
  3567. /*
  3568. * Even if the caller would be happy with getting
  3569. * only the size, we cannot return early at this
  3570. * point if the path requires us to run the content
  3571. * conversion.
  3572. */
  3573. if (size_only && !would_convert_to_git(r->index, s->path))
  3574. return 0;
  3575. /*
  3576. * Note: this check uses xsize_t(st.st_size) that may
  3577. * not be the true size of the blob after it goes
  3578. * through convert_to_git(). This may not strictly be
  3579. * correct, but the whole point of big_file_threshold
  3580. * and is_binary check being that we want to avoid
  3581. * opening the file and inspecting the contents, this
  3582. * is probably fine.
  3583. */
  3584. if ((flags & CHECK_BINARY) &&
  3585. s->size > big_file_threshold && s->is_binary == -1) {
  3586. s->is_binary = 1;
  3587. return 0;
  3588. }
  3589. fd = open(s->path, O_RDONLY);
  3590. if (fd < 0)
  3591. goto err_empty;
  3592. s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
  3593. close(fd);
  3594. s->should_munmap = 1;
  3595. /*
  3596. * Convert from working tree format to canonical git format
  3597. */
  3598. if (convert_to_git(r->index, s->path, s->data, s->size, &buf, conv_flags)) {
  3599. size_t size = 0;
  3600. munmap(s->data, s->size);
  3601. s->should_munmap = 0;
  3602. s->data = strbuf_detach(&buf, &size);
  3603. s->size = size;
  3604. s->should_free = 1;
  3605. }
  3606. }
  3607. else {
  3608. enum object_type type;
  3609. if (size_only || (flags & CHECK_BINARY)) {
  3610. type = oid_object_info(r, &s->oid, &s->size);
  3611. if (type < 0)
  3612. die("unable to read %s",
  3613. oid_to_hex(&s->oid));
  3614. if (size_only)
  3615. return 0;
  3616. if (s->size > big_file_threshold && s->is_binary == -1) {
  3617. s->is_binary = 1;
  3618. return 0;
  3619. }
  3620. }
  3621. s->data = read_object_file(&s->oid, &type, &s->size);
  3622. if (!s->data)
  3623. die("unable to read %s", oid_to_hex(&s->oid));
  3624. s->should_free = 1;
  3625. }
  3626. return 0;
  3627. }
  3628. void diff_free_filespec_blob(struct diff_filespec *s)
  3629. {
  3630. if (s->should_free)
  3631. free(s->data);
  3632. else if (s->should_munmap)
  3633. munmap(s->data, s->size);
  3634. if (s->should_free || s->should_munmap) {
  3635. s->should_free = s->should_munmap = 0;
  3636. s->data = NULL;
  3637. }
  3638. }
  3639. void diff_free_filespec_data(struct diff_filespec *s)
  3640. {
  3641. diff_free_filespec_blob(s);
  3642. FREE_AND_NULL(s->cnt_data);
  3643. }
  3644. static void prep_temp_blob(struct index_state *istate,
  3645. const char *path, struct diff_tempfile *temp,
  3646. void *blob,
  3647. unsigned long size,
  3648. const struct object_id *oid,
  3649. int mode)
  3650. {
  3651. struct strbuf buf = STRBUF_INIT;
  3652. struct strbuf tempfile = STRBUF_INIT;
  3653. char *path_dup = xstrdup(path);
  3654. const char *base = basename(path_dup);
  3655. /* Generate "XXXXXX_basename.ext" */
  3656. strbuf_addstr(&tempfile, "XXXXXX_");
  3657. strbuf_addstr(&tempfile, base);
  3658. temp->tempfile = mks_tempfile_ts(tempfile.buf, strlen(base) + 1);
  3659. if (!temp->tempfile)
  3660. die_errno("unable to create temp-file");
  3661. if (convert_to_working_tree(istate, path,
  3662. (const char *)blob, (size_t)size, &buf)) {
  3663. blob = buf.buf;
  3664. size = buf.len;
  3665. }
  3666. if (write_in_full(temp->tempfile->fd, blob, size) < 0 ||
  3667. close_tempfile_gently(temp->tempfile))
  3668. die_errno("unable to write temp-file");
  3669. temp->name = get_tempfile_path(temp->tempfile);
  3670. oid_to_hex_r(temp->hex, oid);
  3671. xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
  3672. strbuf_release(&buf);
  3673. strbuf_release(&tempfile);
  3674. free(path_dup);
  3675. }
  3676. static struct diff_tempfile *prepare_temp_file(struct repository *r,
  3677. const char *name,
  3678. struct diff_filespec *one)
  3679. {
  3680. struct diff_tempfile *temp = claim_diff_tempfile();
  3681. if (!DIFF_FILE_VALID(one)) {
  3682. not_a_valid_file:
  3683. /* A '-' entry produces this for file-2, and
  3684. * a '+' entry produces this for file-1.
  3685. */
  3686. temp->name = "/dev/null";
  3687. xsnprintf(temp->hex, sizeof(temp->hex), ".");
  3688. xsnprintf(temp->mode, sizeof(temp->mode), ".");
  3689. return temp;
  3690. }
  3691. if (!S_ISGITLINK(one->mode) &&
  3692. (!one->oid_valid ||
  3693. reuse_worktree_file(r->index, name, &one->oid, 1))) {
  3694. struct stat st;
  3695. if (lstat(name, &st) < 0) {
  3696. if (errno == ENOENT)
  3697. goto not_a_valid_file;
  3698. die_errno("stat(%s)", name);
  3699. }
  3700. if (S_ISLNK(st.st_mode)) {
  3701. struct strbuf sb = STRBUF_INIT;
  3702. if (strbuf_readlink(&sb, name, st.st_size) < 0)
  3703. die_errno("readlink(%s)", name);
  3704. prep_temp_blob(r->index, name, temp, sb.buf, sb.len,
  3705. (one->oid_valid ?
  3706. &one->oid : &null_oid),
  3707. (one->oid_valid ?
  3708. one->mode : S_IFLNK));
  3709. strbuf_release(&sb);
  3710. }
  3711. else {
  3712. /* we can borrow from the file in the work tree */
  3713. temp->name = name;
  3714. if (!one->oid_valid)
  3715. oid_to_hex_r(temp->hex, &null_oid);
  3716. else
  3717. oid_to_hex_r(temp->hex, &one->oid);
  3718. /* Even though we may sometimes borrow the
  3719. * contents from the work tree, we always want
  3720. * one->mode. mode is trustworthy even when
  3721. * !(one->oid_valid), as long as
  3722. * DIFF_FILE_VALID(one).
  3723. */
  3724. xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
  3725. }
  3726. return temp;
  3727. }
  3728. else {
  3729. if (diff_populate_filespec(r, one, 0))
  3730. die("cannot read data blob for %s", one->path);
  3731. prep_temp_blob(r->index, name, temp,
  3732. one->data, one->size,
  3733. &one->oid, one->mode);
  3734. }
  3735. return temp;
  3736. }
  3737. static void add_external_diff_name(struct repository *r,
  3738. struct argv_array *argv,
  3739. const char *name,
  3740. struct diff_filespec *df)
  3741. {
  3742. struct diff_tempfile *temp = prepare_temp_file(r, name, df);
  3743. argv_array_push(argv, temp->name);
  3744. argv_array_push(argv, temp->hex);
  3745. argv_array_push(argv, temp->mode);
  3746. }
  3747. /* An external diff command takes:
  3748. *
  3749. * diff-cmd name infile1 infile1-sha1 infile1-mode \
  3750. * infile2 infile2-sha1 infile2-mode [ rename-to ]
  3751. *
  3752. */
  3753. static void run_external_diff(const char *pgm,
  3754. const char *name,
  3755. const char *other,
  3756. struct diff_filespec *one,
  3757. struct diff_filespec *two,
  3758. const char *xfrm_msg,
  3759. struct diff_options *o)
  3760. {
  3761. struct argv_array argv = ARGV_ARRAY_INIT;
  3762. struct argv_array env = ARGV_ARRAY_INIT;
  3763. struct diff_queue_struct *q = &diff_queued_diff;
  3764. argv_array_push(&argv, pgm);
  3765. argv_array_push(&argv, name);
  3766. if (one && two) {
  3767. add_external_diff_name(o->repo, &argv, name, one);
  3768. if (!other)
  3769. add_external_diff_name(o->repo, &argv, name, two);
  3770. else {
  3771. add_external_diff_name(o->repo, &argv, other, two);
  3772. argv_array_push(&argv, other);
  3773. argv_array_push(&argv, xfrm_msg);
  3774. }
  3775. }
  3776. argv_array_pushf(&env, "GIT_DIFF_PATH_COUNTER=%d", ++o->diff_path_counter);
  3777. argv_array_pushf(&env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
  3778. diff_free_filespec_data(one);
  3779. diff_free_filespec_data(two);
  3780. if (run_command_v_opt_cd_env(argv.argv, RUN_USING_SHELL, NULL, env.argv))
  3781. die(_("external diff died, stopping at %s"), name);
  3782. remove_tempfile();
  3783. argv_array_clear(&argv);
  3784. argv_array_clear(&env);
  3785. }
  3786. static int similarity_index(struct diff_filepair *p)
  3787. {
  3788. return p->score * 100 / MAX_SCORE;
  3789. }
  3790. static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
  3791. {
  3792. if (startup_info->have_repository)
  3793. return find_unique_abbrev(oid, abbrev);
  3794. else {
  3795. char *hex = oid_to_hex(oid);
  3796. if (abbrev < 0)
  3797. abbrev = FALLBACK_DEFAULT_ABBREV;
  3798. if (abbrev > the_hash_algo->hexsz)
  3799. BUG("oid abbreviation out of range: %d", abbrev);
  3800. if (abbrev)
  3801. hex[abbrev] = '\0';
  3802. return hex;
  3803. }
  3804. }
  3805. static void fill_metainfo(struct strbuf *msg,
  3806. const char *name,
  3807. const char *other,
  3808. struct diff_filespec *one,
  3809. struct diff_filespec *two,
  3810. struct diff_options *o,
  3811. struct diff_filepair *p,
  3812. int *must_show_header,
  3813. int use_color)
  3814. {
  3815. const char *set = diff_get_color(use_color, DIFF_METAINFO);
  3816. const char *reset = diff_get_color(use_color, DIFF_RESET);
  3817. const char *line_prefix = diff_line_prefix(o);
  3818. *must_show_header = 1;
  3819. strbuf_init(msg, PATH_MAX * 2 + 300);
  3820. switch (p->status) {
  3821. case DIFF_STATUS_COPIED:
  3822. strbuf_addf(msg, "%s%ssimilarity index %d%%",
  3823. line_prefix, set, similarity_index(p));
  3824. strbuf_addf(msg, "%s\n%s%scopy from ",
  3825. reset, line_prefix, set);
  3826. quote_c_style(name, msg, NULL, 0);
  3827. strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
  3828. quote_c_style(other, msg, NULL, 0);
  3829. strbuf_addf(msg, "%s\n", reset);
  3830. break;
  3831. case DIFF_STATUS_RENAMED:
  3832. strbuf_addf(msg, "%s%ssimilarity index %d%%",
  3833. line_prefix, set, similarity_index(p));
  3834. strbuf_addf(msg, "%s\n%s%srename from ",
  3835. reset, line_prefix, set);
  3836. quote_c_style(name, msg, NULL, 0);
  3837. strbuf_addf(msg, "%s\n%s%srename to ",
  3838. reset, line_prefix, set);
  3839. quote_c_style(other, msg, NULL, 0);
  3840. strbuf_addf(msg, "%s\n", reset);
  3841. break;
  3842. case DIFF_STATUS_MODIFIED:
  3843. if (p->score) {
  3844. strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
  3845. line_prefix,
  3846. set, similarity_index(p), reset);
  3847. break;
  3848. }
  3849. /* fallthru */
  3850. default:
  3851. *must_show_header = 0;
  3852. }
  3853. if (one && two && !oideq(&one->oid, &two->oid)) {
  3854. const unsigned hexsz = the_hash_algo->hexsz;
  3855. int abbrev = o->flags.full_index ? hexsz : DEFAULT_ABBREV;
  3856. if (o->flags.binary) {
  3857. mmfile_t mf;
  3858. if ((!fill_mmfile(o->repo, &mf, one) &&
  3859. diff_filespec_is_binary(o->repo, one)) ||
  3860. (!fill_mmfile(o->repo, &mf, two) &&
  3861. diff_filespec_is_binary(o->repo, two)))
  3862. abbrev = hexsz;
  3863. }
  3864. strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
  3865. diff_abbrev_oid(&one->oid, abbrev),
  3866. diff_abbrev_oid(&two->oid, abbrev));
  3867. if (one->mode == two->mode)
  3868. strbuf_addf(msg, " %06o", one->mode);
  3869. strbuf_addf(msg, "%s\n", reset);
  3870. }
  3871. }
  3872. static void run_diff_cmd(const char *pgm,
  3873. const char *name,
  3874. const char *other,
  3875. const char *attr_path,
  3876. struct diff_filespec *one,
  3877. struct diff_filespec *two,
  3878. struct strbuf *msg,
  3879. struct diff_options *o,
  3880. struct diff_filepair *p)
  3881. {
  3882. const char *xfrm_msg = NULL;
  3883. int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
  3884. int must_show_header = 0;
  3885. if (o->flags.allow_external) {
  3886. struct userdiff_driver *drv;
  3887. drv = userdiff_find_by_path(o->repo->index, attr_path);
  3888. if (drv && drv->external)
  3889. pgm = drv->external;
  3890. }
  3891. if (msg) {
  3892. /*
  3893. * don't use colors when the header is intended for an
  3894. * external diff driver
  3895. */
  3896. fill_metainfo(msg, name, other, one, two, o, p,
  3897. &must_show_header,
  3898. want_color(o->use_color) && !pgm);
  3899. xfrm_msg = msg->len ? msg->buf : NULL;
  3900. }
  3901. if (pgm) {
  3902. run_external_diff(pgm, name, other, one, two, xfrm_msg, o);
  3903. return;
  3904. }
  3905. if (one && two)
  3906. builtin_diff(name, other ? other : name,
  3907. one, two, xfrm_msg, must_show_header,
  3908. o, complete_rewrite);
  3909. else
  3910. fprintf(o->file, "* Unmerged path %s\n", name);
  3911. }
  3912. static void diff_fill_oid_info(struct diff_filespec *one, struct index_state *istate)
  3913. {
  3914. if (DIFF_FILE_VALID(one)) {
  3915. if (!one->oid_valid) {
  3916. struct stat st;
  3917. if (one->is_stdin) {
  3918. oidclr(&one->oid);
  3919. return;
  3920. }
  3921. if (lstat(one->path, &st) < 0)
  3922. die_errno("stat '%s'", one->path);
  3923. if (index_path(istate, &one->oid, one->path, &st, 0))
  3924. die("cannot hash %s", one->path);
  3925. }
  3926. }
  3927. else
  3928. oidclr(&one->oid);
  3929. }
  3930. static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
  3931. {
  3932. /* Strip the prefix but do not molest /dev/null and absolute paths */
  3933. if (*namep && !is_absolute_path(*namep)) {
  3934. *namep += prefix_length;
  3935. if (**namep == '/')
  3936. ++*namep;
  3937. }
  3938. if (*otherp && !is_absolute_path(*otherp)) {
  3939. *otherp += prefix_length;
  3940. if (**otherp == '/')
  3941. ++*otherp;
  3942. }
  3943. }
  3944. static void run_diff(struct diff_filepair *p, struct diff_options *o)
  3945. {
  3946. const char *pgm = external_diff();
  3947. struct strbuf msg;
  3948. struct diff_filespec *one = p->one;
  3949. struct diff_filespec *two = p->two;
  3950. const char *name;
  3951. const char *other;
  3952. const char *attr_path;
  3953. name = one->path;
  3954. other = (strcmp(name, two->path) ? two->path : NULL);
  3955. attr_path = name;
  3956. if (o->prefix_length)
  3957. strip_prefix(o->prefix_length, &name, &other);
  3958. if (!o->flags.allow_external)
  3959. pgm = NULL;
  3960. if (DIFF_PAIR_UNMERGED(p)) {
  3961. run_diff_cmd(pgm, name, NULL, attr_path,
  3962. NULL, NULL, NULL, o, p);
  3963. return;
  3964. }
  3965. diff_fill_oid_info(one, o->repo->index);
  3966. diff_fill_oid_info(two, o->repo->index);
  3967. if (!pgm &&
  3968. DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
  3969. (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
  3970. /*
  3971. * a filepair that changes between file and symlink
  3972. * needs to be split into deletion and creation.
  3973. */
  3974. struct diff_filespec *null = alloc_filespec(two->path);
  3975. run_diff_cmd(NULL, name, other, attr_path,
  3976. one, null, &msg,
  3977. o, p);
  3978. free(null);
  3979. strbuf_release(&msg);
  3980. null = alloc_filespec(one->path);
  3981. run_diff_cmd(NULL, name, other, attr_path,
  3982. null, two, &msg, o, p);
  3983. free(null);
  3984. }
  3985. else
  3986. run_diff_cmd(pgm, name, other, attr_path,
  3987. one, two, &msg, o, p);
  3988. strbuf_release(&msg);
  3989. }
  3990. static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
  3991. struct diffstat_t *diffstat)
  3992. {
  3993. const char *name;
  3994. const char *other;
  3995. if (DIFF_PAIR_UNMERGED(p)) {
  3996. /* unmerged */
  3997. builtin_diffstat(p->one->path, NULL, NULL, NULL,
  3998. diffstat, o, p);
  3999. return;
  4000. }
  4001. name = p->one->path;
  4002. other = (strcmp(name, p->two->path) ? p->two->path : NULL);
  4003. if (o->prefix_length)
  4004. strip_prefix(o->prefix_length, &name, &other);
  4005. diff_fill_oid_info(p->one, o->repo->index);
  4006. diff_fill_oid_info(p->two, o->repo->index);
  4007. builtin_diffstat(name, other, p->one, p->two,
  4008. diffstat, o, p);
  4009. }
  4010. static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
  4011. {
  4012. const char *name;
  4013. const char *other;
  4014. const char *attr_path;
  4015. if (DIFF_PAIR_UNMERGED(p)) {
  4016. /* unmerged */
  4017. return;
  4018. }
  4019. name = p->one->path;
  4020. other = (strcmp(name, p->two->path) ? p->two->path : NULL);
  4021. attr_path = other ? other : name;
  4022. if (o->prefix_length)
  4023. strip_prefix(o->prefix_length, &name, &other);
  4024. diff_fill_oid_info(p->one, o->repo->index);
  4025. diff_fill_oid_info(p->two, o->repo->index);
  4026. builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
  4027. }
  4028. static void prep_parse_options(struct diff_options *options);
  4029. void repo_diff_setup(struct repository *r, struct diff_options *options)
  4030. {
  4031. memcpy(options, &default_diff_options, sizeof(*options));
  4032. options->file = stdout;
  4033. options->repo = r;
  4034. options->output_indicators[OUTPUT_INDICATOR_NEW] = '+';
  4035. options->output_indicators[OUTPUT_INDICATOR_OLD] = '-';
  4036. options->output_indicators[OUTPUT_INDICATOR_CONTEXT] = ' ';
  4037. options->abbrev = DEFAULT_ABBREV;
  4038. options->line_termination = '\n';
  4039. options->break_opt = -1;
  4040. options->rename_limit = -1;
  4041. options->dirstat_permille = diff_dirstat_permille_default;
  4042. options->context = diff_context_default;
  4043. options->interhunkcontext = diff_interhunk_context_default;
  4044. options->ws_error_highlight = ws_error_highlight_default;
  4045. options->flags.rename_empty = 1;
  4046. options->objfind = NULL;
  4047. /* pathchange left =NULL by default */
  4048. options->change = diff_change;
  4049. options->add_remove = diff_addremove;
  4050. options->use_color = diff_use_color_default;
  4051. options->detect_rename = diff_detect_rename_default;
  4052. options->xdl_opts |= diff_algorithm;
  4053. if (diff_indent_heuristic)
  4054. DIFF_XDL_SET(options, INDENT_HEURISTIC);
  4055. options->orderfile = diff_order_file_cfg;
  4056. if (diff_no_prefix) {
  4057. options->a_prefix = options->b_prefix = "";
  4058. } else if (!diff_mnemonic_prefix) {
  4059. options->a_prefix = "a/";
  4060. options->b_prefix = "b/";
  4061. }
  4062. options->color_moved = diff_color_moved_default;
  4063. options->color_moved_ws_handling = diff_color_moved_ws_default;
  4064. prep_parse_options(options);
  4065. }
  4066. void diff_setup_done(struct diff_options *options)
  4067. {
  4068. unsigned check_mask = DIFF_FORMAT_NAME |
  4069. DIFF_FORMAT_NAME_STATUS |
  4070. DIFF_FORMAT_CHECKDIFF |
  4071. DIFF_FORMAT_NO_OUTPUT;
  4072. /*
  4073. * This must be signed because we're comparing against a potentially
  4074. * negative value.
  4075. */
  4076. const int hexsz = the_hash_algo->hexsz;
  4077. if (options->set_default)
  4078. options->set_default(options);
  4079. if (HAS_MULTI_BITS(options->output_format & check_mask))
  4080. die(_("--name-only, --name-status, --check and -s are mutually exclusive"));
  4081. if (HAS_MULTI_BITS(options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK))
  4082. die(_("-G, -S and --find-object are mutually exclusive"));
  4083. /*
  4084. * Most of the time we can say "there are changes"
  4085. * only by checking if there are changed paths, but
  4086. * --ignore-whitespace* options force us to look
  4087. * inside contents.
  4088. */
  4089. if ((options->xdl_opts & XDF_WHITESPACE_FLAGS))
  4090. options->flags.diff_from_contents = 1;
  4091. else
  4092. options->flags.diff_from_contents = 0;
  4093. if (options->flags.find_copies_harder)
  4094. options->detect_rename = DIFF_DETECT_COPY;
  4095. if (!options->flags.relative_name)
  4096. options->prefix = NULL;
  4097. if (options->prefix)
  4098. options->prefix_length = strlen(options->prefix);
  4099. else
  4100. options->prefix_length = 0;
  4101. if (options->output_format & (DIFF_FORMAT_NAME |
  4102. DIFF_FORMAT_NAME_STATUS |
  4103. DIFF_FORMAT_CHECKDIFF |
  4104. DIFF_FORMAT_NO_OUTPUT))
  4105. options->output_format &= ~(DIFF_FORMAT_RAW |
  4106. DIFF_FORMAT_NUMSTAT |
  4107. DIFF_FORMAT_DIFFSTAT |
  4108. DIFF_FORMAT_SHORTSTAT |
  4109. DIFF_FORMAT_DIRSTAT |
  4110. DIFF_FORMAT_SUMMARY |
  4111. DIFF_FORMAT_PATCH);
  4112. /*
  4113. * These cases always need recursive; we do not drop caller-supplied
  4114. * recursive bits for other formats here.
  4115. */
  4116. if (options->output_format & (DIFF_FORMAT_PATCH |
  4117. DIFF_FORMAT_NUMSTAT |
  4118. DIFF_FORMAT_DIFFSTAT |
  4119. DIFF_FORMAT_SHORTSTAT |
  4120. DIFF_FORMAT_DIRSTAT |
  4121. DIFF_FORMAT_SUMMARY |
  4122. DIFF_FORMAT_CHECKDIFF))
  4123. options->flags.recursive = 1;
  4124. /*
  4125. * Also pickaxe would not work very well if you do not say recursive
  4126. */
  4127. if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
  4128. options->flags.recursive = 1;
  4129. /*
  4130. * When patches are generated, submodules diffed against the work tree
  4131. * must be checked for dirtiness too so it can be shown in the output
  4132. */
  4133. if (options->output_format & DIFF_FORMAT_PATCH)
  4134. options->flags.dirty_submodules = 1;
  4135. if (options->detect_rename && options->rename_limit < 0)
  4136. options->rename_limit = diff_rename_limit_default;
  4137. if (hexsz < options->abbrev)
  4138. options->abbrev = hexsz; /* full */
  4139. /*
  4140. * It does not make sense to show the first hit we happened
  4141. * to have found. It does not make sense not to return with
  4142. * exit code in such a case either.
  4143. */
  4144. if (options->flags.quick) {
  4145. options->output_format = DIFF_FORMAT_NO_OUTPUT;
  4146. options->flags.exit_with_status = 1;
  4147. }
  4148. options->diff_path_counter = 0;
  4149. if (options->flags.follow_renames && options->pathspec.nr != 1)
  4150. die(_("--follow requires exactly one pathspec"));
  4151. if (!options->use_color || external_diff())
  4152. options->color_moved = 0;
  4153. FREE_AND_NULL(options->parseopts);
  4154. }
  4155. int parse_long_opt(const char *opt, const char **argv,
  4156. const char **optarg)
  4157. {
  4158. const char *arg = argv[0];
  4159. if (!skip_prefix(arg, "--", &arg))
  4160. return 0;
  4161. if (!skip_prefix(arg, opt, &arg))
  4162. return 0;
  4163. if (*arg == '=') { /* stuck form: --option=value */
  4164. *optarg = arg + 1;
  4165. return 1;
  4166. }
  4167. if (*arg != '\0')
  4168. return 0;
  4169. /* separate form: --option value */
  4170. if (!argv[1])
  4171. die("Option '--%s' requires a value", opt);
  4172. *optarg = argv[1];
  4173. return 2;
  4174. }
  4175. static int diff_opt_stat(const struct option *opt, const char *value, int unset)
  4176. {
  4177. struct diff_options *options = opt->value;
  4178. int width = options->stat_width;
  4179. int name_width = options->stat_name_width;
  4180. int graph_width = options->stat_graph_width;
  4181. int count = options->stat_count;
  4182. char *end;
  4183. BUG_ON_OPT_NEG(unset);
  4184. if (!strcmp(opt->long_name, "stat")) {
  4185. if (value) {
  4186. width = strtoul(value, &end, 10);
  4187. if (*end == ',')
  4188. name_width = strtoul(end+1, &end, 10);
  4189. if (*end == ',')
  4190. count = strtoul(end+1, &end, 10);
  4191. if (*end)
  4192. return error(_("invalid --stat value: %s"), value);
  4193. }
  4194. } else if (!strcmp(opt->long_name, "stat-width")) {
  4195. width = strtoul(value, &end, 10);
  4196. if (*end)
  4197. return error(_("%s expects a numerical value"),
  4198. opt->long_name);
  4199. } else if (!strcmp(opt->long_name, "stat-name-width")) {
  4200. name_width = strtoul(value, &end, 10);
  4201. if (*end)
  4202. return error(_("%s expects a numerical value"),
  4203. opt->long_name);
  4204. } else if (!strcmp(opt->long_name, "stat-graph-width")) {
  4205. graph_width = strtoul(value, &end, 10);
  4206. if (*end)
  4207. return error(_("%s expects a numerical value"),
  4208. opt->long_name);
  4209. } else if (!strcmp(opt->long_name, "stat-count")) {
  4210. count = strtoul(value, &end, 10);
  4211. if (*end)
  4212. return error(_("%s expects a numerical value"),
  4213. opt->long_name);
  4214. } else
  4215. BUG("%s should not get here", opt->long_name);
  4216. options->output_format |= DIFF_FORMAT_DIFFSTAT;
  4217. options->stat_name_width = name_width;
  4218. options->stat_graph_width = graph_width;
  4219. options->stat_width = width;
  4220. options->stat_count = count;
  4221. return 0;
  4222. }
  4223. static int parse_dirstat_opt(struct diff_options *options, const char *params)
  4224. {
  4225. struct strbuf errmsg = STRBUF_INIT;
  4226. if (parse_dirstat_params(options, params, &errmsg))
  4227. die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
  4228. errmsg.buf);
  4229. strbuf_release(&errmsg);
  4230. /*
  4231. * The caller knows a dirstat-related option is given from the command
  4232. * line; allow it to say "return this_function();"
  4233. */
  4234. options->output_format |= DIFF_FORMAT_DIRSTAT;
  4235. return 1;
  4236. }
  4237. static const char diff_status_letters[] = {
  4238. DIFF_STATUS_ADDED,
  4239. DIFF_STATUS_COPIED,
  4240. DIFF_STATUS_DELETED,
  4241. DIFF_STATUS_MODIFIED,
  4242. DIFF_STATUS_RENAMED,
  4243. DIFF_STATUS_TYPE_CHANGED,
  4244. DIFF_STATUS_UNKNOWN,
  4245. DIFF_STATUS_UNMERGED,
  4246. DIFF_STATUS_FILTER_AON,
  4247. DIFF_STATUS_FILTER_BROKEN,
  4248. '\0',
  4249. };
  4250. static unsigned int filter_bit['Z' + 1];
  4251. static void prepare_filter_bits(void)
  4252. {
  4253. int i;
  4254. if (!filter_bit[DIFF_STATUS_ADDED]) {
  4255. for (i = 0; diff_status_letters[i]; i++)
  4256. filter_bit[(int) diff_status_letters[i]] = (1 << i);
  4257. }
  4258. }
  4259. static unsigned filter_bit_tst(char status, const struct diff_options *opt)
  4260. {
  4261. return opt->filter & filter_bit[(int) status];
  4262. }
  4263. unsigned diff_filter_bit(char status)
  4264. {
  4265. prepare_filter_bits();
  4266. return filter_bit[(int) status];
  4267. }
  4268. static int diff_opt_diff_filter(const struct option *option,
  4269. const char *optarg, int unset)
  4270. {
  4271. struct diff_options *opt = option->value;
  4272. int i, optch;
  4273. BUG_ON_OPT_NEG(unset);
  4274. prepare_filter_bits();
  4275. /*
  4276. * If there is a negation e.g. 'd' in the input, and we haven't
  4277. * initialized the filter field with another --diff-filter, start
  4278. * from full set of bits, except for AON.
  4279. */
  4280. if (!opt->filter) {
  4281. for (i = 0; (optch = optarg[i]) != '\0'; i++) {
  4282. if (optch < 'a' || 'z' < optch)
  4283. continue;
  4284. opt->filter = (1 << (ARRAY_SIZE(diff_status_letters) - 1)) - 1;
  4285. opt->filter &= ~filter_bit[DIFF_STATUS_FILTER_AON];
  4286. break;
  4287. }
  4288. }
  4289. for (i = 0; (optch = optarg[i]) != '\0'; i++) {
  4290. unsigned int bit;
  4291. int negate;
  4292. if ('a' <= optch && optch <= 'z') {
  4293. negate = 1;
  4294. optch = toupper(optch);
  4295. } else {
  4296. negate = 0;
  4297. }
  4298. bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
  4299. if (!bit)
  4300. return error(_("unknown change class '%c' in --diff-filter=%s"),
  4301. optarg[i], optarg);
  4302. if (negate)
  4303. opt->filter &= ~bit;
  4304. else
  4305. opt->filter |= bit;
  4306. }
  4307. return 0;
  4308. }
  4309. static void enable_patch_output(int *fmt)
  4310. {
  4311. *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
  4312. *fmt |= DIFF_FORMAT_PATCH;
  4313. }
  4314. static int diff_opt_ws_error_highlight(const struct option *option,
  4315. const char *arg, int unset)
  4316. {
  4317. struct diff_options *opt = option->value;
  4318. int val = parse_ws_error_highlight(arg);
  4319. BUG_ON_OPT_NEG(unset);
  4320. if (val < 0)
  4321. return error(_("unknown value after ws-error-highlight=%.*s"),
  4322. -1 - val, arg);
  4323. opt->ws_error_highlight = val;
  4324. return 0;
  4325. }
  4326. static int diff_opt_find_object(const struct option *option,
  4327. const char *arg, int unset)
  4328. {
  4329. struct diff_options *opt = option->value;
  4330. struct object_id oid;
  4331. BUG_ON_OPT_NEG(unset);
  4332. if (get_oid(arg, &oid))
  4333. return error(_("unable to resolve '%s'"), arg);
  4334. if (!opt->objfind)
  4335. opt->objfind = xcalloc(1, sizeof(*opt->objfind));
  4336. opt->pickaxe_opts |= DIFF_PICKAXE_KIND_OBJFIND;
  4337. opt->flags.recursive = 1;
  4338. opt->flags.tree_in_recursive = 1;
  4339. oidset_insert(opt->objfind, &oid);
  4340. return 0;
  4341. }
  4342. static int diff_opt_anchored(const struct option *opt,
  4343. const char *arg, int unset)
  4344. {
  4345. struct diff_options *options = opt->value;
  4346. BUG_ON_OPT_NEG(unset);
  4347. options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
  4348. ALLOC_GROW(options->anchors, options->anchors_nr + 1,
  4349. options->anchors_alloc);
  4350. options->anchors[options->anchors_nr++] = xstrdup(arg);
  4351. return 0;
  4352. }
  4353. static int diff_opt_binary(const struct option *opt,
  4354. const char *arg, int unset)
  4355. {
  4356. struct diff_options *options = opt->value;
  4357. BUG_ON_OPT_NEG(unset);
  4358. BUG_ON_OPT_ARG(arg);
  4359. enable_patch_output(&options->output_format);
  4360. options->flags.binary = 1;
  4361. return 0;
  4362. }
  4363. static int diff_opt_break_rewrites(const struct option *opt,
  4364. const char *arg, int unset)
  4365. {
  4366. int *break_opt = opt->value;
  4367. int opt1, opt2;
  4368. BUG_ON_OPT_NEG(unset);
  4369. if (!arg)
  4370. arg = "";
  4371. opt1 = parse_rename_score(&arg);
  4372. if (*arg == 0)
  4373. opt2 = 0;
  4374. else if (*arg != '/')
  4375. return error(_("%s expects <n>/<m> form"), opt->long_name);
  4376. else {
  4377. arg++;
  4378. opt2 = parse_rename_score(&arg);
  4379. }
  4380. if (*arg != 0)
  4381. return error(_("%s expects <n>/<m> form"), opt->long_name);
  4382. *break_opt = opt1 | (opt2 << 16);
  4383. return 0;
  4384. }
  4385. static int diff_opt_char(const struct option *opt,
  4386. const char *arg, int unset)
  4387. {
  4388. char *value = opt->value;
  4389. BUG_ON_OPT_NEG(unset);
  4390. if (arg[1])
  4391. return error(_("%s expects a character, got '%s'"),
  4392. opt->long_name, arg);
  4393. *value = arg[0];
  4394. return 0;
  4395. }
  4396. static int diff_opt_color_moved(const struct option *opt,
  4397. const char *arg, int unset)
  4398. {
  4399. struct diff_options *options = opt->value;
  4400. if (unset) {
  4401. options->color_moved = COLOR_MOVED_NO;
  4402. } else if (!arg) {
  4403. if (diff_color_moved_default)
  4404. options->color_moved = diff_color_moved_default;
  4405. if (options->color_moved == COLOR_MOVED_NO)
  4406. options->color_moved = COLOR_MOVED_DEFAULT;
  4407. } else {
  4408. int cm = parse_color_moved(arg);
  4409. if (cm < 0)
  4410. return error(_("bad --color-moved argument: %s"), arg);
  4411. options->color_moved = cm;
  4412. }
  4413. return 0;
  4414. }
  4415. static int diff_opt_color_moved_ws(const struct option *opt,
  4416. const char *arg, int unset)
  4417. {
  4418. struct diff_options *options = opt->value;
  4419. unsigned cm;
  4420. if (unset) {
  4421. options->color_moved_ws_handling = 0;
  4422. return 0;
  4423. }
  4424. cm = parse_color_moved_ws(arg);
  4425. if (cm & COLOR_MOVED_WS_ERROR)
  4426. return error(_("invalid mode '%s' in --color-moved-ws"), arg);
  4427. options->color_moved_ws_handling = cm;
  4428. return 0;
  4429. }
  4430. static int diff_opt_color_words(const struct option *opt,
  4431. const char *arg, int unset)
  4432. {
  4433. struct diff_options *options = opt->value;
  4434. BUG_ON_OPT_NEG(unset);
  4435. options->use_color = 1;
  4436. options->word_diff = DIFF_WORDS_COLOR;
  4437. options->word_regex = arg;
  4438. return 0;
  4439. }
  4440. static int diff_opt_compact_summary(const struct option *opt,
  4441. const char *arg, int unset)
  4442. {
  4443. struct diff_options *options = opt->value;
  4444. BUG_ON_OPT_ARG(arg);
  4445. if (unset) {
  4446. options->flags.stat_with_summary = 0;
  4447. } else {
  4448. options->flags.stat_with_summary = 1;
  4449. options->output_format |= DIFF_FORMAT_DIFFSTAT;
  4450. }
  4451. return 0;
  4452. }
  4453. static int diff_opt_diff_algorithm(const struct option *opt,
  4454. const char *arg, int unset)
  4455. {
  4456. struct diff_options *options = opt->value;
  4457. long value = parse_algorithm_value(arg);
  4458. BUG_ON_OPT_NEG(unset);
  4459. if (value < 0)
  4460. return error(_("option diff-algorithm accepts \"myers\", "
  4461. "\"minimal\", \"patience\" and \"histogram\""));
  4462. /* clear out previous settings */
  4463. DIFF_XDL_CLR(options, NEED_MINIMAL);
  4464. options->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
  4465. options->xdl_opts |= value;
  4466. return 0;
  4467. }
  4468. static int diff_opt_dirstat(const struct option *opt,
  4469. const char *arg, int unset)
  4470. {
  4471. struct diff_options *options = opt->value;
  4472. BUG_ON_OPT_NEG(unset);
  4473. if (!strcmp(opt->long_name, "cumulative")) {
  4474. if (arg)
  4475. BUG("how come --cumulative take a value?");
  4476. arg = "cumulative";
  4477. } else if (!strcmp(opt->long_name, "dirstat-by-file"))
  4478. parse_dirstat_opt(options, "files");
  4479. parse_dirstat_opt(options, arg ? arg : "");
  4480. return 0;
  4481. }
  4482. static int diff_opt_find_copies(const struct option *opt,
  4483. const char *arg, int unset)
  4484. {
  4485. struct diff_options *options = opt->value;
  4486. BUG_ON_OPT_NEG(unset);
  4487. if (!arg)
  4488. arg = "";
  4489. options->rename_score = parse_rename_score(&arg);
  4490. if (*arg != 0)
  4491. return error(_("invalid argument to %s"), opt->long_name);
  4492. if (options->detect_rename == DIFF_DETECT_COPY)
  4493. options->flags.find_copies_harder = 1;
  4494. else
  4495. options->detect_rename = DIFF_DETECT_COPY;
  4496. return 0;
  4497. }
  4498. static int diff_opt_find_renames(const struct option *opt,
  4499. const char *arg, int unset)
  4500. {
  4501. struct diff_options *options = opt->value;
  4502. BUG_ON_OPT_NEG(unset);
  4503. if (!arg)
  4504. arg = "";
  4505. options->rename_score = parse_rename_score(&arg);
  4506. if (*arg != 0)
  4507. return error(_("invalid argument to %s"), opt->long_name);
  4508. options->detect_rename = DIFF_DETECT_RENAME;
  4509. return 0;
  4510. }
  4511. static int diff_opt_follow(const struct option *opt,
  4512. const char *arg, int unset)
  4513. {
  4514. struct diff_options *options = opt->value;
  4515. BUG_ON_OPT_ARG(arg);
  4516. if (unset) {
  4517. options->flags.follow_renames = 0;
  4518. options->flags.default_follow_renames = 0;
  4519. } else {
  4520. options->flags.follow_renames = 1;
  4521. }
  4522. return 0;
  4523. }
  4524. static int diff_opt_ignore_submodules(const struct option *opt,
  4525. const char *arg, int unset)
  4526. {
  4527. struct diff_options *options = opt->value;
  4528. BUG_ON_OPT_NEG(unset);
  4529. if (!arg)
  4530. arg = "all";
  4531. options->flags.override_submodule_config = 1;
  4532. handle_ignore_submodules_arg(options, arg);
  4533. return 0;
  4534. }
  4535. static int diff_opt_line_prefix(const struct option *opt,
  4536. const char *optarg, int unset)
  4537. {
  4538. struct diff_options *options = opt->value;
  4539. BUG_ON_OPT_NEG(unset);
  4540. options->line_prefix = optarg;
  4541. options->line_prefix_length = strlen(options->line_prefix);
  4542. graph_setup_line_prefix(options);
  4543. return 0;
  4544. }
  4545. static int diff_opt_no_prefix(const struct option *opt,
  4546. const char *optarg, int unset)
  4547. {
  4548. struct diff_options *options = opt->value;
  4549. BUG_ON_OPT_NEG(unset);
  4550. BUG_ON_OPT_ARG(optarg);
  4551. options->a_prefix = "";
  4552. options->b_prefix = "";
  4553. return 0;
  4554. }
  4555. static enum parse_opt_result diff_opt_output(struct parse_opt_ctx_t *ctx,
  4556. const struct option *opt,
  4557. const char *arg, int unset)
  4558. {
  4559. struct diff_options *options = opt->value;
  4560. char *path;
  4561. BUG_ON_OPT_NEG(unset);
  4562. path = prefix_filename(ctx->prefix, arg);
  4563. options->file = xfopen(path, "w");
  4564. options->close_file = 1;
  4565. if (options->use_color != GIT_COLOR_ALWAYS)
  4566. options->use_color = GIT_COLOR_NEVER;
  4567. free(path);
  4568. return 0;
  4569. }
  4570. static int diff_opt_patience(const struct option *opt,
  4571. const char *arg, int unset)
  4572. {
  4573. struct diff_options *options = opt->value;
  4574. int i;
  4575. BUG_ON_OPT_NEG(unset);
  4576. BUG_ON_OPT_ARG(arg);
  4577. options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
  4578. /*
  4579. * Both --patience and --anchored use PATIENCE_DIFF
  4580. * internally, so remove any anchors previously
  4581. * specified.
  4582. */
  4583. for (i = 0; i < options->anchors_nr; i++)
  4584. free(options->anchors[i]);
  4585. options->anchors_nr = 0;
  4586. return 0;
  4587. }
  4588. static int diff_opt_pickaxe_regex(const struct option *opt,
  4589. const char *arg, int unset)
  4590. {
  4591. struct diff_options *options = opt->value;
  4592. BUG_ON_OPT_NEG(unset);
  4593. options->pickaxe = arg;
  4594. options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
  4595. return 0;
  4596. }
  4597. static int diff_opt_pickaxe_string(const struct option *opt,
  4598. const char *arg, int unset)
  4599. {
  4600. struct diff_options *options = opt->value;
  4601. BUG_ON_OPT_NEG(unset);
  4602. options->pickaxe = arg;
  4603. options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
  4604. return 0;
  4605. }
  4606. static int diff_opt_relative(const struct option *opt,
  4607. const char *arg, int unset)
  4608. {
  4609. struct diff_options *options = opt->value;
  4610. BUG_ON_OPT_NEG(unset);
  4611. options->flags.relative_name = 1;
  4612. if (arg)
  4613. options->prefix = arg;
  4614. return 0;
  4615. }
  4616. static int diff_opt_submodule(const struct option *opt,
  4617. const char *arg, int unset)
  4618. {
  4619. struct diff_options *options = opt->value;
  4620. BUG_ON_OPT_NEG(unset);
  4621. if (!arg)
  4622. arg = "log";
  4623. if (parse_submodule_params(options, arg))
  4624. return error(_("failed to parse --submodule option parameter: '%s'"),
  4625. arg);
  4626. return 0;
  4627. }
  4628. static int diff_opt_textconv(const struct option *opt,
  4629. const char *arg, int unset)
  4630. {
  4631. struct diff_options *options = opt->value;
  4632. BUG_ON_OPT_ARG(arg);
  4633. if (unset) {
  4634. options->flags.allow_textconv = 0;
  4635. } else {
  4636. options->flags.allow_textconv = 1;
  4637. options->flags.textconv_set_via_cmdline = 1;
  4638. }
  4639. return 0;
  4640. }
  4641. static int diff_opt_unified(const struct option *opt,
  4642. const char *arg, int unset)
  4643. {
  4644. struct diff_options *options = opt->value;
  4645. char *s;
  4646. BUG_ON_OPT_NEG(unset);
  4647. if (arg) {
  4648. options->context = strtol(arg, &s, 10);
  4649. if (*s)
  4650. return error(_("%s expects a numerical value"), "--unified");
  4651. }
  4652. enable_patch_output(&options->output_format);
  4653. return 0;
  4654. }
  4655. static int diff_opt_word_diff(const struct option *opt,
  4656. const char *arg, int unset)
  4657. {
  4658. struct diff_options *options = opt->value;
  4659. BUG_ON_OPT_NEG(unset);
  4660. if (arg) {
  4661. if (!strcmp(arg, "plain"))
  4662. options->word_diff = DIFF_WORDS_PLAIN;
  4663. else if (!strcmp(arg, "color")) {
  4664. options->use_color = 1;
  4665. options->word_diff = DIFF_WORDS_COLOR;
  4666. }
  4667. else if (!strcmp(arg, "porcelain"))
  4668. options->word_diff = DIFF_WORDS_PORCELAIN;
  4669. else if (!strcmp(arg, "none"))
  4670. options->word_diff = DIFF_WORDS_NONE;
  4671. else
  4672. return error(_("bad --word-diff argument: %s"), arg);
  4673. } else {
  4674. if (options->word_diff == DIFF_WORDS_NONE)
  4675. options->word_diff = DIFF_WORDS_PLAIN;
  4676. }
  4677. return 0;
  4678. }
  4679. static int diff_opt_word_diff_regex(const struct option *opt,
  4680. const char *arg, int unset)
  4681. {
  4682. struct diff_options *options = opt->value;
  4683. BUG_ON_OPT_NEG(unset);
  4684. if (options->word_diff == DIFF_WORDS_NONE)
  4685. options->word_diff = DIFF_WORDS_PLAIN;
  4686. options->word_regex = arg;
  4687. return 0;
  4688. }
  4689. static void prep_parse_options(struct diff_options *options)
  4690. {
  4691. struct option parseopts[] = {
  4692. OPT_GROUP(N_("Diff output format options")),
  4693. OPT_BITOP('p', "patch", &options->output_format,
  4694. N_("generate patch"),
  4695. DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
  4696. OPT_BIT_F('s', "no-patch", &options->output_format,
  4697. N_("suppress diff output"),
  4698. DIFF_FORMAT_NO_OUTPUT, PARSE_OPT_NONEG),
  4699. OPT_BITOP('u', NULL, &options->output_format,
  4700. N_("generate patch"),
  4701. DIFF_FORMAT_PATCH, DIFF_FORMAT_NO_OUTPUT),
  4702. OPT_CALLBACK_F('U', "unified", options, N_("<n>"),
  4703. N_("generate diffs with <n> lines context"),
  4704. PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_unified),
  4705. OPT_BOOL('W', "function-context", &options->flags.funccontext,
  4706. N_("generate diffs with <n> lines context")),
  4707. OPT_BIT_F(0, "raw", &options->output_format,
  4708. N_("generate the diff in raw format"),
  4709. DIFF_FORMAT_RAW, PARSE_OPT_NONEG),
  4710. OPT_BITOP(0, "patch-with-raw", &options->output_format,
  4711. N_("synonym for '-p --raw'"),
  4712. DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW,
  4713. DIFF_FORMAT_NO_OUTPUT),
  4714. OPT_BITOP(0, "patch-with-stat", &options->output_format,
  4715. N_("synonym for '-p --stat'"),
  4716. DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT,
  4717. DIFF_FORMAT_NO_OUTPUT),
  4718. OPT_BIT_F(0, "numstat", &options->output_format,
  4719. N_("machine friendly --stat"),
  4720. DIFF_FORMAT_NUMSTAT, PARSE_OPT_NONEG),
  4721. OPT_BIT_F(0, "shortstat", &options->output_format,
  4722. N_("output only the last line of --stat"),
  4723. DIFF_FORMAT_SHORTSTAT, PARSE_OPT_NONEG),
  4724. OPT_CALLBACK_F('X', "dirstat", options, N_("<param1,param2>..."),
  4725. N_("output the distribution of relative amount of changes for each sub-directory"),
  4726. PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
  4727. diff_opt_dirstat),
  4728. OPT_CALLBACK_F(0, "cumulative", options, NULL,
  4729. N_("synonym for --dirstat=cumulative"),
  4730. PARSE_OPT_NONEG | PARSE_OPT_NOARG,
  4731. diff_opt_dirstat),
  4732. OPT_CALLBACK_F(0, "dirstat-by-file", options, N_("<param1,param2>..."),
  4733. N_("synonym for --dirstat=files,param1,param2..."),
  4734. PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
  4735. diff_opt_dirstat),
  4736. OPT_BIT_F(0, "check", &options->output_format,
  4737. N_("warn if changes introduce conflict markers or whitespace errors"),
  4738. DIFF_FORMAT_CHECKDIFF, PARSE_OPT_NONEG),
  4739. OPT_BIT_F(0, "summary", &options->output_format,
  4740. N_("condensed summary such as creations, renames and mode changes"),
  4741. DIFF_FORMAT_SUMMARY, PARSE_OPT_NONEG),
  4742. OPT_BIT_F(0, "name-only", &options->output_format,
  4743. N_("show only names of changed files"),
  4744. DIFF_FORMAT_NAME, PARSE_OPT_NONEG),
  4745. OPT_BIT_F(0, "name-status", &options->output_format,
  4746. N_("show only names and status of changed files"),
  4747. DIFF_FORMAT_NAME_STATUS, PARSE_OPT_NONEG),
  4748. OPT_CALLBACK_F(0, "stat", options, N_("<width>[,<name-width>[,<count>]]"),
  4749. N_("generate diffstat"),
  4750. PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_stat),
  4751. OPT_CALLBACK_F(0, "stat-width", options, N_("<width>"),
  4752. N_("generate diffstat with a given width"),
  4753. PARSE_OPT_NONEG, diff_opt_stat),
  4754. OPT_CALLBACK_F(0, "stat-name-width", options, N_("<width>"),
  4755. N_("generate diffstat with a given name width"),
  4756. PARSE_OPT_NONEG, diff_opt_stat),
  4757. OPT_CALLBACK_F(0, "stat-graph-width", options, N_("<width>"),
  4758. N_("generate diffstat with a given graph width"),
  4759. PARSE_OPT_NONEG, diff_opt_stat),
  4760. OPT_CALLBACK_F(0, "stat-count", options, N_("<count>"),
  4761. N_("generate diffstat with limited lines"),
  4762. PARSE_OPT_NONEG, diff_opt_stat),
  4763. OPT_CALLBACK_F(0, "compact-summary", options, NULL,
  4764. N_("generate compact summary in diffstat"),
  4765. PARSE_OPT_NOARG, diff_opt_compact_summary),
  4766. OPT_CALLBACK_F(0, "binary", options, NULL,
  4767. N_("output a binary diff that can be applied"),
  4768. PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_binary),
  4769. OPT_BOOL(0, "full-index", &options->flags.full_index,
  4770. N_("show full pre- and post-image object names on the \"index\" lines")),
  4771. OPT_COLOR_FLAG(0, "color", &options->use_color,
  4772. N_("show colored diff")),
  4773. OPT_CALLBACK_F(0, "ws-error-highlight", options, N_("<kind>"),
  4774. N_("highlight whitespace errors in the 'context', 'old' or 'new' lines in the diff"),
  4775. PARSE_OPT_NONEG, diff_opt_ws_error_highlight),
  4776. OPT_SET_INT('z', NULL, &options->line_termination,
  4777. N_("do not munge pathnames and use NULs as output field terminators in --raw or --numstat"),
  4778. 0),
  4779. OPT__ABBREV(&options->abbrev),
  4780. OPT_STRING_F(0, "src-prefix", &options->a_prefix, N_("<prefix>"),
  4781. N_("show the given source prefix instead of \"a/\""),
  4782. PARSE_OPT_NONEG),
  4783. OPT_STRING_F(0, "dst-prefix", &options->b_prefix, N_("<prefix>"),
  4784. N_("show the given destination prefix instead of \"b/\""),
  4785. PARSE_OPT_NONEG),
  4786. OPT_CALLBACK_F(0, "line-prefix", options, N_("<prefix>"),
  4787. N_("prepend an additional prefix to every line of output"),
  4788. PARSE_OPT_NONEG, diff_opt_line_prefix),
  4789. OPT_CALLBACK_F(0, "no-prefix", options, NULL,
  4790. N_("do not show any source or destination prefix"),
  4791. PARSE_OPT_NONEG | PARSE_OPT_NOARG, diff_opt_no_prefix),
  4792. OPT_INTEGER_F(0, "inter-hunk-context", &options->interhunkcontext,
  4793. N_("show context between diff hunks up to the specified number of lines"),
  4794. PARSE_OPT_NONEG),
  4795. OPT_CALLBACK_F(0, "output-indicator-new",
  4796. &options->output_indicators[OUTPUT_INDICATOR_NEW],
  4797. N_("<char>"),
  4798. N_("specify the character to indicate a new line instead of '+'"),
  4799. PARSE_OPT_NONEG, diff_opt_char),
  4800. OPT_CALLBACK_F(0, "output-indicator-old",
  4801. &options->output_indicators[OUTPUT_INDICATOR_OLD],
  4802. N_("<char>"),
  4803. N_("specify the character to indicate an old line instead of '-'"),
  4804. PARSE_OPT_NONEG, diff_opt_char),
  4805. OPT_CALLBACK_F(0, "output-indicator-context",
  4806. &options->output_indicators[OUTPUT_INDICATOR_CONTEXT],
  4807. N_("<char>"),
  4808. N_("specify the character to indicate a context instead of ' '"),
  4809. PARSE_OPT_NONEG, diff_opt_char),
  4810. OPT_GROUP(N_("Diff rename options")),
  4811. OPT_CALLBACK_F('B', "break-rewrites", &options->break_opt, N_("<n>[/<m>]"),
  4812. N_("break complete rewrite changes into pairs of delete and create"),
  4813. PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
  4814. diff_opt_break_rewrites),
  4815. OPT_CALLBACK_F('M', "find-renames", options, N_("<n>"),
  4816. N_("detect renames"),
  4817. PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
  4818. diff_opt_find_renames),
  4819. OPT_SET_INT_F('D', "irreversible-delete", &options->irreversible_delete,
  4820. N_("omit the preimage for deletes"),
  4821. 1, PARSE_OPT_NONEG),
  4822. OPT_CALLBACK_F('C', "find-copies", options, N_("<n>"),
  4823. N_("detect copies"),
  4824. PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
  4825. diff_opt_find_copies),
  4826. OPT_BOOL(0, "find-copies-harder", &options->flags.find_copies_harder,
  4827. N_("use unmodified files as source to find copies")),
  4828. OPT_SET_INT_F(0, "no-renames", &options->detect_rename,
  4829. N_("disable rename detection"),
  4830. 0, PARSE_OPT_NONEG),
  4831. OPT_BOOL(0, "rename-empty", &options->flags.rename_empty,
  4832. N_("use empty blobs as rename source")),
  4833. OPT_CALLBACK_F(0, "follow", options, NULL,
  4834. N_("continue listing the history of a file beyond renames"),
  4835. PARSE_OPT_NOARG, diff_opt_follow),
  4836. OPT_INTEGER('l', NULL, &options->rename_limit,
  4837. N_("prevent rename/copy detection if the number of rename/copy targets exceeds given limit")),
  4838. OPT_GROUP(N_("Diff algorithm options")),
  4839. OPT_BIT(0, "minimal", &options->xdl_opts,
  4840. N_("produce the smallest possible diff"),
  4841. XDF_NEED_MINIMAL),
  4842. OPT_BIT_F('w', "ignore-all-space", &options->xdl_opts,
  4843. N_("ignore whitespace when comparing lines"),
  4844. XDF_IGNORE_WHITESPACE, PARSE_OPT_NONEG),
  4845. OPT_BIT_F('b', "ignore-space-change", &options->xdl_opts,
  4846. N_("ignore changes in amount of whitespace"),
  4847. XDF_IGNORE_WHITESPACE_CHANGE, PARSE_OPT_NONEG),
  4848. OPT_BIT_F(0, "ignore-space-at-eol", &options->xdl_opts,
  4849. N_("ignore changes in whitespace at EOL"),
  4850. XDF_IGNORE_WHITESPACE_AT_EOL, PARSE_OPT_NONEG),
  4851. OPT_BIT_F(0, "ignore-cr-at-eol", &options->xdl_opts,
  4852. N_("ignore carrier-return at the end of line"),
  4853. XDF_IGNORE_CR_AT_EOL, PARSE_OPT_NONEG),
  4854. OPT_BIT_F(0, "ignore-blank-lines", &options->xdl_opts,
  4855. N_("ignore changes whose lines are all blank"),
  4856. XDF_IGNORE_BLANK_LINES, PARSE_OPT_NONEG),
  4857. OPT_BIT(0, "indent-heuristic", &options->xdl_opts,
  4858. N_("heuristic to shift diff hunk boundaries for easy reading"),
  4859. XDF_INDENT_HEURISTIC),
  4860. OPT_CALLBACK_F(0, "patience", options, NULL,
  4861. N_("generate diff using the \"patience diff\" algorithm"),
  4862. PARSE_OPT_NONEG | PARSE_OPT_NOARG,
  4863. diff_opt_patience),
  4864. OPT_BITOP(0, "histogram", &options->xdl_opts,
  4865. N_("generate diff using the \"histogram diff\" algorithm"),
  4866. XDF_HISTOGRAM_DIFF, XDF_DIFF_ALGORITHM_MASK),
  4867. OPT_CALLBACK_F(0, "diff-algorithm", options, N_("<algorithm>"),
  4868. N_("choose a diff algorithm"),
  4869. PARSE_OPT_NONEG, diff_opt_diff_algorithm),
  4870. OPT_CALLBACK_F(0, "anchored", options, N_("<text>"),
  4871. N_("generate diff using the \"anchored diff\" algorithm"),
  4872. PARSE_OPT_NONEG, diff_opt_anchored),
  4873. OPT_CALLBACK_F(0, "word-diff", options, N_("<mode>"),
  4874. N_("show word diff, using <mode> to delimit changed words"),
  4875. PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_word_diff),
  4876. OPT_CALLBACK_F(0, "word-diff-regex", options, N_("<regex>"),
  4877. N_("use <regex> to decide what a word is"),
  4878. PARSE_OPT_NONEG, diff_opt_word_diff_regex),
  4879. OPT_CALLBACK_F(0, "color-words", options, N_("<regex>"),
  4880. N_("equivalent to --word-diff=color --word-diff-regex=<regex>"),
  4881. PARSE_OPT_NONEG | PARSE_OPT_OPTARG, diff_opt_color_words),
  4882. OPT_CALLBACK_F(0, "color-moved", options, N_("<mode>"),
  4883. N_("moved lines of code are colored differently"),
  4884. PARSE_OPT_OPTARG, diff_opt_color_moved),
  4885. OPT_CALLBACK_F(0, "color-moved-ws", options, N_("<mode>"),
  4886. N_("how white spaces are ignored in --color-moved"),
  4887. 0, diff_opt_color_moved_ws),
  4888. OPT_GROUP(N_("Other diff options")),
  4889. OPT_CALLBACK_F(0, "relative", options, N_("<prefix>"),
  4890. N_("when run from subdir, exclude changes outside and show relative paths"),
  4891. PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
  4892. diff_opt_relative),
  4893. OPT_BOOL('a', "text", &options->flags.text,
  4894. N_("treat all files as text")),
  4895. OPT_BOOL('R', NULL, &options->flags.reverse_diff,
  4896. N_("swap two inputs, reverse the diff")),
  4897. OPT_BOOL(0, "exit-code", &options->flags.exit_with_status,
  4898. N_("exit with 1 if there were differences, 0 otherwise")),
  4899. OPT_BOOL(0, "quiet", &options->flags.quick,
  4900. N_("disable all output of the program")),
  4901. OPT_BOOL(0, "ext-diff", &options->flags.allow_external,
  4902. N_("allow an external diff helper to be executed")),
  4903. OPT_CALLBACK_F(0, "textconv", options, NULL,
  4904. N_("run external text conversion filters when comparing binary files"),
  4905. PARSE_OPT_NOARG, diff_opt_textconv),
  4906. OPT_CALLBACK_F(0, "ignore-submodules", options, N_("<when>"),
  4907. N_("ignore changes to submodules in the diff generation"),
  4908. PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
  4909. diff_opt_ignore_submodules),
  4910. OPT_CALLBACK_F(0, "submodule", options, N_("<format>"),
  4911. N_("specify how differences in submodules are shown"),
  4912. PARSE_OPT_NONEG | PARSE_OPT_OPTARG,
  4913. diff_opt_submodule),
  4914. OPT_SET_INT_F(0, "ita-invisible-in-index", &options->ita_invisible_in_index,
  4915. N_("hide 'git add -N' entries from the index"),
  4916. 1, PARSE_OPT_NONEG),
  4917. OPT_SET_INT_F(0, "ita-visible-in-index", &options->ita_invisible_in_index,
  4918. N_("treat 'git add -N' entries as real in the index"),
  4919. 0, PARSE_OPT_NONEG),
  4920. OPT_CALLBACK_F('S', NULL, options, N_("<string>"),
  4921. N_("look for differences that change the number of occurrences of the specified string"),
  4922. 0, diff_opt_pickaxe_string),
  4923. OPT_CALLBACK_F('G', NULL, options, N_("<regex>"),
  4924. N_("look for differences that change the number of occurrences of the specified regex"),
  4925. 0, diff_opt_pickaxe_regex),
  4926. OPT_BIT_F(0, "pickaxe-all", &options->pickaxe_opts,
  4927. N_("show all changes in the changeset with -S or -G"),
  4928. DIFF_PICKAXE_ALL, PARSE_OPT_NONEG),
  4929. OPT_BIT_F(0, "pickaxe-regex", &options->pickaxe_opts,
  4930. N_("treat <string> in -S as extended POSIX regular expression"),
  4931. DIFF_PICKAXE_REGEX, PARSE_OPT_NONEG),
  4932. OPT_FILENAME('O', NULL, &options->orderfile,
  4933. N_("control the order in which files appear in the output")),
  4934. OPT_CALLBACK_F(0, "find-object", options, N_("<object-id>"),
  4935. N_("look for differences that change the number of occurrences of the specified object"),
  4936. PARSE_OPT_NONEG, diff_opt_find_object),
  4937. OPT_CALLBACK_F(0, "diff-filter", options, N_("[(A|C|D|M|R|T|U|X|B)...[*]]"),
  4938. N_("select files by diff type"),
  4939. PARSE_OPT_NONEG, diff_opt_diff_filter),
  4940. { OPTION_CALLBACK, 0, "output", options, N_("<file>"),
  4941. N_("Output to a specific file"),
  4942. PARSE_OPT_NONEG, NULL, 0, diff_opt_output },
  4943. OPT_END()
  4944. };
  4945. ALLOC_ARRAY(options->parseopts, ARRAY_SIZE(parseopts));
  4946. memcpy(options->parseopts, parseopts, sizeof(parseopts));
  4947. }
  4948. int diff_opt_parse(struct diff_options *options,
  4949. const char **av, int ac, const char *prefix)
  4950. {
  4951. if (!prefix)
  4952. prefix = "";
  4953. ac = parse_options(ac, av, prefix, options->parseopts, NULL,
  4954. PARSE_OPT_KEEP_DASHDASH |
  4955. PARSE_OPT_KEEP_UNKNOWN |
  4956. PARSE_OPT_NO_INTERNAL_HELP |
  4957. PARSE_OPT_ONE_SHOT |
  4958. PARSE_OPT_STOP_AT_NON_OPTION);
  4959. return ac;
  4960. }
  4961. int parse_rename_score(const char **cp_p)
  4962. {
  4963. unsigned long num, scale;
  4964. int ch, dot;
  4965. const char *cp = *cp_p;
  4966. num = 0;
  4967. scale = 1;
  4968. dot = 0;
  4969. for (;;) {
  4970. ch = *cp;
  4971. if ( !dot && ch == '.' ) {
  4972. scale = 1;
  4973. dot = 1;
  4974. } else if ( ch == '%' ) {
  4975. scale = dot ? scale*100 : 100;
  4976. cp++; /* % is always at the end */
  4977. break;
  4978. } else if ( ch >= '0' && ch <= '9' ) {
  4979. if ( scale < 100000 ) {
  4980. scale *= 10;
  4981. num = (num*10) + (ch-'0');
  4982. }
  4983. } else {
  4984. break;
  4985. }
  4986. cp++;
  4987. }
  4988. *cp_p = cp;
  4989. /* user says num divided by scale and we say internally that
  4990. * is MAX_SCORE * num / scale.
  4991. */
  4992. return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
  4993. }
  4994. struct diff_queue_struct diff_queued_diff;
  4995. void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
  4996. {
  4997. ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
  4998. queue->queue[queue->nr++] = dp;
  4999. }
  5000. struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
  5001. struct diff_filespec *one,
  5002. struct diff_filespec *two)
  5003. {
  5004. struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
  5005. dp->one = one;
  5006. dp->two = two;
  5007. if (queue)
  5008. diff_q(queue, dp);
  5009. return dp;
  5010. }
  5011. void diff_free_filepair(struct diff_filepair *p)
  5012. {
  5013. free_filespec(p->one);
  5014. free_filespec(p->two);
  5015. free(p);
  5016. }
  5017. const char *diff_aligned_abbrev(const struct object_id *oid, int len)
  5018. {
  5019. int abblen;
  5020. const char *abbrev;
  5021. /* Do we want all 40 hex characters? */
  5022. if (len == the_hash_algo->hexsz)
  5023. return oid_to_hex(oid);
  5024. /* An abbreviated value is fine, possibly followed by an ellipsis. */
  5025. abbrev = diff_abbrev_oid(oid, len);
  5026. if (!print_sha1_ellipsis())
  5027. return abbrev;
  5028. abblen = strlen(abbrev);
  5029. /*
  5030. * In well-behaved cases, where the abbreviated result is the
  5031. * same as the requested length, append three dots after the
  5032. * abbreviation (hence the whole logic is limited to the case
  5033. * where abblen < 37); when the actual abbreviated result is a
  5034. * bit longer than the requested length, we reduce the number
  5035. * of dots so that they match the well-behaved ones. However,
  5036. * if the actual abbreviation is longer than the requested
  5037. * length by more than three, we give up on aligning, and add
  5038. * three dots anyway, to indicate that the output is not the
  5039. * full object name. Yes, this may be suboptimal, but this
  5040. * appears only in "diff --raw --abbrev" output and it is not
  5041. * worth the effort to change it now. Note that this would
  5042. * likely to work fine when the automatic sizing of default
  5043. * abbreviation length is used--we would be fed -1 in "len" in
  5044. * that case, and will end up always appending three-dots, but
  5045. * the automatic sizing is supposed to give abblen that ensures
  5046. * uniqueness across all objects (statistically speaking).
  5047. */
  5048. if (abblen < the_hash_algo->hexsz - 3) {
  5049. static char hex[GIT_MAX_HEXSZ + 1];
  5050. if (len < abblen && abblen <= len + 2)
  5051. xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
  5052. else
  5053. xsnprintf(hex, sizeof(hex), "%s...", abbrev);
  5054. return hex;
  5055. }
  5056. return oid_to_hex(oid);
  5057. }
  5058. static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
  5059. {
  5060. int line_termination = opt->line_termination;
  5061. int inter_name_termination = line_termination ? '\t' : '\0';
  5062. fprintf(opt->file, "%s", diff_line_prefix(opt));
  5063. if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
  5064. fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
  5065. diff_aligned_abbrev(&p->one->oid, opt->abbrev));
  5066. fprintf(opt->file, "%s ",
  5067. diff_aligned_abbrev(&p->two->oid, opt->abbrev));
  5068. }
  5069. if (p->score) {
  5070. fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
  5071. inter_name_termination);
  5072. } else {
  5073. fprintf(opt->file, "%c%c", p->status, inter_name_termination);
  5074. }
  5075. if (p->status == DIFF_STATUS_COPIED ||
  5076. p->status == DIFF_STATUS_RENAMED) {
  5077. const char *name_a, *name_b;
  5078. name_a = p->one->path;
  5079. name_b = p->two->path;
  5080. strip_prefix(opt->prefix_length, &name_a, &name_b);
  5081. write_name_quoted(name_a, opt->file, inter_name_termination);
  5082. write_name_quoted(name_b, opt->file, line_termination);
  5083. } else {
  5084. const char *name_a, *name_b;
  5085. name_a = p->one->mode ? p->one->path : p->two->path;
  5086. name_b = NULL;
  5087. strip_prefix(opt->prefix_length, &name_a, &name_b);
  5088. write_name_quoted(name_a, opt->file, line_termination);
  5089. }
  5090. }
  5091. int diff_unmodified_pair(struct diff_filepair *p)
  5092. {
  5093. /* This function is written stricter than necessary to support
  5094. * the currently implemented transformers, but the idea is to
  5095. * let transformers to produce diff_filepairs any way they want,
  5096. * and filter and clean them up here before producing the output.
  5097. */
  5098. struct diff_filespec *one = p->one, *two = p->two;
  5099. if (DIFF_PAIR_UNMERGED(p))
  5100. return 0; /* unmerged is interesting */
  5101. /* deletion, addition, mode or type change
  5102. * and rename are all interesting.
  5103. */
  5104. if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
  5105. DIFF_PAIR_MODE_CHANGED(p) ||
  5106. strcmp(one->path, two->path))
  5107. return 0;
  5108. /* both are valid and point at the same path. that is, we are
  5109. * dealing with a change.
  5110. */
  5111. if (one->oid_valid && two->oid_valid &&
  5112. oideq(&one->oid, &two->oid) &&
  5113. !one->dirty_submodule && !two->dirty_submodule)
  5114. return 1; /* no change */
  5115. if (!one->oid_valid && !two->oid_valid)
  5116. return 1; /* both look at the same file on the filesystem. */
  5117. return 0;
  5118. }
  5119. static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
  5120. {
  5121. if (diff_unmodified_pair(p))
  5122. return;
  5123. if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
  5124. (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
  5125. return; /* no tree diffs in patch format */
  5126. run_diff(p, o);
  5127. }
  5128. static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
  5129. struct diffstat_t *diffstat)
  5130. {
  5131. if (diff_unmodified_pair(p))
  5132. return;
  5133. if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
  5134. (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
  5135. return; /* no useful stat for tree diffs */
  5136. run_diffstat(p, o, diffstat);
  5137. }
  5138. static void diff_flush_checkdiff(struct diff_filepair *p,
  5139. struct diff_options *o)
  5140. {
  5141. if (diff_unmodified_pair(p))
  5142. return;
  5143. if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
  5144. (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
  5145. return; /* nothing to check in tree diffs */
  5146. run_checkdiff(p, o);
  5147. }
  5148. int diff_queue_is_empty(void)
  5149. {
  5150. struct diff_queue_struct *q = &diff_queued_diff;
  5151. int i;
  5152. for (i = 0; i < q->nr; i++)
  5153. if (!diff_unmodified_pair(q->queue[i]))
  5154. return 0;
  5155. return 1;
  5156. }
  5157. #if DIFF_DEBUG
  5158. void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
  5159. {
  5160. fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
  5161. x, one ? one : "",
  5162. s->path,
  5163. DIFF_FILE_VALID(s) ? "valid" : "invalid",
  5164. s->mode,
  5165. s->oid_valid ? oid_to_hex(&s->oid) : "");
  5166. fprintf(stderr, "queue[%d] %s size %lu\n",
  5167. x, one ? one : "",
  5168. s->size);
  5169. }
  5170. void diff_debug_filepair(const struct diff_filepair *p, int i)
  5171. {
  5172. diff_debug_filespec(p->one, i, "one");
  5173. diff_debug_filespec(p->two, i, "two");
  5174. fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
  5175. p->score, p->status ? p->status : '?',
  5176. p->one->rename_used, p->broken_pair);
  5177. }
  5178. void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
  5179. {
  5180. int i;
  5181. if (msg)
  5182. fprintf(stderr, "%s\n", msg);
  5183. fprintf(stderr, "q->nr = %d\n", q->nr);
  5184. for (i = 0; i < q->nr; i++) {
  5185. struct diff_filepair *p = q->queue[i];
  5186. diff_debug_filepair(p, i);
  5187. }
  5188. }
  5189. #endif
  5190. static void diff_resolve_rename_copy(void)
  5191. {
  5192. int i;
  5193. struct diff_filepair *p;
  5194. struct diff_queue_struct *q = &diff_queued_diff;
  5195. diff_debug_queue("resolve-rename-copy", q);
  5196. for (i = 0; i < q->nr; i++) {
  5197. p = q->queue[i];
  5198. p->status = 0; /* undecided */
  5199. if (DIFF_PAIR_UNMERGED(p))
  5200. p->status = DIFF_STATUS_UNMERGED;
  5201. else if (!DIFF_FILE_VALID(p->one))
  5202. p->status = DIFF_STATUS_ADDED;
  5203. else if (!DIFF_FILE_VALID(p->two))
  5204. p->status = DIFF_STATUS_DELETED;
  5205. else if (DIFF_PAIR_TYPE_CHANGED(p))
  5206. p->status = DIFF_STATUS_TYPE_CHANGED;
  5207. /* from this point on, we are dealing with a pair
  5208. * whose both sides are valid and of the same type, i.e.
  5209. * either in-place edit or rename/copy edit.
  5210. */
  5211. else if (DIFF_PAIR_RENAME(p)) {
  5212. /*
  5213. * A rename might have re-connected a broken
  5214. * pair up, causing the pathnames to be the
  5215. * same again. If so, that's not a rename at
  5216. * all, just a modification..
  5217. *
  5218. * Otherwise, see if this source was used for
  5219. * multiple renames, in which case we decrement
  5220. * the count, and call it a copy.
  5221. */
  5222. if (!strcmp(p->one->path, p->two->path))
  5223. p->status = DIFF_STATUS_MODIFIED;
  5224. else if (--p->one->rename_used > 0)
  5225. p->status = DIFF_STATUS_COPIED;
  5226. else
  5227. p->status = DIFF_STATUS_RENAMED;
  5228. }
  5229. else if (!oideq(&p->one->oid, &p->two->oid) ||
  5230. p->one->mode != p->two->mode ||
  5231. p->one->dirty_submodule ||
  5232. p->two->dirty_submodule ||
  5233. is_null_oid(&p->one->oid))
  5234. p->status = DIFF_STATUS_MODIFIED;
  5235. else {
  5236. /* This is a "no-change" entry and should not
  5237. * happen anymore, but prepare for broken callers.
  5238. */
  5239. error("feeding unmodified %s to diffcore",
  5240. p->one->path);
  5241. p->status = DIFF_STATUS_UNKNOWN;
  5242. }
  5243. }
  5244. diff_debug_queue("resolve-rename-copy done", q);
  5245. }
  5246. static int check_pair_status(struct diff_filepair *p)
  5247. {
  5248. switch (p->status) {
  5249. case DIFF_STATUS_UNKNOWN:
  5250. return 0;
  5251. case 0:
  5252. die("internal error in diff-resolve-rename-copy");
  5253. default:
  5254. return 1;
  5255. }
  5256. }
  5257. static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
  5258. {
  5259. int fmt = opt->output_format;
  5260. if (fmt & DIFF_FORMAT_CHECKDIFF)
  5261. diff_flush_checkdiff(p, opt);
  5262. else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
  5263. diff_flush_raw(p, opt);
  5264. else if (fmt & DIFF_FORMAT_NAME) {
  5265. const char *name_a, *name_b;
  5266. name_a = p->two->path;
  5267. name_b = NULL;
  5268. strip_prefix(opt->prefix_length, &name_a, &name_b);
  5269. fprintf(opt->file, "%s", diff_line_prefix(opt));
  5270. write_name_quoted(name_a, opt->file, opt->line_termination);
  5271. }
  5272. }
  5273. static void show_file_mode_name(struct diff_options *opt, const char *newdelete, struct diff_filespec *fs)
  5274. {
  5275. struct strbuf sb = STRBUF_INIT;
  5276. if (fs->mode)
  5277. strbuf_addf(&sb, " %s mode %06o ", newdelete, fs->mode);
  5278. else
  5279. strbuf_addf(&sb, " %s ", newdelete);
  5280. quote_c_style(fs->path, &sb, NULL, 0);
  5281. strbuf_addch(&sb, '\n');
  5282. emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
  5283. sb.buf, sb.len, 0);
  5284. strbuf_release(&sb);
  5285. }
  5286. static void show_mode_change(struct diff_options *opt, struct diff_filepair *p,
  5287. int show_name)
  5288. {
  5289. if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
  5290. struct strbuf sb = STRBUF_INIT;
  5291. strbuf_addf(&sb, " mode change %06o => %06o",
  5292. p->one->mode, p->two->mode);
  5293. if (show_name) {
  5294. strbuf_addch(&sb, ' ');
  5295. quote_c_style(p->two->path, &sb, NULL, 0);
  5296. }
  5297. strbuf_addch(&sb, '\n');
  5298. emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
  5299. sb.buf, sb.len, 0);
  5300. strbuf_release(&sb);
  5301. }
  5302. }
  5303. static void show_rename_copy(struct diff_options *opt, const char *renamecopy,
  5304. struct diff_filepair *p)
  5305. {
  5306. struct strbuf sb = STRBUF_INIT;
  5307. struct strbuf names = STRBUF_INIT;
  5308. pprint_rename(&names, p->one->path, p->two->path);
  5309. strbuf_addf(&sb, " %s %s (%d%%)\n",
  5310. renamecopy, names.buf, similarity_index(p));
  5311. strbuf_release(&names);
  5312. emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
  5313. sb.buf, sb.len, 0);
  5314. show_mode_change(opt, p, 0);
  5315. strbuf_release(&sb);
  5316. }
  5317. static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
  5318. {
  5319. switch(p->status) {
  5320. case DIFF_STATUS_DELETED:
  5321. show_file_mode_name(opt, "delete", p->one);
  5322. break;
  5323. case DIFF_STATUS_ADDED:
  5324. show_file_mode_name(opt, "create", p->two);
  5325. break;
  5326. case DIFF_STATUS_COPIED:
  5327. show_rename_copy(opt, "copy", p);
  5328. break;
  5329. case DIFF_STATUS_RENAMED:
  5330. show_rename_copy(opt, "rename", p);
  5331. break;
  5332. default:
  5333. if (p->score) {
  5334. struct strbuf sb = STRBUF_INIT;
  5335. strbuf_addstr(&sb, " rewrite ");
  5336. quote_c_style(p->two->path, &sb, NULL, 0);
  5337. strbuf_addf(&sb, " (%d%%)\n", similarity_index(p));
  5338. emit_diff_symbol(opt, DIFF_SYMBOL_SUMMARY,
  5339. sb.buf, sb.len, 0);
  5340. strbuf_release(&sb);
  5341. }
  5342. show_mode_change(opt, p, !p->score);
  5343. break;
  5344. }
  5345. }
  5346. struct patch_id_t {
  5347. git_hash_ctx *ctx;
  5348. int patchlen;
  5349. };
  5350. static int remove_space(char *line, int len)
  5351. {
  5352. int i;
  5353. char *dst = line;
  5354. unsigned char c;
  5355. for (i = 0; i < len; i++)
  5356. if (!isspace((c = line[i])))
  5357. *dst++ = c;
  5358. return dst - line;
  5359. }
  5360. void flush_one_hunk(struct object_id *result, git_hash_ctx *ctx)
  5361. {
  5362. unsigned char hash[GIT_MAX_RAWSZ];
  5363. unsigned short carry = 0;
  5364. int i;
  5365. the_hash_algo->final_fn(hash, ctx);
  5366. the_hash_algo->init_fn(ctx);
  5367. /* 20-byte sum, with carry */
  5368. for (i = 0; i < the_hash_algo->rawsz; ++i) {
  5369. carry += result->hash[i] + hash[i];
  5370. result->hash[i] = carry;
  5371. carry >>= 8;
  5372. }
  5373. }
  5374. static void patch_id_consume(void *priv, char *line, unsigned long len)
  5375. {
  5376. struct patch_id_t *data = priv;
  5377. int new_len;
  5378. new_len = remove_space(line, len);
  5379. the_hash_algo->update_fn(data->ctx, line, new_len);
  5380. data->patchlen += new_len;
  5381. }
  5382. static void patch_id_add_string(git_hash_ctx *ctx, const char *str)
  5383. {
  5384. the_hash_algo->update_fn(ctx, str, strlen(str));
  5385. }
  5386. static void patch_id_add_mode(git_hash_ctx *ctx, unsigned mode)
  5387. {
  5388. /* large enough for 2^32 in octal */
  5389. char buf[12];
  5390. int len = xsnprintf(buf, sizeof(buf), "%06o", mode);
  5391. the_hash_algo->update_fn(ctx, buf, len);
  5392. }
  5393. /* returns 0 upon success, and writes result into oid */
  5394. static int diff_get_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only, int stable)
  5395. {
  5396. struct diff_queue_struct *q = &diff_queued_diff;
  5397. int i;
  5398. git_hash_ctx ctx;
  5399. struct patch_id_t data;
  5400. the_hash_algo->init_fn(&ctx);
  5401. memset(&data, 0, sizeof(struct patch_id_t));
  5402. data.ctx = &ctx;
  5403. oidclr(oid);
  5404. for (i = 0; i < q->nr; i++) {
  5405. xpparam_t xpp;
  5406. xdemitconf_t xecfg;
  5407. mmfile_t mf1, mf2;
  5408. struct diff_filepair *p = q->queue[i];
  5409. int len1, len2;
  5410. memset(&xpp, 0, sizeof(xpp));
  5411. memset(&xecfg, 0, sizeof(xecfg));
  5412. if (p->status == 0)
  5413. return error("internal diff status error");
  5414. if (p->status == DIFF_STATUS_UNKNOWN)
  5415. continue;
  5416. if (diff_unmodified_pair(p))
  5417. continue;
  5418. if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
  5419. (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
  5420. continue;
  5421. if (DIFF_PAIR_UNMERGED(p))
  5422. continue;
  5423. diff_fill_oid_info(p->one, options->repo->index);
  5424. diff_fill_oid_info(p->two, options->repo->index);
  5425. len1 = remove_space(p->one->path, strlen(p->one->path));
  5426. len2 = remove_space(p->two->path, strlen(p->two->path));
  5427. patch_id_add_string(&ctx, "diff--git");
  5428. patch_id_add_string(&ctx, "a/");
  5429. the_hash_algo->update_fn(&ctx, p->one->path, len1);
  5430. patch_id_add_string(&ctx, "b/");
  5431. the_hash_algo->update_fn(&ctx, p->two->path, len2);
  5432. if (p->one->mode == 0) {
  5433. patch_id_add_string(&ctx, "newfilemode");
  5434. patch_id_add_mode(&ctx, p->two->mode);
  5435. patch_id_add_string(&ctx, "---/dev/null");
  5436. patch_id_add_string(&ctx, "+++b/");
  5437. the_hash_algo->update_fn(&ctx, p->two->path, len2);
  5438. } else if (p->two->mode == 0) {
  5439. patch_id_add_string(&ctx, "deletedfilemode");
  5440. patch_id_add_mode(&ctx, p->one->mode);
  5441. patch_id_add_string(&ctx, "---a/");
  5442. the_hash_algo->update_fn(&ctx, p->one->path, len1);
  5443. patch_id_add_string(&ctx, "+++/dev/null");
  5444. } else {
  5445. patch_id_add_string(&ctx, "---a/");
  5446. the_hash_algo->update_fn(&ctx, p->one->path, len1);
  5447. patch_id_add_string(&ctx, "+++b/");
  5448. the_hash_algo->update_fn(&ctx, p->two->path, len2);
  5449. }
  5450. if (diff_header_only)
  5451. continue;
  5452. if (fill_mmfile(options->repo, &mf1, p->one) < 0 ||
  5453. fill_mmfile(options->repo, &mf2, p->two) < 0)
  5454. return error("unable to read files to diff");
  5455. if (diff_filespec_is_binary(options->repo, p->one) ||
  5456. diff_filespec_is_binary(options->repo, p->two)) {
  5457. the_hash_algo->update_fn(&ctx, oid_to_hex(&p->one->oid),
  5458. the_hash_algo->hexsz);
  5459. the_hash_algo->update_fn(&ctx, oid_to_hex(&p->two->oid),
  5460. the_hash_algo->hexsz);
  5461. continue;
  5462. }
  5463. xpp.flags = 0;
  5464. xecfg.ctxlen = 3;
  5465. xecfg.flags = 0;
  5466. if (xdi_diff_outf(&mf1, &mf2, discard_hunk_line,
  5467. patch_id_consume, &data, &xpp, &xecfg))
  5468. return error("unable to generate patch-id diff for %s",
  5469. p->one->path);
  5470. if (stable)
  5471. flush_one_hunk(oid, &ctx);
  5472. }
  5473. if (!stable)
  5474. the_hash_algo->final_fn(oid->hash, &ctx);
  5475. return 0;
  5476. }
  5477. int diff_flush_patch_id(struct diff_options *options, struct object_id *oid, int diff_header_only, int stable)
  5478. {
  5479. struct diff_queue_struct *q = &diff_queued_diff;
  5480. int i;
  5481. int result = diff_get_patch_id(options, oid, diff_header_only, stable);
  5482. for (i = 0; i < q->nr; i++)
  5483. diff_free_filepair(q->queue[i]);
  5484. free(q->queue);
  5485. DIFF_QUEUE_CLEAR(q);
  5486. return result;
  5487. }
  5488. static int is_summary_empty(const struct diff_queue_struct *q)
  5489. {
  5490. int i;
  5491. for (i = 0; i < q->nr; i++) {
  5492. const struct diff_filepair *p = q->queue[i];
  5493. switch (p->status) {
  5494. case DIFF_STATUS_DELETED:
  5495. case DIFF_STATUS_ADDED:
  5496. case DIFF_STATUS_COPIED:
  5497. case DIFF_STATUS_RENAMED:
  5498. return 0;
  5499. default:
  5500. if (p->score)
  5501. return 0;
  5502. if (p->one->mode && p->two->mode &&
  5503. p->one->mode != p->two->mode)
  5504. return 0;
  5505. break;
  5506. }
  5507. }
  5508. return 1;
  5509. }
  5510. static const char rename_limit_warning[] =
  5511. N_("inexact rename detection was skipped due to too many files.");
  5512. static const char degrade_cc_to_c_warning[] =
  5513. N_("only found copies from modified paths due to too many files.");
  5514. static const char rename_limit_advice[] =
  5515. N_("you may want to set your %s variable to at least "
  5516. "%d and retry the command.");
  5517. void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
  5518. {
  5519. fflush(stdout);
  5520. if (degraded_cc)
  5521. warning(_(degrade_cc_to_c_warning));
  5522. else if (needed)
  5523. warning(_(rename_limit_warning));
  5524. else
  5525. return;
  5526. if (0 < needed)
  5527. warning(_(rename_limit_advice), varname, needed);
  5528. }
  5529. static void diff_flush_patch_all_file_pairs(struct diff_options *o)
  5530. {
  5531. int i;
  5532. static struct emitted_diff_symbols esm = EMITTED_DIFF_SYMBOLS_INIT;
  5533. struct diff_queue_struct *q = &diff_queued_diff;
  5534. if (WSEH_NEW & WS_RULE_MASK)
  5535. BUG("WS rules bit mask overlaps with diff symbol flags");
  5536. if (o->color_moved)
  5537. o->emitted_symbols = &esm;
  5538. for (i = 0; i < q->nr; i++) {
  5539. struct diff_filepair *p = q->queue[i];
  5540. if (check_pair_status(p))
  5541. diff_flush_patch(p, o);
  5542. }
  5543. if (o->emitted_symbols) {
  5544. if (o->color_moved) {
  5545. struct hashmap add_lines, del_lines;
  5546. if (o->color_moved_ws_handling &
  5547. COLOR_MOVED_WS_ALLOW_INDENTATION_CHANGE)
  5548. o->color_moved_ws_handling |= XDF_IGNORE_WHITESPACE;
  5549. hashmap_init(&del_lines, moved_entry_cmp, o, 0);
  5550. hashmap_init(&add_lines, moved_entry_cmp, o, 0);
  5551. add_lines_to_move_detection(o, &add_lines, &del_lines);
  5552. mark_color_as_moved(o, &add_lines, &del_lines);
  5553. if (o->color_moved == COLOR_MOVED_ZEBRA_DIM)
  5554. dim_moved_lines(o);
  5555. hashmap_free_entries(&add_lines, struct moved_entry,
  5556. ent);
  5557. hashmap_free_entries(&del_lines, struct moved_entry,
  5558. ent);
  5559. }
  5560. for (i = 0; i < esm.nr; i++)
  5561. emit_diff_symbol_from_struct(o, &esm.buf[i]);
  5562. for (i = 0; i < esm.nr; i++)
  5563. free((void *)esm.buf[i].line);
  5564. esm.nr = 0;
  5565. o->emitted_symbols = NULL;
  5566. }
  5567. }
  5568. void diff_flush(struct diff_options *options)
  5569. {
  5570. struct diff_queue_struct *q = &diff_queued_diff;
  5571. int i, output_format = options->output_format;
  5572. int separator = 0;
  5573. int dirstat_by_line = 0;
  5574. /*
  5575. * Order: raw, stat, summary, patch
  5576. * or: name/name-status/checkdiff (other bits clear)
  5577. */
  5578. if (!q->nr)
  5579. goto free_queue;
  5580. if (output_format & (DIFF_FORMAT_RAW |
  5581. DIFF_FORMAT_NAME |
  5582. DIFF_FORMAT_NAME_STATUS |
  5583. DIFF_FORMAT_CHECKDIFF)) {
  5584. for (i = 0; i < q->nr; i++) {
  5585. struct diff_filepair *p = q->queue[i];
  5586. if (check_pair_status(p))
  5587. flush_one_pair(p, options);
  5588. }
  5589. separator++;
  5590. }
  5591. if (output_format & DIFF_FORMAT_DIRSTAT && options->flags.dirstat_by_line)
  5592. dirstat_by_line = 1;
  5593. if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
  5594. dirstat_by_line) {
  5595. struct diffstat_t diffstat;
  5596. memset(&diffstat, 0, sizeof(struct diffstat_t));
  5597. for (i = 0; i < q->nr; i++) {
  5598. struct diff_filepair *p = q->queue[i];
  5599. if (check_pair_status(p))
  5600. diff_flush_stat(p, options, &diffstat);
  5601. }
  5602. if (output_format & DIFF_FORMAT_NUMSTAT)
  5603. show_numstat(&diffstat, options);
  5604. if (output_format & DIFF_FORMAT_DIFFSTAT)
  5605. show_stats(&diffstat, options);
  5606. if (output_format & DIFF_FORMAT_SHORTSTAT)
  5607. show_shortstats(&diffstat, options);
  5608. if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
  5609. show_dirstat_by_line(&diffstat, options);
  5610. free_diffstat_info(&diffstat);
  5611. separator++;
  5612. }
  5613. if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
  5614. show_dirstat(options);
  5615. if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
  5616. for (i = 0; i < q->nr; i++) {
  5617. diff_summary(options, q->queue[i]);
  5618. }
  5619. separator++;
  5620. }
  5621. if (output_format & DIFF_FORMAT_NO_OUTPUT &&
  5622. options->flags.exit_with_status &&
  5623. options->flags.diff_from_contents) {
  5624. /*
  5625. * run diff_flush_patch for the exit status. setting
  5626. * options->file to /dev/null should be safe, because we
  5627. * aren't supposed to produce any output anyway.
  5628. */
  5629. if (options->close_file)
  5630. fclose(options->file);
  5631. options->file = xfopen("/dev/null", "w");
  5632. options->close_file = 1;
  5633. options->color_moved = 0;
  5634. for (i = 0; i < q->nr; i++) {
  5635. struct diff_filepair *p = q->queue[i];
  5636. if (check_pair_status(p))
  5637. diff_flush_patch(p, options);
  5638. if (options->found_changes)
  5639. break;
  5640. }
  5641. }
  5642. if (output_format & DIFF_FORMAT_PATCH) {
  5643. if (separator) {
  5644. emit_diff_symbol(options, DIFF_SYMBOL_SEPARATOR, NULL, 0, 0);
  5645. if (options->stat_sep)
  5646. /* attach patch instead of inline */
  5647. emit_diff_symbol(options, DIFF_SYMBOL_STAT_SEP,
  5648. NULL, 0, 0);
  5649. }
  5650. diff_flush_patch_all_file_pairs(options);
  5651. }
  5652. if (output_format & DIFF_FORMAT_CALLBACK)
  5653. options->format_callback(q, options, options->format_callback_data);
  5654. for (i = 0; i < q->nr; i++)
  5655. diff_free_filepair(q->queue[i]);
  5656. free_queue:
  5657. free(q->queue);
  5658. DIFF_QUEUE_CLEAR(q);
  5659. if (options->close_file)
  5660. fclose(options->file);
  5661. /*
  5662. * Report the content-level differences with HAS_CHANGES;
  5663. * diff_addremove/diff_change does not set the bit when
  5664. * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
  5665. */
  5666. if (options->flags.diff_from_contents) {
  5667. if (options->found_changes)
  5668. options->flags.has_changes = 1;
  5669. else
  5670. options->flags.has_changes = 0;
  5671. }
  5672. }
  5673. static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
  5674. {
  5675. return (((p->status == DIFF_STATUS_MODIFIED) &&
  5676. ((p->score &&
  5677. filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
  5678. (!p->score &&
  5679. filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
  5680. ((p->status != DIFF_STATUS_MODIFIED) &&
  5681. filter_bit_tst(p->status, options)));
  5682. }
  5683. static void diffcore_apply_filter(struct diff_options *options)
  5684. {
  5685. int i;
  5686. struct diff_queue_struct *q = &diff_queued_diff;
  5687. struct diff_queue_struct outq;
  5688. DIFF_QUEUE_CLEAR(&outq);
  5689. if (!options->filter)
  5690. return;
  5691. if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
  5692. int found;
  5693. for (i = found = 0; !found && i < q->nr; i++) {
  5694. if (match_filter(options, q->queue[i]))
  5695. found++;
  5696. }
  5697. if (found)
  5698. return;
  5699. /* otherwise we will clear the whole queue
  5700. * by copying the empty outq at the end of this
  5701. * function, but first clear the current entries
  5702. * in the queue.
  5703. */
  5704. for (i = 0; i < q->nr; i++)
  5705. diff_free_filepair(q->queue[i]);
  5706. }
  5707. else {
  5708. /* Only the matching ones */
  5709. for (i = 0; i < q->nr; i++) {
  5710. struct diff_filepair *p = q->queue[i];
  5711. if (match_filter(options, p))
  5712. diff_q(&outq, p);
  5713. else
  5714. diff_free_filepair(p);
  5715. }
  5716. }
  5717. free(q->queue);
  5718. *q = outq;
  5719. }
  5720. /* Check whether two filespecs with the same mode and size are identical */
  5721. static int diff_filespec_is_identical(struct repository *r,
  5722. struct diff_filespec *one,
  5723. struct diff_filespec *two)
  5724. {
  5725. if (S_ISGITLINK(one->mode))
  5726. return 0;
  5727. if (diff_populate_filespec(r, one, 0))
  5728. return 0;
  5729. if (diff_populate_filespec(r, two, 0))
  5730. return 0;
  5731. return !memcmp(one->data, two->data, one->size);
  5732. }
  5733. static int diff_filespec_check_stat_unmatch(struct repository *r,
  5734. struct diff_filepair *p)
  5735. {
  5736. if (p->done_skip_stat_unmatch)
  5737. return p->skip_stat_unmatch_result;
  5738. p->done_skip_stat_unmatch = 1;
  5739. p->skip_stat_unmatch_result = 0;
  5740. /*
  5741. * 1. Entries that come from stat info dirtiness
  5742. * always have both sides (iow, not create/delete),
  5743. * one side of the object name is unknown, with
  5744. * the same mode and size. Keep the ones that
  5745. * do not match these criteria. They have real
  5746. * differences.
  5747. *
  5748. * 2. At this point, the file is known to be modified,
  5749. * with the same mode and size, and the object
  5750. * name of one side is unknown. Need to inspect
  5751. * the identical contents.
  5752. */
  5753. if (!DIFF_FILE_VALID(p->one) || /* (1) */
  5754. !DIFF_FILE_VALID(p->two) ||
  5755. (p->one->oid_valid && p->two->oid_valid) ||
  5756. (p->one->mode != p->two->mode) ||
  5757. diff_populate_filespec(r, p->one, CHECK_SIZE_ONLY) ||
  5758. diff_populate_filespec(r, p->two, CHECK_SIZE_ONLY) ||
  5759. (p->one->size != p->two->size) ||
  5760. !diff_filespec_is_identical(r, p->one, p->two)) /* (2) */
  5761. p->skip_stat_unmatch_result = 1;
  5762. return p->skip_stat_unmatch_result;
  5763. }
  5764. static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
  5765. {
  5766. int i;
  5767. struct diff_queue_struct *q = &diff_queued_diff;
  5768. struct diff_queue_struct outq;
  5769. DIFF_QUEUE_CLEAR(&outq);
  5770. for (i = 0; i < q->nr; i++) {
  5771. struct diff_filepair *p = q->queue[i];
  5772. if (diff_filespec_check_stat_unmatch(diffopt->repo, p))
  5773. diff_q(&outq, p);
  5774. else {
  5775. /*
  5776. * The caller can subtract 1 from skip_stat_unmatch
  5777. * to determine how many paths were dirty only
  5778. * due to stat info mismatch.
  5779. */
  5780. if (!diffopt->flags.no_index)
  5781. diffopt->skip_stat_unmatch++;
  5782. diff_free_filepair(p);
  5783. }
  5784. }
  5785. free(q->queue);
  5786. *q = outq;
  5787. }
  5788. static int diffnamecmp(const void *a_, const void *b_)
  5789. {
  5790. const struct diff_filepair *a = *((const struct diff_filepair **)a_);
  5791. const struct diff_filepair *b = *((const struct diff_filepair **)b_);
  5792. const char *name_a, *name_b;
  5793. name_a = a->one ? a->one->path : a->two->path;
  5794. name_b = b->one ? b->one->path : b->two->path;
  5795. return strcmp(name_a, name_b);
  5796. }
  5797. void diffcore_fix_diff_index(void)
  5798. {
  5799. struct diff_queue_struct *q = &diff_queued_diff;
  5800. QSORT(q->queue, q->nr, diffnamecmp);
  5801. }
  5802. static void add_if_missing(struct repository *r,
  5803. struct oid_array *to_fetch,
  5804. const struct diff_filespec *filespec)
  5805. {
  5806. if (filespec && filespec->oid_valid &&
  5807. !S_ISGITLINK(filespec->mode) &&
  5808. oid_object_info_extended(r, &filespec->oid, NULL,
  5809. OBJECT_INFO_FOR_PREFETCH))
  5810. oid_array_append(to_fetch, &filespec->oid);
  5811. }
  5812. void diffcore_std(struct diff_options *options)
  5813. {
  5814. if (options->repo == the_repository && has_promisor_remote()) {
  5815. /*
  5816. * Prefetch the diff pairs that are about to be flushed.
  5817. */
  5818. int i;
  5819. struct diff_queue_struct *q = &diff_queued_diff;
  5820. struct oid_array to_fetch = OID_ARRAY_INIT;
  5821. for (i = 0; i < q->nr; i++) {
  5822. struct diff_filepair *p = q->queue[i];
  5823. add_if_missing(options->repo, &to_fetch, p->one);
  5824. add_if_missing(options->repo, &to_fetch, p->two);
  5825. }
  5826. if (to_fetch.nr)
  5827. /*
  5828. * NEEDSWORK: Consider deduplicating the OIDs sent.
  5829. */
  5830. promisor_remote_get_direct(options->repo,
  5831. to_fetch.oid, to_fetch.nr);
  5832. oid_array_clear(&to_fetch);
  5833. }
  5834. /* NOTE please keep the following in sync with diff_tree_combined() */
  5835. if (options->skip_stat_unmatch)
  5836. diffcore_skip_stat_unmatch(options);
  5837. if (!options->found_follow) {
  5838. /* See try_to_follow_renames() in tree-diff.c */
  5839. if (options->break_opt != -1)
  5840. diffcore_break(options->repo,
  5841. options->break_opt);
  5842. if (options->detect_rename)
  5843. diffcore_rename(options);
  5844. if (options->break_opt != -1)
  5845. diffcore_merge_broken();
  5846. }
  5847. if (options->pickaxe_opts & DIFF_PICKAXE_KINDS_MASK)
  5848. diffcore_pickaxe(options);
  5849. if (options->orderfile)
  5850. diffcore_order(options->orderfile);
  5851. if (!options->found_follow)
  5852. /* See try_to_follow_renames() in tree-diff.c */
  5853. diff_resolve_rename_copy();
  5854. diffcore_apply_filter(options);
  5855. if (diff_queued_diff.nr && !options->flags.diff_from_contents)
  5856. options->flags.has_changes = 1;
  5857. else
  5858. options->flags.has_changes = 0;
  5859. options->found_follow = 0;
  5860. }
  5861. int diff_result_code(struct diff_options *opt, int status)
  5862. {
  5863. int result = 0;
  5864. diff_warn_rename_limit("diff.renameLimit",
  5865. opt->needed_rename_limit,
  5866. opt->degraded_cc_to_c);
  5867. if (!opt->flags.exit_with_status &&
  5868. !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
  5869. return status;
  5870. if (opt->flags.exit_with_status &&
  5871. opt->flags.has_changes)
  5872. result |= 01;
  5873. if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
  5874. opt->flags.check_failed)
  5875. result |= 02;
  5876. return result;
  5877. }
  5878. int diff_can_quit_early(struct diff_options *opt)
  5879. {
  5880. return (opt->flags.quick &&
  5881. !opt->filter &&
  5882. opt->flags.has_changes);
  5883. }
  5884. /*
  5885. * Shall changes to this submodule be ignored?
  5886. *
  5887. * Submodule changes can be configured to be ignored separately for each path,
  5888. * but that configuration can be overridden from the command line.
  5889. */
  5890. static int is_submodule_ignored(const char *path, struct diff_options *options)
  5891. {
  5892. int ignored = 0;
  5893. struct diff_flags orig_flags = options->flags;
  5894. if (!options->flags.override_submodule_config)
  5895. set_diffopt_flags_from_submodule_config(options, path);
  5896. if (options->flags.ignore_submodules)
  5897. ignored = 1;
  5898. options->flags = orig_flags;
  5899. return ignored;
  5900. }
  5901. void diff_addremove(struct diff_options *options,
  5902. int addremove, unsigned mode,
  5903. const struct object_id *oid,
  5904. int oid_valid,
  5905. const char *concatpath, unsigned dirty_submodule)
  5906. {
  5907. struct diff_filespec *one, *two;
  5908. if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
  5909. return;
  5910. /* This may look odd, but it is a preparation for
  5911. * feeding "there are unchanged files which should
  5912. * not produce diffs, but when you are doing copy
  5913. * detection you would need them, so here they are"
  5914. * entries to the diff-core. They will be prefixed
  5915. * with something like '=' or '*' (I haven't decided
  5916. * which but should not make any difference).
  5917. * Feeding the same new and old to diff_change()
  5918. * also has the same effect.
  5919. * Before the final output happens, they are pruned after
  5920. * merged into rename/copy pairs as appropriate.
  5921. */
  5922. if (options->flags.reverse_diff)
  5923. addremove = (addremove == '+' ? '-' :
  5924. addremove == '-' ? '+' : addremove);
  5925. if (options->prefix &&
  5926. strncmp(concatpath, options->prefix, options->prefix_length))
  5927. return;
  5928. one = alloc_filespec(concatpath);
  5929. two = alloc_filespec(concatpath);
  5930. if (addremove != '+')
  5931. fill_filespec(one, oid, oid_valid, mode);
  5932. if (addremove != '-') {
  5933. fill_filespec(two, oid, oid_valid, mode);
  5934. two->dirty_submodule = dirty_submodule;
  5935. }
  5936. diff_queue(&diff_queued_diff, one, two);
  5937. if (!options->flags.diff_from_contents)
  5938. options->flags.has_changes = 1;
  5939. }
  5940. void diff_change(struct diff_options *options,
  5941. unsigned old_mode, unsigned new_mode,
  5942. const struct object_id *old_oid,
  5943. const struct object_id *new_oid,
  5944. int old_oid_valid, int new_oid_valid,
  5945. const char *concatpath,
  5946. unsigned old_dirty_submodule, unsigned new_dirty_submodule)
  5947. {
  5948. struct diff_filespec *one, *two;
  5949. struct diff_filepair *p;
  5950. if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
  5951. is_submodule_ignored(concatpath, options))
  5952. return;
  5953. if (options->flags.reverse_diff) {
  5954. SWAP(old_mode, new_mode);
  5955. SWAP(old_oid, new_oid);
  5956. SWAP(old_oid_valid, new_oid_valid);
  5957. SWAP(old_dirty_submodule, new_dirty_submodule);
  5958. }
  5959. if (options->prefix &&
  5960. strncmp(concatpath, options->prefix, options->prefix_length))
  5961. return;
  5962. one = alloc_filespec(concatpath);
  5963. two = alloc_filespec(concatpath);
  5964. fill_filespec(one, old_oid, old_oid_valid, old_mode);
  5965. fill_filespec(two, new_oid, new_oid_valid, new_mode);
  5966. one->dirty_submodule = old_dirty_submodule;
  5967. two->dirty_submodule = new_dirty_submodule;
  5968. p = diff_queue(&diff_queued_diff, one, two);
  5969. if (options->flags.diff_from_contents)
  5970. return;
  5971. if (options->flags.quick && options->skip_stat_unmatch &&
  5972. !diff_filespec_check_stat_unmatch(options->repo, p))
  5973. return;
  5974. options->flags.has_changes = 1;
  5975. }
  5976. struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
  5977. {
  5978. struct diff_filepair *pair;
  5979. struct diff_filespec *one, *two;
  5980. if (options->prefix &&
  5981. strncmp(path, options->prefix, options->prefix_length))
  5982. return NULL;
  5983. one = alloc_filespec(path);
  5984. two = alloc_filespec(path);
  5985. pair = diff_queue(&diff_queued_diff, one, two);
  5986. pair->is_unmerged = 1;
  5987. return pair;
  5988. }
  5989. static char *run_textconv(struct repository *r,
  5990. const char *pgm,
  5991. struct diff_filespec *spec,
  5992. size_t *outsize)
  5993. {
  5994. struct diff_tempfile *temp;
  5995. const char *argv[3];
  5996. const char **arg = argv;
  5997. struct child_process child = CHILD_PROCESS_INIT;
  5998. struct strbuf buf = STRBUF_INIT;
  5999. int err = 0;
  6000. temp = prepare_temp_file(r, spec->path, spec);
  6001. *arg++ = pgm;
  6002. *arg++ = temp->name;
  6003. *arg = NULL;
  6004. child.use_shell = 1;
  6005. child.argv = argv;
  6006. child.out = -1;
  6007. if (start_command(&child)) {
  6008. remove_tempfile();
  6009. return NULL;
  6010. }
  6011. if (strbuf_read(&buf, child.out, 0) < 0)
  6012. err = error("error reading from textconv command '%s'", pgm);
  6013. close(child.out);
  6014. if (finish_command(&child) || err) {
  6015. strbuf_release(&buf);
  6016. remove_tempfile();
  6017. return NULL;
  6018. }
  6019. remove_tempfile();
  6020. return strbuf_detach(&buf, outsize);
  6021. }
  6022. size_t fill_textconv(struct repository *r,
  6023. struct userdiff_driver *driver,
  6024. struct diff_filespec *df,
  6025. char **outbuf)
  6026. {
  6027. size_t size;
  6028. if (!driver) {
  6029. if (!DIFF_FILE_VALID(df)) {
  6030. *outbuf = "";
  6031. return 0;
  6032. }
  6033. if (diff_populate_filespec(r, df, 0))
  6034. die("unable to read files to diff");
  6035. *outbuf = df->data;
  6036. return df->size;
  6037. }
  6038. if (!driver->textconv)
  6039. BUG("fill_textconv called with non-textconv driver");
  6040. if (driver->textconv_cache && df->oid_valid) {
  6041. *outbuf = notes_cache_get(driver->textconv_cache,
  6042. &df->oid,
  6043. &size);
  6044. if (*outbuf)
  6045. return size;
  6046. }
  6047. *outbuf = run_textconv(r, driver->textconv, df, &size);
  6048. if (!*outbuf)
  6049. die("unable to read files to diff");
  6050. if (driver->textconv_cache && df->oid_valid) {
  6051. /* ignore errors, as we might be in a readonly repository */
  6052. notes_cache_put(driver->textconv_cache, &df->oid, *outbuf,
  6053. size);
  6054. /*
  6055. * we could save up changes and flush them all at the end,
  6056. * but we would need an extra call after all diffing is done.
  6057. * Since generating a cache entry is the slow path anyway,
  6058. * this extra overhead probably isn't a big deal.
  6059. */
  6060. notes_cache_write(driver->textconv_cache);
  6061. }
  6062. return size;
  6063. }
  6064. int textconv_object(struct repository *r,
  6065. const char *path,
  6066. unsigned mode,
  6067. const struct object_id *oid,
  6068. int oid_valid,
  6069. char **buf,
  6070. unsigned long *buf_size)
  6071. {
  6072. struct diff_filespec *df;
  6073. struct userdiff_driver *textconv;
  6074. df = alloc_filespec(path);
  6075. fill_filespec(df, oid, oid_valid, mode);
  6076. textconv = get_textconv(r, df);
  6077. if (!textconv) {
  6078. free_filespec(df);
  6079. return 0;
  6080. }
  6081. *buf_size = fill_textconv(r, textconv, df, buf);
  6082. free_filespec(df);
  6083. return 1;
  6084. }
  6085. void setup_diff_pager(struct diff_options *opt)
  6086. {
  6087. /*
  6088. * If the user asked for our exit code, then either they want --quiet
  6089. * or --exit-code. We should definitely not bother with a pager in the
  6090. * former case, as we will generate no output. Since we still properly
  6091. * report our exit code even when a pager is run, we _could_ run a
  6092. * pager with --exit-code. But since we have not done so historically,
  6093. * and because it is easy to find people oneline advising "git diff
  6094. * --exit-code" in hooks and other scripts, we do not do so.
  6095. */
  6096. if (!opt->flags.exit_with_status &&
  6097. check_pager_config("diff") != 0)
  6098. setup_pager();
  6099. }