-
Notifications
You must be signed in to change notification settings - Fork 66
/
git.cpp
3101 lines (2426 loc) · 97.4 KB
/
git.cpp
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Description: interface to git programs
Author: Marco Costalba (C) 2005-2007
Copyright: See COPYING file that comes with this distribution
*/
#include <QApplication>
#include <QDir>
#include <QFile>
#include <QImageReader>
#include <QPalette>
#include <QRegExp>
//#include <QSet> //CT TODO remove
#include <QSettings>
#include <QTextCodec>
#include <QTextDocument>
#include <QTextStream>
#include "FileHistory.h"
#include "annotate.h"
#include "cache.h"
#include "dataloader.h"
#include "git.h"
#include "lanes.h"
#include "myprocess.h"
#include "rangeselectimpl.h"
#define SHOW_MSG(x) QApplication::postEvent(parent(), new MessageEvent(x)); EM_PROCESS_EVENTS_NO_INPUT;
#define GIT_LOG_FORMAT "%m%HX%PX%n%cn<%ce>%n%an<%ae>%n%at%n%s%n"
// Used on init() for reading parameters once;
// It's OK to be unique among qgit windows.
static bool startup = true;
using namespace QGit;
// ****************************************************************************
bool Git::TreeEntry::operator<(const TreeEntry& te) const {
if (this->type == te.type)
return( this->name.localeAwareCompare( te.name ) < 0 );
// directories are smaller then files
// to appear as first when sorted
if (this->type == "tree")
return true;
if (te.type == "tree")
return false;
return( this->name.localeAwareCompare( te.name ) < 0 );
}
Git::Git(QObject* p) : QObject(p) {
EM_INIT(exGitStopped, "Stopping connection with git");
fileCacheAccessed = cacheNeedsUpdate = isMergeHead = false;
isStGIT = isGIT = loadingUnAppliedPatches = isTextHighlighterFound = false;
errorReportingEnabled = true; // report errors if run() fails
curDomain = NULL;
revData = NULL;
revsFiles.reserve(MAX_DICT_SIZE);
}
void Git::checkEnvironment() {
QString version;
if (run("git --version", &version)) {
version = version.section(' ', -1, -1).section('.', 0, 2);
if (version < GIT_VERSION) {
// simply send information, the 'not compatible version'
// policy should be implemented upstream
const QString cmd("Current git version is " + version +
" but is required " + GIT_VERSION + " or better");
const QString errorDesc("Your installed git is too old."
"\nPlease upgrade to avoid possible misbehaviours.");
MainExecErrorEvent* e = new MainExecErrorEvent(cmd, errorDesc);
QApplication::postEvent(parent(), e);
}
} else {
dbs("Cannot find git files");
return;
}
errorReportingEnabled = false;
isTextHighlighterFound = run("source-highlight -V", &version);
errorReportingEnabled = true;
if (isTextHighlighterFound)
textHighlighterVersionFound = version.section('\n', 0, 0);
else
textHighlighterVersionFound = "GNU source-highlight not installed";
}
void Git::userInfo(SList info) {
/*
git looks for commit user information in following order:
- GIT_AUTHOR_NAME and GIT_AUTHOR_EMAIL environment variables
- repository config file
- global config file
- your name, hostname and domain
*/
const QString env(QProcess::systemEnvironment().join(","));
QString user(env.section("GIT_AUTHOR_NAME", 1).section(",", 0, 0).section("=", 1).trimmed());
QString email(env.section("GIT_AUTHOR_EMAIL", 1).section(",", 0, 0).section("=", 1).trimmed());
info.clear();
info << "Environment" << user << email;
errorReportingEnabled = false; // 'git config' could fail, see docs
run("git config user.name", &user);
run("git config user.email", &email);
info << "Local config" << user << email;
run("git config --global user.name", &user);
run("git config --global user.email", &email);
info << "Global config" << user << email;
errorReportingEnabled = true;
}
const QStringList Git::getGitConfigList(bool global) {
QString runOutput;
errorReportingEnabled = false; // 'git config' could fail, see docs
if (global)
run("git config --global --list", &runOutput);
else
run("git config --list", &runOutput);
errorReportingEnabled = true;
return runOutput.split('\n', QString::SkipEmptyParts);
}
bool Git::isImageFile(SCRef file) {
const QString ext(file.section('.', -1).toLower());
return QImageReader::supportedImageFormats().contains(ext.toLatin1());
}
//CT TODO investigate if there is a better way of getting this (from git e.g.)
bool Git::isBinaryFile(SCRef file) {
static const char* binaryFileExtensions[] = {"bmp", "gif", "jpeg", "jpg",
"png", "svg", "tiff", "pcx", "xcf", "xpm",
"bz", "bz2", "rar", "tar", "z", "gz", "tgz", "zip", 0};
if (isImageFile(file))
return true;
const QString ext(file.section('.', -1).toLower());
int i = 0;
while (binaryFileExtensions[i] != 0)
if (ext == binaryFileExtensions[i++])
return true;
return false;
}
void Git::setThrowOnStop(bool b) {
if (b)
EM_REGISTER(exGitStopped);
else
EM_REMOVE(exGitStopped);
}
bool Git::isThrowOnStopRaised(int excpId, SCRef curContext) {
return EM_MATCH(excpId, exGitStopped, curContext);
}
void Git::setTextCodec(QTextCodec* tc) {
QTextCodec::setCodecForLocale(tc);
QString name(tc ? tc->name() : "Latin1");
// workaround Qt issue of mime name different from
// standard http://www.iana.org/assignments/character-sets
if (name == "Big5-HKSCS")
name = "Big5";
bool dummy;
if (tc != getTextCodec(&dummy))
run("git config i18n.commitencoding " + name);
}
QTextCodec* Git::getTextCodec(bool* isGitArchive) {
*isGitArchive = isGIT;
if (!isGIT) // can be called also when not in an archive
return NULL;
QString runOutput;
if (!run("git config i18n.commitencoding", &runOutput))
return NULL;
if (runOutput.isEmpty()) // git docs says default is utf-8
return QTextCodec::codecForName(QByteArray("utf8"));
return QTextCodec::codecForName(runOutput.trimmed().toLatin1());
}
//CT TODO utility function; can go elsewhere
const QString Git::quote(SCRef nm) {
return (QUOTE_CHAR + nm + QUOTE_CHAR);
}
//CT TODO utility function; can go elsewhere
const QString Git::quote(SCList sl) {
QString q(sl.join(QUOTE_CHAR + ' ' + QUOTE_CHAR));
q.prepend(QUOTE_CHAR).append(QUOTE_CHAR);
return q;
}
uint Git::checkRef(const ShaString& sha, uint mask) const {
RefMap::const_iterator it(refsShaMap.constFind(sha));
return (it != refsShaMap.constEnd() ? (*it).type & mask : 0);
}
uint Git::checkRef(SCRef sha, uint mask) const {
RefMap::const_iterator it(refsShaMap.constFind(toTempSha(sha)));
return (it != refsShaMap.constEnd() ? (*it).type & mask : 0);
}
const QStringList Git::getRefNames(SCRef sha, uint mask) const {
QStringList result;
if (!checkRef(sha, mask))
return result;
const Reference& rf = refsShaMap[toTempSha(sha)];
if (mask & TAG)
result << rf.tags;
if (mask & BRANCH)
result << rf.branches;
if (mask & RMT_BRANCH)
result << rf.remoteBranches;
if (mask & REF)
result << rf.refs;
if (mask == APPLIED || mask == UN_APPLIED)
result << QStringList(rf.stgitPatch);
return result;
}
const QStringList Git::getAllRefSha(uint mask) {
QStringList shas;
FOREACH (RefMap, it, refsShaMap)
if ((*it).type & mask)
shas.append(it.key());
return shas;
}
const QString Git::getRefSha(SCRef refName, RefType type, bool askGit) {
bool any = (type == ANY_REF);
FOREACH (RefMap, it, refsShaMap) {
const Reference& rf = *it;
if ((any || type == TAG) && rf.tags.contains(refName))
return it.key();
else if ((any || type == BRANCH) && rf.branches.contains(refName))
return it.key();
else if ((any || type == RMT_BRANCH) && rf.remoteBranches.contains(refName))
return it.key();
else if ((any || type == REF) && rf.refs.contains(refName))
return it.key();
else if ((any || type == APPLIED || type == UN_APPLIED) && rf.stgitPatch == refName)
return it.key();
}
if (!askGit)
return "";
// if a ref was not found perhaps is an abbreviated form
QString runOutput;
errorReportingEnabled = false;
bool ok = run("git rev-parse --revs-only " + refName, &runOutput);
errorReportingEnabled = true;
return (ok ? runOutput.trimmed() : "");
}
void Git::appendNamesWithId(QStringList& names, SCRef sha, SCList data, bool onlyLoaded) {
const Rev* r = revLookup(sha);
if (onlyLoaded && !r)
return;
if (onlyLoaded) { // prepare for later sorting
SCRef cap = QString("%1 ").arg(r->orderIdx, 6);
FOREACH_SL (it, data)
names.append(cap + *it);
} else
names += data;
}
const QStringList Git::getAllRefNames(uint mask, bool onlyLoaded) {
// returns reference names sorted by loading order if 'onlyLoaded' is set
QStringList names;
FOREACH (RefMap, it, refsShaMap) {
if (mask & TAG)
appendNamesWithId(names, it.key(), (*it).tags, onlyLoaded);
if (mask & BRANCH)
appendNamesWithId(names, it.key(), (*it).branches, onlyLoaded);
if (mask & RMT_BRANCH)
appendNamesWithId(names, it.key(), (*it).remoteBranches, onlyLoaded);
if (mask & REF)
appendNamesWithId(names, it.key(), (*it).refs, onlyLoaded);
if ((mask & (APPLIED | UN_APPLIED)) && !onlyLoaded)
names.append((*it).stgitPatch); // doesn't work with 'onlyLoaded'
}
if (onlyLoaded) {
names.sort();
QStringList::iterator itN(names.begin());
for ( ; itN != names.end(); ++itN) // strip 'idx'
(*itN) = (*itN).section(' ', -1, -1);
}
return names;
}
const QString Git::getRevInfo(SCRef sha) {
if (sha.isEmpty())
return "";
uint type = checkRef(sha);
if (type == 0)
return "";
QString refsInfo;
if (type & BRANCH) {
const QString cap(type & CUR_BRANCH ? "HEAD: " : "Branch: ");
refsInfo = cap + getRefNames(sha, BRANCH).join(" ");
}
if (type & RMT_BRANCH)
refsInfo.append(" Remote branch: " + getRefNames(sha, RMT_BRANCH).join(" "));
if (type & TAG)
refsInfo.append(" Tag: " + getRefNames(sha, TAG).join(" "));
if (type & REF)
refsInfo.append(" Ref: " + getRefNames(sha, REF).join(" "));
if (type & APPLIED)
refsInfo.append(" Patch: " + getRefNames(sha, APPLIED).join(" "));
if (type & UN_APPLIED)
refsInfo.append(" Patch: " + getRefNames(sha, UN_APPLIED).join(" "));
if (type & TAG) {
SCRef msg(getTagMsg(sha));
if (!msg.isEmpty())
refsInfo.append(" [" + msg + "]");
}
return refsInfo.trimmed();
}
const QString Git::getTagMsg(SCRef sha) {
if (!checkRef(sha, TAG)) {
dbs("ASSERT in Git::getTagMsg, tag not found");
return "";
}
Reference& rf = refsShaMap[toTempSha(sha)];
if (!rf.tagMsg.isEmpty())
return rf.tagMsg;
QRegExp pgp("-----BEGIN PGP SIGNATURE*END PGP SIGNATURE-----",
Qt::CaseSensitive, QRegExp::Wildcard);
if (!rf.tagObj.isEmpty()) {
QString ro;
if (run("git cat-file tag " + rf.tagObj, &ro))
rf.tagMsg = ro.section("\n\n", 1).remove(pgp).trimmed();
}
return rf.tagMsg;
}
bool Git::isPatchName(SCRef nm) {
if (!getRefSha(nm, UN_APPLIED, false).isEmpty())
return true;
return !getRefSha(nm, APPLIED, false).isEmpty();
}
void Git::addExtraFileInfo(QString* rowName, SCRef sha, SCRef diffToSha, bool allMergeFiles) {
const RevFile* files = getFiles(sha, diffToSha, allMergeFiles);
if (!files)
return;
int idx = findFileIndex(*files, *rowName);
if (idx == -1)
return;
QString extSt(files->extendedStatus(idx));
if (extSt.isEmpty())
return;
*rowName = extSt;
}
void Git::removeExtraFileInfo(QString* rowName) {
if (rowName->contains(" --> ")) // return destination file name
*rowName = rowName->section(" --> ", 1, 1).section(" (", 0, 0);
}
void Git::formatPatchFileHeader(QString* rowName, SCRef sha, SCRef diffToSha,
bool combined, bool allMergeFiles) {
if (combined) {
rowName->prepend("diff --combined ");
return; // TODO rename/copy still not supported in this case
}
// let's see if it's a rename/copy...
addExtraFileInfo(rowName, sha, diffToSha, allMergeFiles);
if (rowName->contains(" --> ")) { // ...it is!
SCRef destFile(rowName->section(" --> ", 1, 1).section(" (", 0, 0));
SCRef origFile(rowName->section(" --> ", 0, 0));
*rowName = "diff --git a/" + origFile + " b/" + destFile;
} else
*rowName = "diff --git a/" + *rowName + " b/" + *rowName;
}
Annotate* Git::startAnnotate(FileHistory* fh, QObject* guiObj) { // non blocking
Annotate* ann = new Annotate(this, guiObj);
if (!ann->start(fh)) // non blocking call
return NULL; // ann will delete itself when done
return ann; // caller will delete with Git::cancelAnnotate()
}
void Git::cancelAnnotate(Annotate* ann) {
if (ann)
ann->deleteWhenDone();
}
const FileAnnotation* Git::lookupAnnotation(Annotate* ann, SCRef sha) {
return (ann ? ann->lookupAnnotation(sha) : NULL);
}
void Git::cancelDataLoading(const FileHistory* fh) {
// normally called when closing file viewer
emit cancelLoading(fh); // non blocking
}
const Rev* Git::revLookup(SCRef sha, const FileHistory* fh) const {
return revLookup(toTempSha(sha), fh);
}
const Rev* Git::revLookup(const ShaString& sha, const FileHistory* fh) const {
const RevMap& r = (fh ? fh->revs : revData->revs);
return (sha.latin1() ? r.value(sha) : NULL);
}
bool Git::run(SCRef runCmd, QString* runOutput, QObject* receiver, SCRef buf) {
QByteArray ba;
bool ret = run(runOutput ? &ba : NULL, runCmd, receiver, buf);
if (runOutput)
*runOutput = ba;
return ret;
}
bool Git::run(QByteArray* runOutput, SCRef runCmd, QObject* receiver, SCRef buf) {
MyProcess p(parent(), this, workDir, errorReportingEnabled);
return p.runSync(runCmd, runOutput, receiver, buf);
}
MyProcess* Git::runAsync(SCRef runCmd, QObject* receiver, SCRef buf) {
MyProcess* p = new MyProcess(parent(), this, workDir, errorReportingEnabled);
if (!p->runAsync(runCmd, receiver, buf)) {
delete p;
p = NULL;
}
return p; // auto-deleted when done
}
MyProcess* Git::runAsScript(SCRef runCmd, QObject* receiver, SCRef buf) {
const QString scriptFile(workDir + "/qgit_script" + QGit::SCRIPT_EXT);
#ifndef Q_OS_WIN32
// without this process doesn't start under Linux
QString cmd(runCmd.startsWith("#!") ? runCmd : "#!/bin/sh\n" + runCmd);
#else
QString cmd(runCmd);
#endif
if (!writeToFile(scriptFile, cmd, true))
return NULL;
MyProcess* p = runAsync(scriptFile, receiver, buf);
if (p)
connect(p, SIGNAL(eof()), this, SLOT(on_runAsScript_eof()));
return p;
}
void Git::on_runAsScript_eof() {
QDir dir(workDir);
dir.remove("qgit_script" + QGit::SCRIPT_EXT);
}
void Git::cancelProcess(MyProcess* p) {
if (p)
p->on_cancel(); // non blocking call
}
int Git::findFileIndex(const RevFile& rf, SCRef name) {
if (name.isEmpty())
return -1;
int idx = name.lastIndexOf('/') + 1;
SCRef dr = name.left(idx);
SCRef nm = name.mid(idx);
for (uint i = 0, cnt = rf.count(); i < cnt; ++i) {
if (fileNamesVec[rf.nameAt(i)] == nm && dirNamesVec[rf.dirAt(i)] == dr)
return i;
}
return -1;
}
const QString Git::getLaneParent(SCRef fromSHA, int laneNum) {
const Rev* rs = revLookup(fromSHA);
if (!rs)
return "";
for (int idx = rs->orderIdx - 1; idx >= 0; idx--) {
const Rev* r = revLookup(revData->revOrder[idx]);
if (laneNum >= r->lanes.count())
return "";
if (!isFreeLane(r->lanes[laneNum])) {
int type = r->lanes[laneNum], parNum = 0;
while (!isMerge(type) && type != ACTIVE) {
if (isHead(type))
parNum++;
type = r->lanes[--laneNum];
}
return r->parent(parNum);
}
}
return "";
}
const QStringList Git::getChildren(SCRef parent) {
QStringList children;
const Rev* r = revLookup(parent);
if (!r)
return children;
for (int i = 0; i < r->children.count(); i++)
children.append(revData->revOrder[r->children[i]]);
// reorder children by loading order
QStringList::iterator itC(children.begin());
for ( ; itC != children.end(); ++itC) {
const Rev* r = revLookup(*itC);
(*itC).prepend(QString("%1 ").arg(r->orderIdx, 6));
}
children.sort();
for (itC = children.begin(); itC != children.end(); ++itC)
(*itC) = (*itC).section(' ', -1, -1);
return children;
}
const QString Git::getShortLog(SCRef sha) {
const Rev* r = revLookup(sha);
return (r ? r->shortLog() : "");
}
MyProcess* Git::getDiff(SCRef sha, QObject* receiver, SCRef diffToSha, bool combined) {
if (sha.isEmpty())
return NULL;
QString runCmd;
if (sha != ZERO_SHA) {
runCmd = "git diff-tree --no-color -r --patch-with-stat ";
runCmd.append(combined ? "-c " : "-C -m "); // TODO rename for combined
const Rev* r = revLookup(sha);
if (r->parentsCount() == 0)
runCmd.append("--root ");
runCmd.append(diffToSha + " " + sha); // diffToSha could be empty
} else
runCmd = "git diff-index --no-color -r -m --patch-with-stat HEAD";
return runAsync(runCmd, receiver);
}
const QString Git::getWorkDirDiff(SCRef fileName) {
QString runCmd("git diff-index --no-color -r -z -m -p --full-index --no-commit-id HEAD"), runOutput;
if (!fileName.isEmpty())
runCmd.append(" -- " + quote(fileName));
if (!run(runCmd, &runOutput))
return "";
/* For unknown reasons file sha of index is not ZERO_SHA but
a value of unknown origin.
Replace that with ZERO_SHA so to not fool annotate
*/
int idx = runOutput.indexOf("..");
if (idx != -1)
runOutput.replace(idx + 2, 40, ZERO_SHA);
return runOutput;
}
const QString Git::getFileSha(SCRef file, SCRef revSha) {
if (revSha == ZERO_SHA) {
QStringList files, dummy;
getWorkDirFiles(files, dummy, RevFile::ANY);
if (files.contains(file))
return ZERO_SHA; // it is unknown to git
}
const QString sha(revSha == ZERO_SHA ? "HEAD" : revSha);
QString runCmd("git ls-tree -r " + sha + " " + quote(file)), runOutput;
if (!run(runCmd, &runOutput))
return "";
return runOutput.mid(12, 40); // could be empty, deleted file case
}
MyProcess* Git::getFile(SCRef fileSha, QObject* receiver, QByteArray* result, SCRef fileName) {
QString runCmd;
/*
symlinks in git are one line files with just the name of the target,
not the target content. Instead 'cat' command resolves symlinks and
returns target content. So we use 'cat' only if the file is modified
in working directory, to let annotation work for changed files, otherwise
we go with a safe 'git cat-file blob HEAD' instead.
NOTE: This fails if the modified file is a new symlink, converted
from an old plain file. In this case annotation will fail until
change is committed.
*/
if (fileSha == ZERO_SHA)
#ifdef Q_OS_WIN32
{
QString winPath = quote(fileName);
winPath.replace("/", "\\");
runCmd = "type " + winPath;
}
#else
runCmd = "cat " + quote(fileName);
#endif
else {
if (fileSha.isEmpty()) // deleted
runCmd = "git diff-tree HEAD HEAD"; // fake an empty file reading
else
runCmd = "git cat-file blob " + fileSha;
}
if (!receiver) {
run(result, runCmd);
return NULL; // in case of sync call we ignore run() return value
}
return runAsync(runCmd, receiver);
}
MyProcess* Git::getHighlightedFile(SCRef fileSha, QObject* receiver, QString* result, SCRef fileName) {
if (!isTextHighlighter()) {
dbs("ASSERT in getHighlightedFile: highlighter not found");
return NULL;
}
QString ext(fileName.section('.', -1, -1, QString::SectionIncludeLeadingSep));
QString inputFile(workDir + "/qgit_hlght_input" + ext);
if (!saveFile(fileSha, fileName, inputFile))
return NULL;
QString runCmd("source-highlight --failsafe -f html -i " + quote(inputFile));
if (!receiver) {
run(runCmd, result);
on_getHighlightedFile_eof();
return NULL; // in case of sync call we ignore run() return value
}
MyProcess* p = runAsync(runCmd, receiver);
if (p)
connect(p, SIGNAL(eof()), this, SLOT(on_getHighlightedFile_eof()));
return p;
}
void Git::on_getHighlightedFile_eof() {
QDir dir(workDir);
const QStringList sl(dir.entryList(QStringList() << "qgit_hlght_input*"));
FOREACH_SL (it, sl)
dir.remove(*it);
}
bool Git::saveFile(SCRef fileSha, SCRef fileName, SCRef path) {
QByteArray fileData;
getFile(fileSha, NULL, &fileData, fileName); // sync call
if (isBinaryFile(fileName))
return writeToFile(path, fileData);
return writeToFile(path, QString(fileData));
}
bool Git::getTree(SCRef treeSha, TreeInfo& ti, bool isWorkingDir, SCRef path) {
QStringList deleted;
if (isWorkingDir) {
// retrieve unknown and deleted files under path
QStringList unknowns, dummy;
getWorkDirFiles(unknowns, dummy, RevFile::UNKNOWN);
FOREACH_SL (it, unknowns) {
// don't add files under other directories
QFileInfo f(*it);
SCRef d(f.dir().path());
if (d == path || (path.isEmpty() && d == ".")) {
TreeEntry te(f.fileName(), "", "?");
ti.append(te);
}
}
getWorkDirFiles(deleted, dummy, RevFile::DELETED);
}
// if needed fake a working directory tree starting from HEAD tree
QString runOutput, tree(treeSha);
if (treeSha == ZERO_SHA) {
// HEAD could be empty for just init'ed repositories
if (!run("git rev-parse --revs-only HEAD", &tree))
return false;
tree = tree.trimmed();
}
if (!tree.isEmpty() && !run("git ls-tree " + tree, &runOutput))
return false;
const QStringList sl(runOutput.split('\n', QString::SkipEmptyParts));
FOREACH_SL (it, sl) {
// append any not deleted file
SCRef fn((*it).section('\t', 1, 1));
SCRef fp(path.isEmpty() ? fn : path + '/' + fn);
if (deleted.empty() || (deleted.indexOf(fp) == -1)) {
TreeEntry te(fn, (*it).mid(12, 40), (*it).mid(7, 4));
ti.append(te);
}
}
qSort(ti); // list directories before files
return true;
}
void Git::getWorkDirFiles(SList files, SList dirs, RevFile::StatusFlag status) {
files.clear();
dirs.clear();
const RevFile* f = getFiles(ZERO_SHA);
if (!f)
return;
for (int i = 0; i < f->count(); i++) {
if (f->statusCmp(i, status)) {
SCRef fp(filePath(*f, i));
files.append(fp);
for (int j = 0, cnt = fp.count('/'); j < cnt; j++) {
SCRef dir(fp.section('/', 0, j));
if (dirs.indexOf(dir) == -1)
dirs.append(dir);
}
}
}
}
bool Git::isNothingToCommit() {
if (!revsFiles.contains(ZERO_SHA_RAW))
return true;
const RevFile* rf = revsFiles[ZERO_SHA_RAW];
return (rf->count() == workingDirInfo.otherFiles.count());
}
bool Git::isTreeModified(SCRef sha) {
const RevFile* f = getFiles(sha);
if (!f)
return true; // no files info, stay on the safe side
for (int i = 0; i < f->count(); ++i)
if (!f->statusCmp(i, RevFile::MODIFIED))
return true;
return false;
}
bool Git::isParentOf(SCRef par, SCRef child) {
const Rev* c = revLookup(child);
return (c && c->parentsCount() == 1 && QString(c->parent(0)) == par); // no merges
}
bool Git::isContiguous(const QStringList &revs)
{
if (revs.count() == 1) return true;
for (QStringList::const_iterator it=revs.begin(), end=revs.end()-1; it!=end; ++it) {
const Rev* c = revLookup(*it);
if (!c->parents().contains(*(it+1))) return false;
}
return true;
}
bool Git::isSameFiles(SCRef tree1Sha, SCRef tree2Sha) {
// early skip common case of browsing with up and down arrows, i.e.
// going from parent(child) to child(parent). In this case we can
// check RevFileMap and skip a costly 'git diff-tree' call.
if (isParentOf(tree1Sha, tree2Sha))
return !isTreeModified(tree2Sha);
if (isParentOf(tree2Sha, tree1Sha))
return !isTreeModified(tree1Sha);
const QString runCmd("git diff-tree --no-color -r " + tree1Sha + " " + tree2Sha);
QString runOutput;
if (!run(runCmd, &runOutput))
return false;
bool isChanged = (runOutput.indexOf(" A\t") != -1 || runOutput.indexOf(" D\t") != -1);
return !isChanged;
}
const QStringList Git::getDescendantBranches(SCRef sha, bool shaOnly) {
QStringList tl;
const Rev* r = revLookup(sha);
if (!r || (r->descBrnMaster == -1))
return tl;
const QVector<int>& nr = revLookup(revData->revOrder[r->descBrnMaster])->descBranches;
for (int i = 0; i < nr.count(); i++) {
const ShaString& sha = revData->revOrder[nr[i]];
if (shaOnly) {
tl.append(sha);
continue;
}
SCRef cap = " (" + sha + ") ";
RefMap::const_iterator it(refsShaMap.find(sha));
if (it == refsShaMap.constEnd())
continue;
if (!(*it).branches.empty())
tl.append((*it).branches.join(" ").append(cap));
if (!(*it).remoteBranches.empty())
tl.append((*it).remoteBranches.join(" ").append(cap));
}
return tl;
}
const QStringList Git::getNearTags(bool goDown, SCRef sha) {
QStringList tl;
const Rev* r = revLookup(sha);
if (!r)
return tl;
int nearRefsMaster = (goDown ? r->descRefsMaster : r->ancRefsMaster);
if (nearRefsMaster == -1)
return tl;
const QVector<int>& nr = goDown ? revLookup(revData->revOrder[nearRefsMaster])->descRefs :
revLookup(revData->revOrder[nearRefsMaster])->ancRefs;
for (int i = 0; i < nr.count(); i++) {
const ShaString& sha = revData->revOrder[nr[i]];
SCRef cap = " (" + sha + ")";
RefMap::const_iterator it(refsShaMap.find(sha));
if (it != refsShaMap.constEnd())
tl.append((*it).tags.join(cap).append(cap));
}
return tl;
}
const QString Git::getLastCommitMsg() {
// FIXME: Make sure the amend action is not called when there is
// nothing to amend. That is in empty repository or over StGit stack
// with nothing applied.
QString sha;
QString top;
if (run("git rev-parse --verify HEAD", &top))
sha = top.trimmed();
else {
dbs("ASSERT: getLastCommitMsg head is not valid");
return "";
}
const Rev* c = revLookup(sha);
if (!c) {
dbp("ASSERT: getLastCommitMsg sha <%1> not found", sha);
return "";
}
return c->shortLog() + "\n\n" + c->longLog().trimmed();
}
const QString Git::getNewCommitMsg() {
const Rev* c = revLookup(ZERO_SHA);
if (!c) {
dbs("ASSERT: getNewCommitMsg zero_sha not found");
return "";
}
QString status = c->longLog();
status.prepend('\n').replace(QRegExp("\\n([^#\\n]?)"), "\n#\\1"); // comment all the lines
if (isMergeHead) {
QFile file(QDir(gitDir).absoluteFilePath("MERGE_MSG"));
if (file.open(QIODevice::ReadOnly)) {
QTextStream in(&file);
while(!in.atEnd())
status.prepend(in.readLine());
file.close();
}
}
return status;
}
//CT TODO utility function; can go elsewhere
const QString Git::colorMatch(SCRef txt, QRegExp& regExp) {