gitdiff.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #include "gitdiff.h"
  2. #include <gitrepository.h>
  3. #include <QDebug>
  4. #include <git2/types.h>
  5. #include <git2/diff.h>
  6. #include <git2/commit.h>
  7. GitDiff::GitDiff(git_commit* a, git_commit* b, GitRepository *repository) : QObject()
  8. ,m_repository(repository)
  9. {
  10. Q_ASSERT_X(m_repository, "GitDiff", "Repository of NULL");
  11. connect(m_repository, &GitRepository::destroyed, this, &GitDiff::deleteLater);
  12. readBody(a, b);
  13. }
  14. void GitDiff::readBody(git_commit *a, git_commit *b)
  15. {
  16. git_diff *diff = nullptr;
  17. git_tree *a_tree = nullptr;
  18. git_tree *b_tree = nullptr;
  19. git_commit_tree(&a_tree, a);
  20. git_commit_tree(&b_tree, b);
  21. git_diff_tree_to_tree(&diff, m_repository->raw(), a_tree, b_tree, nullptr);
  22. git_diff_print(diff,
  23. GIT_DIFF_FORMAT_PATCH,
  24. [](const git_diff_delta *delta, const git_diff_hunk *hunk,
  25. const git_diff_line *line, void *payload) -> int
  26. {
  27. Q_UNUSED(hunk)
  28. QString prefix("<font color=\"%1\">%2");
  29. QString suffix("</font><br/>");
  30. GitDiff* diff = static_cast<GitDiff*>(payload);
  31. QString fileName(delta->new_file.path);
  32. if(line->origin == GIT_DIFF_LINE_FILE_HDR) {
  33. return 0;
  34. }
  35. switch(line->origin) {
  36. case GIT_DIFF_LINE_ADDITION:
  37. prefix = prefix.arg("#00ff00");
  38. break;
  39. case GIT_DIFF_LINE_DELETION:
  40. prefix = prefix.arg("#ff0000");
  41. break;
  42. case GIT_DIFF_LINE_HUNK_HDR:
  43. prefix = "<br/><b>";
  44. suffix = "</b><br/>";
  45. break;
  46. default:
  47. prefix = prefix.arg("#000000").arg("&nbsp;");
  48. break;
  49. }
  50. if ( line->origin == GIT_DIFF_LINE_ADDITION ||
  51. line->origin == GIT_DIFF_LINE_DELETION) {
  52. prefix = prefix.arg(line->origin);
  53. }
  54. diff->m_diffList[fileName].append(prefix);
  55. diff->m_diffList[fileName].append(QString::fromUtf8(line->content, line->content_len).toHtmlEscaped().replace(" ", "&nbsp;"));
  56. diff->m_diffList[fileName].append(suffix);
  57. return 0;
  58. }, this);
  59. git_diff_free(diff);
  60. git_tree_free(a_tree);
  61. git_tree_free(b_tree);
  62. }
  63. void GitDiff::reset()
  64. {
  65. m_diffList.clear();
  66. }
  67. QStringList GitDiff::files()
  68. {
  69. return m_diffList.keys();
  70. }
  71. QString GitDiff::unified(const QString& file)
  72. {
  73. return m_diffList.value(file);
  74. }