1#include "GitBase.h"
2
3#include <GitAsyncProcess.h>
4#include <GitSyncProcess.h>
5
6#include <QLogger.h>
7
8using namespace QLogger;
9
10#include <QDir>
11#include <QFileInfo>
12
13GitBase::GitBase(const QString &workingDirectory)
14 : mWorkingDirectory(workingDirectory)
15 , mGitDirectory(mWorkingDirectory + "/.git")
16{
17 QFileInfo fileInfo(mGitDirectory);
18
19 if (fileInfo.isFile())
20 {
21 QFile f(fileInfo.filePath());
22
23 if (f.open(QIODevice::ReadOnly))
24 {
25 auto path = f.readAll().split(':').last().trimmed();
26 mGitDirectory = mWorkingDirectory + "/" + path;
27 f.close();
28 }
29 }
30}
31
32QString GitBase::getWorkingDir() const
33{
34 return mWorkingDirectory;
35}
36
37void GitBase::setWorkingDir(const QString &workingDir)
38{
39 mWorkingDirectory = workingDir;
40}
41
42QString GitBase::getGitDir() const
43{
44 return mGitDirectory;
45}
46
47GitExecResult GitBase::run(const QString &cmd) const
48{
49 GitSyncProcess p(mWorkingDirectory);
50
51 const auto ret = p.run(cmd);
52 const auto runOutput = ret.output;
53
54 if (ret.success && runOutput.contains("fatal:"))
55 QLog_Info("Git", QString("Git command {%1} reported issues:\n%2").arg(cmd, runOutput));
56 else if (!ret.success)
57 QLog_Warning("Git", QString("Git command {%1} has errors:\n%2").arg(cmd, runOutput));
58
59 return ret;
60}
61
62void GitBase::updateCurrentBranch()
63{
64 QLog_Trace("Git", "Updating the cached current branch");
65
66 const auto cmd = QString("git rev-parse --abbrev-ref HEAD");
67
68 QLog_Trace("Git", QString("Updating the cached current branch: {%1}").arg(cmd));
69
70 const auto ret = run(cmd);
71
72 mCurrentBranch = ret.success ? ret.output.trimmed().remove("heads/") : QString();
73}
74
75QString GitBase::getCurrentBranch()
76{
77 if (mCurrentBranch.isEmpty())
78 updateCurrentBranch();
79
80 return mCurrentBranch;
81}
82
83GitExecResult GitBase::getLastCommit() const
84{
85 QLog_Trace("Git", "Getting last commit");
86
87 const auto cmd = QString("git rev-parse HEAD");
88
89 QLog_Trace("Git", QString("Getting last commit: {%1}").arg(cmd));
90
91 const auto ret = run(cmd);
92
93 return ret;
94}
95