githandler.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #include "githandler.h"
  2. #include <QDebug>
  3. #include <QUrl>
  4. #include <qqml.h>
  5. #include <gitrepository.h>
  6. #include <gitbranch.h>
  7. #include <commitmodel.h>
  8. #include <git2.h>
  9. #include <commitgraph.h>
  10. GitHandler::GitHandler() : QObject()
  11. ,m_repositories(new RepositoryModel(this))
  12. {
  13. git_libgit2_init();
  14. }
  15. GitHandler::~GitHandler()
  16. {
  17. git_libgit2_shutdown();
  18. }
  19. void GitHandler::open(const QUrl &url)
  20. {
  21. if(url.isLocalFile()) {
  22. open(url.toLocalFile());
  23. }
  24. }
  25. void GitHandler::open(const QString &path)
  26. {
  27. git_buf root = {0,0,0};
  28. if(git_repository_discover(&root, path.toUtf8().data(), 0, NULL) != 0) {
  29. qDebug() << lastError();
  30. return;
  31. }
  32. GitRepository* repo = new GitRepository(QString::fromUtf8(root.ptr, root.size));
  33. if(!repo->isValid()) {
  34. qDebug() << lastError();
  35. return;
  36. }
  37. BranchContainer &branches = repo->branches();
  38. CommitGraph* graph = new CommitGraph();
  39. graph->addHead(branches.value("master").data()->oid());
  40. foreach(GitBranch* branch, branches) {
  41. qDebug() << "Next head " << branch->name();
  42. graph->addHead(branch->oid());
  43. }
  44. foreach (GitCommit* commit, graph->m_fullList) {
  45. qDebug() << commit->sha1();
  46. commit->m_y = graph->m_fullList.indexOf(commit);
  47. }
  48. CommitModel* main = new CommitModel("main");
  49. foreach (GitCommit* commitPtr, graph->m_commits) {
  50. main->add(commitPtr);
  51. }
  52. m_commits.insert("main", main);
  53. m_repositories->add(repo);
  54. }
  55. CommitModel* GitHandler::modelByHead(const QString& head)
  56. {
  57. return m_commits.value(head).data();
  58. }
  59. QString GitHandler::lastError() const
  60. {
  61. const git_error *e = giterr_last();
  62. if(e) {
  63. return QString("(%1): %2").arg(e->klass).arg(e->message);
  64. giterr_clear();
  65. }
  66. giterr_clear();
  67. return QString();
  68. }