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

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

6850 lines
188KB

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