-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGitService.cpp
More file actions
414 lines (354 loc) · 11.9 KB
/
Copy pathGitService.cpp
File metadata and controls
414 lines (354 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
#include "git/GitService.h"
#include "settings/SettingsService.h"
#include "tools/ProcessRunner.h"
#include <QDir>
#include <QFileInfo>
#include <QProcess>
#include <QStandardPaths>
#include <QTimer>
namespace cold {
GitService::GitService(SettingsService& settings, QObject* parent)
: QObject(parent), m_settings(settings), m_runner(new ProcessRunner(this)),
m_refreshDebounce(new QTimer(this)) {
m_refreshDebounce->setSingleShot(true);
m_refreshDebounce->setInterval(kDebounceMs);
connect(m_refreshDebounce, &QTimer::timeout, this, &GitService::onDebounceTimeout);
connect(m_runner, &ProcessRunner::outputLine, this, &GitService::onOutputLine);
connect(m_runner, &ProcessRunner::finished, this, &GitService::onProcessFinished);
connect(m_runner, &ProcessRunner::failed, this, &GitService::onProcessFailed);
}
GitService::~GitService() {
if (m_runner && m_runner->isRunning()) {
m_runner->cancel();
}
}
void GitService::initialize() {
m_runner->initialize();
}
bool GitService::isRepository() const {
return m_isRepo;
}
const QHash<QString, GitStatus>& GitService::statusMap() const {
return m_status;
}
QString GitService::gitExecutable() const {
QString path = m_settings.toolPath(QStringLiteral("git"));
if (path.isEmpty()) {
path = QStandardPaths::findExecutable(QStringLiteral("git"));
}
return path;
}
void GitService::detectRepository() {
const bool wasRepo = m_isRepo;
m_isRepo = false;
if (m_projectRoot.isEmpty()) {
if (wasRepo) {
emit repositoryChanged(false);
}
return;
}
const QDir gitDir(m_projectRoot + QStringLiteral("/.git"));
if (gitDir.exists()) {
m_isRepo = true;
} else {
const QString gitPath = gitExecutable();
if (!gitPath.isEmpty()) {
QProcess proc;
proc.setProgram(gitPath);
proc.setArguments({QStringLiteral("-C"), m_projectRoot, QStringLiteral("rev-parse"),
QStringLiteral("--is-inside-work-tree")});
proc.start();
if (proc.waitForFinished(2000) && proc.exitCode() == 0) {
const QByteArray out = proc.readAllStandardOutput().trimmed();
m_isRepo = (out == "true");
}
}
}
if (wasRepo != m_isRepo) {
emit repositoryChanged(m_isRepo);
}
}
void GitService::setProjectRoot(const QString& root) {
m_projectRoot = QFileInfo(root).canonicalFilePath();
if (m_projectRoot.isEmpty() && !root.isEmpty()) {
m_projectRoot = QFileInfo(root).absoluteFilePath();
}
detectRepository();
scheduleRefresh();
}
void GitService::clearProject() {
m_refreshDebounce->stop();
m_runner->cancel();
m_projectRoot.clear();
m_isRepo = false;
m_status.clear();
m_pendingOp = GitPendingOp::None;
m_stdoutAccum.clear();
setBusy(false);
emit repositoryChanged(false);
emit statusUpdated(m_status);
}
void GitService::scheduleRefresh() {
if (!m_isRepo || m_projectRoot.isEmpty()) {
return;
}
m_refreshDebounce->start();
}
void GitService::refreshNow() {
if (!m_isRepo || m_projectRoot.isEmpty()) {
return;
}
const QString gitPath = gitExecutable();
if (gitPath.isEmpty()) {
emit gitError(QStringLiteral("git not found — install git or set tool path"));
return;
}
m_refreshDebounce->stop();
startOp(GitPendingOp::Status, {QStringLiteral("status"), QStringLiteral("--porcelain")});
}
void GitService::requestDiff(const QString& path) {
if (!m_isRepo || path.isEmpty()) {
return;
}
const QString gitPath = gitExecutable();
if (gitPath.isEmpty()) {
emit gitError(QStringLiteral("git not found — install git or set tool path"));
return;
}
m_diffPath = QFileInfo(path).canonicalFilePath();
if (m_diffPath.isEmpty()) {
m_diffPath = QFileInfo(path).absoluteFilePath();
}
QString relative = QDir(m_projectRoot).relativeFilePath(m_diffPath);
if (relative.startsWith(QLatin1String(".."))) {
emit gitError(QStringLiteral("File is outside the project"));
return;
}
GitStatus fileStatus = m_status.value(m_diffPath, GitStatus::None);
QStringList args;
if (fileStatus == GitStatus::Untracked) {
args = {QStringLiteral("diff"), QStringLiteral("--no-index"), QStringLiteral("--no-color"),
QStringLiteral("/dev/null"), relative};
} else {
args = {QStringLiteral("diff"), QStringLiteral("--no-color"), QStringLiteral("--"),
relative};
}
startOp(GitPendingOp::Diff, args);
}
void GitService::stagePaths(const QStringList& paths) {
if (!m_isRepo || paths.isEmpty()) {
return;
}
const QString gitPath = gitExecutable();
if (gitPath.isEmpty()) {
emit gitError(QStringLiteral("git not found — install git or set tool path"));
return;
}
m_stagePaths = paths;
QStringList args = {QStringLiteral("add"), QStringLiteral("--")};
for (const QString& path : paths) {
QString relative = QDir(m_projectRoot).relativeFilePath(path);
if (!relative.startsWith(QLatin1String(".."))) {
args.append(relative);
}
}
if (args.size() <= 2) {
return;
}
startOp(GitPendingOp::Add, args);
}
void GitService::commit(const QString& message) {
if (!m_isRepo || message.trimmed().isEmpty()) {
return;
}
const QString gitPath = gitExecutable();
if (gitPath.isEmpty()) {
emit gitError(QStringLiteral("git not found — install git or set tool path"));
return;
}
m_commitMessage = message;
startOp(GitPendingOp::Commit,
{QStringLiteral("commit"), QStringLiteral("-m"), message.trimmed()});
}
QStringList GitService::stagedPaths() const {
return m_stagedPaths;
}
void GitService::onDebounceTimeout() {
refreshNow();
}
void GitService::startOp(GitPendingOp op, const QStringList& args) {
const QString gitPath = gitExecutable();
if (gitPath.isEmpty()) {
emit gitError(QStringLiteral("git not found — install git or set tool path"));
return;
}
if (m_runner->isRunning()) {
m_runner->cancel();
}
m_stdoutAccum.clear();
m_pendingOp = op;
m_finishedOp = GitPendingOp::None;
setBusy(true);
QStringList fullArgs = {QStringLiteral("-C"), m_projectRoot};
fullArgs.append(args);
m_runner->start(gitPath, fullArgs, m_projectRoot);
}
void GitService::onOutputLine(OutputChannel channel, const QString& line) {
Q_UNUSED(channel);
if (m_pendingOp == GitPendingOp::None) {
return;
}
if (!m_stdoutAccum.isEmpty()) {
m_stdoutAccum += QLatin1Char('\n');
}
m_stdoutAccum += line;
}
void GitService::onProcessFinished(int exitCode) {
m_finishedOp = m_pendingOp;
finishOp(exitCode);
m_pendingOp = GitPendingOp::None;
setBusy(false);
}
void GitService::onProcessFailed(const QString& message) {
emit gitError(message);
m_pendingOp = GitPendingOp::None;
setBusy(false);
}
void GitService::finishOp(int exitCode) {
switch (m_finishedOp) {
case GitPendingOp::Status:
if (exitCode == 0) {
parseStatusOutput(m_stdoutAccum);
} else {
emit gitError(QStringLiteral("git status failed (exit %1)").arg(exitCode));
}
break;
case GitPendingOp::Diff:
if (exitCode == 0 || exitCode == 1) {
emit diffReady(m_diffPath, m_stdoutAccum);
} else {
emit gitError(QStringLiteral("git diff failed (exit %1)").arg(exitCode));
}
break;
case GitPendingOp::Add:
if (exitCode == 0) {
refreshNow();
} else {
emit gitError(QStringLiteral("git add failed (exit %1)").arg(exitCode));
}
break;
case GitPendingOp::Commit:
if (exitCode == 0) {
emit commitFinished(true, QStringLiteral("Committed successfully"));
refreshNow();
} else {
const QString err = m_stdoutAccum.isEmpty()
? QStringLiteral("git commit failed (exit %1)").arg(exitCode)
: m_stdoutAccum;
emit commitFinished(false, err);
emit gitError(err);
}
break;
default:
break;
}
m_stdoutAccum.clear();
}
void GitService::parseStatusOutput(const QString& output) {
m_stagedPaths.clear();
m_status = parsePorcelain(output, m_projectRoot, &m_stagedPaths);
emitStatus();
}
QHash<QString, GitStatus> GitService::parsePorcelain(const QString& output,
const QString& projectRoot,
QStringList* stagedOut) {
QHash<QString, GitStatus> result;
const QStringList lines = output.split(QLatin1Char('\n'), Qt::SkipEmptyParts);
for (QString line : lines) {
line = line.trimmed();
if (line.isEmpty()) {
continue;
}
GitStatus status = GitStatus::None;
QString relativePath;
QChar indexChar = QLatin1Char(' ');
if (line.startsWith(QStringLiteral("??"))) {
status = GitStatus::Untracked;
relativePath = line.mid(3).trimmed();
} else if (line.size() >= 3) {
indexChar = line.at(0);
const QChar worktree = line.at(1);
status = statusFromChars(indexChar, worktree);
relativePath = line.mid(3).trimmed();
const int arrow = relativePath.indexOf(QStringLiteral(" -> "));
if (arrow >= 0) {
relativePath = relativePath.mid(arrow + 4).trimmed();
}
if (relativePath.startsWith(QLatin1Char('"')) &&
relativePath.endsWith(QLatin1Char('"'))) {
relativePath = relativePath.mid(1, relativePath.size() - 2);
}
} else {
continue;
}
if (status == GitStatus::None || relativePath.isEmpty()) {
continue;
}
const QString key = resolvePathKey(projectRoot, relativePath);
const GitStatus existing = result.value(key, GitStatus::None);
if (gitStatusPriority(status) > gitStatusPriority(existing)) {
result.insert(key, status);
}
if (stagedOut && indexChar != QLatin1Char(' ') && indexChar != QLatin1Char('?') &&
!key.isEmpty()) {
if (!stagedOut->contains(key)) {
stagedOut->append(key);
}
}
}
if (stagedOut) {
stagedOut->sort();
}
return result;
}
GitStatus GitService::statusFromChars(QChar index, QChar worktree) {
auto charStatus = [](QChar c) -> GitStatus {
if (c == QLatin1Char('?')) {
return GitStatus::Untracked;
}
if (c == QLatin1Char('D')) {
return GitStatus::Deleted;
}
if (c == QLatin1Char('A')) {
return GitStatus::Added;
}
if (c == QLatin1Char('R')) {
return GitStatus::Renamed;
}
if (c == QLatin1Char('M') || c == QLatin1Char('T')) {
return GitStatus::Modified;
}
return GitStatus::None;
};
const GitStatus wi = charStatus(worktree);
const GitStatus idx = charStatus(index);
if (gitStatusPriority(wi) >= gitStatusPriority(idx)) {
return wi != GitStatus::None ? wi : idx;
}
return idx;
}
QString GitService::resolvePathKey(const QString& projectRoot, const QString& relativePath) {
const QString absolute = QDir(projectRoot).absoluteFilePath(relativePath);
const QString canonical = QFileInfo(absolute).canonicalFilePath();
return canonical.isEmpty() ? absolute : canonical;
}
void GitService::emitStatus() {
emit statusUpdated(m_status);
}
void GitService::setBusy(bool busy) {
if (m_busy != busy) {
m_busy = busy;
emit busyChanged(busy);
}
}
} // namespace cold