gitplugin.cpp 50.8 KB
Newer Older
1 2
/***************************************************************************
 *   Copyright 2008 Evgeniy Ivanov <powerfox@kde.ru>                       *
3
 *   Copyright 2009 Hugo Parente Lima <hugo.pl@gmail.com>                  *
4
 *   Copyright 2010 Aleix Pol Gonzalez <aleixpol@kde.org>                  *
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
 *                                                                         *
 *   This program is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU General Public License as        *
 *   published by the Free Software Foundation; either version 2 of        *
 *   the License or (at your option) version 3 or any later version        *
 *   accepted by the membership of KDE e.V. (or its successor approved     *
 *   by the membership of KDE e.V.), which shall act as a proxy            *
 *   defined in Section 14 of version 3 of the license.                    *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>. *
 ***************************************************************************/

#include "gitplugin.h"

#include <KPluginFactory>
#include <KPluginLoader>
27 28 29 30 31
#include <KLocalizedString>
#include <KAboutData>
#include <KDebug>
#include <QFileInfo>
#include <QDir>
32
#include <QDateTime>
33
#include <QFileSystemWatcher>
34
#include <QTimer>
35
#include <QTextCodec>
36

37 38
#include <interfaces/icore.h>
#include <interfaces/iprojectcontroller.h>
39
#include <interfaces/iproject.h>
40

Milian Wolff's avatar
Milian Wolff committed
41 42
#include <util/path.h>

43 44
#include <vcs/vcsjob.h>
#include <vcs/vcsrevision.h>
45
#include <vcs/vcsevent.h>
46
#include <vcs/dvcs/dvcsjob.h>
47
#include <vcs/vcsannotation.h>
48
#include <vcs/widgets/standardvcslocationwidget.h>
49
#include <KIO/CopyJob>
50
#include <KIO/NetAccess>
51
#include "gitclonejob.h"
52 53 54 55
#include <interfaces/contextmenuextension.h>
#include <QMenu>
#include <interfaces/iruncontroller.h>
#include "stashmanagerdialog.h"
56
#include <KMessageBox>
57
#include <KTextEdit>
58
#include <KDirWatch>
59
#include <KTextEditor/Document>
60
#include "gitjob.h"
61
#include "gitmessagehighlighter.h"
62
#include "gitplugincheckinrepositoryjob.h"
63

64 65
using namespace KDevelop;

66 67 68 69 70 71 72 73 74 75
QVariant runSynchronously(KDevelop::VcsJob* job)
{
    QVariant ret;
    if(job->exec() && job->status()==KDevelop::VcsJob::JobSucceeded) {
        ret = job->fetchResults();
    }
    delete job;
    return ret;
}

76 77
namespace
{
Milian Wolff's avatar
Milian Wolff committed
78 79

QDir dotGitDirectory(const QUrl& dirPath)
80
{
81
    const QFileInfo finfo(dirPath.toLocalFile());
Milian Wolff's avatar
Milian Wolff committed
82
    QDir dir = finfo.absoluteDir();
83 84
    
    static const QString gitDir(".git");
85
    while (!dir.exists(gitDir) && dir.cdUp()) {} // cdUp, until there is a sub-directory called .git
86

87 88 89
    return dir;
}

90 91 92 93
/**
 * Whenever a directory is provided, change it for all the files in it but not inner directories,
 * that way we make sure we won't get into recursion,
 */
Milian Wolff's avatar
Milian Wolff committed
94
static QList<QUrl> preventRecursion(const QList<QUrl>& urls)
95
{
Milian Wolff's avatar
Milian Wolff committed
96 97
    QList<QUrl> ret;
    foreach(const QUrl& url, urls) {
98 99 100 101
        QDir d(url.toLocalFile());
        if(d.exists()) {
            QStringList entries = d.entryList(QDir::Files | QDir::NoDotAndDotDot);
            foreach(const QString& entry, entries) {
Milian Wolff's avatar
Milian Wolff committed
102
                QUrl entryUrl = QUrl::fromLocalFile(d.absoluteFilePath(entry));
103 104 105 106 107 108 109 110
                ret += entryUrl;
            }
        } else
            ret += url;
    }
    return ret;
}

111 112 113 114 115 116 117 118
QString toRevisionName(const KDevelop::VcsRevision& rev, QString currentRevision=QString())
{
    switch(rev.revisionType()) {
        case VcsRevision::Special:
            switch(rev.revisionValue().value<VcsRevision::RevisionSpecialType>()) {
                case VcsRevision::Head:
                    return "^HEAD";
                case VcsRevision::Base:
119
                    return "";
120 121 122 123 124 125
                case VcsRevision::Working:
                    return "";
                case VcsRevision::Previous:
                    Q_ASSERT(!currentRevision.isEmpty());
                    return currentRevision + "^1";
                case VcsRevision::Start:
126 127
                    return "";
                case VcsRevision::UserSpecialType: //Not used
128 129 130 131 132 133 134 135 136 137 138 139 140 141
                    Q_ASSERT(false && "i don't know how to do that");
            }
            break;
        case VcsRevision::GlobalNumber:
            return rev.revisionValue().toString();
        case VcsRevision::Date:
        case VcsRevision::FileNumber:
        case VcsRevision::Invalid:
        case VcsRevision::UserSpecialType:
            Q_ASSERT(false);
    }
    return QString();
}

142
QString revisionInterval(const KDevelop::VcsRevision& rev, const KDevelop::VcsRevision& limit)
143 144
{
    QString ret;
145
    if(rev.revisionType()==VcsRevision::Special &&
Yuri Chornoivan's avatar
Yuri Chornoivan committed
146
                rev.revisionValue().value<VcsRevision::RevisionSpecialType>()==VcsRevision::Start) //if we want it to the beginning just put the revisionInterval
147 148
        ret = toRevisionName(limit, QString());
    else {
149
        QString dst = toRevisionName(limit);
150 151 152 153 154 155 156 157 158
        if(dst.isEmpty())
            ret = dst;
        else {
            QString src = toRevisionName(rev, dst);
            if(src.isEmpty())
                ret = src;
            else
                ret = src+".."+dst;
        }
159
    }
160 161 162
    return ret;
}

Milian Wolff's avatar
Milian Wolff committed
163
QDir urlDir(const QUrl& url)
164 165 166 167 168 169 170
{
    QFileInfo f(url.toLocalFile());
    if(f.isDir())
        return QDir(url.toLocalFile());
    else
        return f.absoluteDir();
}
Milian Wolff's avatar
Milian Wolff committed
171
QDir urlDir(const QList<QUrl>& urls) { return urlDir(urls.first()); } //TODO: could be improved
172

173 174
}

175
GitPlugin::GitPlugin( QObject *parent, const QVariantList & )
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
176
    : DistributedVersionControlPlugin(parent, "kdevgit"), m_oldVersion(false)
177
{
178
    if (QStandardPaths::findExecutable("git").isEmpty()) {
179
        m_hasError = true;
Laurent Montel's avatar
Laurent Montel committed
180
        m_errorDescription = i18n("git is not installed");
181 182 183
        return;
    }

184 185
    KDEV_USE_EXTENSION_INTERFACE( KDevelop::IBasicVersionControl )
    KDEV_USE_EXTENSION_INTERFACE( KDevelop::IDistributedVersionControl )
186
    KDEV_USE_EXTENSION_INTERFACE( KDevelop::IBranchingVersionControl )
187

188
    m_hasError = false;
189
    setObjectName("Git");
190 191 192 193 194
    
    DVcsJob* versionJob = new DVcsJob(QDir::tempPath(), this, KDevelop::OutputJob::Silent);
    *versionJob << "git" << "--version";
    connect(versionJob, SIGNAL(readyForParsing(KDevelop::DVcsJob*)), SLOT(parseGitVersionOutput(KDevelop::DVcsJob*)));
    ICore::self()->runController()->registerJob(versionJob);
195 196 197 198
    
    m_watcher = new KDirWatch(this);
    connect(m_watcher, SIGNAL(dirty(QString)), SLOT(fileChanged(QString)));
    connect(m_watcher, SIGNAL(created(QString)), SLOT(fileChanged(QString)));
199 200 201
}

GitPlugin::~GitPlugin()
202
{}
203

204 205 206 207 208 209 210 211 212 213 214 215 216 217
bool emptyOutput(DVcsJob* job)
{
    QScopedPointer<DVcsJob> _job(job);
    if(job->exec() && job->status()==VcsJob::JobSucceeded)
        return job->rawOutput().trimmed().isEmpty();
    
    return false;
}

bool GitPlugin::hasStashes(const QDir& repository)
{
    return !emptyOutput(gitStash(repository, QStringList("list"), KDevelop::OutputJob::Silent));
}

218
bool GitPlugin::hasModifications(const QDir& d)
219
{
220
    return !emptyOutput(lsFiles(d, QStringList("-m"), OutputJob::Silent));
221 222
}

Milian Wolff's avatar
Milian Wolff committed
223
bool GitPlugin::hasModifications(const QDir& repo, const QUrl& file)
224 225 226 227
{
    return !emptyOutput(lsFiles(repo, QStringList() << "-m" << file.path(), OutputJob::Silent));
}

Milian Wolff's avatar
Milian Wolff committed
228
void GitPlugin::additionalMenuEntries(QMenu* menu, const QList<QUrl>& urls)
229 230 231 232
{
    m_urls = urls;
    
    QDir dir=urlDir(urls);
233
    bool hasSt = hasStashes(dir);
234
    menu->addSeparator()->setText(i18n("Git Stashes"));
235 236 237
    menu->addAction(i18n("Stash Manager"), this, SLOT(ctxStashManager()))->setEnabled(hasSt);
    menu->addAction(i18n("Push Stash"), this, SLOT(ctxPushStash()));
    menu->addAction(i18n("Pop Stash"), this, SLOT(ctxPopStash()))->setEnabled(hasSt);
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
}

void GitPlugin::ctxPushStash()
{
    VcsJob* job = gitStash(urlDir(m_urls), QStringList(), KDevelop::OutputJob::Verbose);
    ICore::self()->runController()->registerJob(job);
}

void GitPlugin::ctxPopStash()
{
    VcsJob* job = gitStash(urlDir(m_urls), QStringList("pop"), KDevelop::OutputJob::Verbose);
    ICore::self()->runController()->registerJob(job);
}

void GitPlugin::ctxStashManager()
{
    QPointer<StashManagerDialog> d = new StashManagerDialog(urlDir(m_urls), this, 0);
    d->exec();
    
    delete d;
}

260
DVcsJob* GitPlugin::errorsFound(const QString& error, KDevelop::OutputJob::OutputJobVerbosity verbosity=OutputJob::Verbose)
261
{
262
    DVcsJob* j = new DVcsJob(QDir::temp(), this, verbosity);
263 264 265 266
    *j << "echo" << i18n("error: %1", error) << "-n";
    return j;
}

267
QString GitPlugin::name() const
268
{
269 270 271
    return QLatin1String("Git");
}

Milian Wolff's avatar
Milian Wolff committed
272
QUrl GitPlugin::repositoryRoot(const QUrl& path)
273
{
Milian Wolff's avatar
Milian Wolff committed
274
    return QUrl::fromLocalFile(dotGitDirectory(path).absolutePath());
275 276
}

Milian Wolff's avatar
Milian Wolff committed
277
bool GitPlugin::isValidDirectory(const QUrl & dirPath)
278
{
279
    QDir dir=dotGitDirectory(dirPath);
280

281
    return dir.cd(".git") && dir.exists("HEAD");
282 283
}

Milian Wolff's avatar
Milian Wolff committed
284
bool GitPlugin::isVersionControlled(const QUrl &path)
285
{
286
    QFileInfo fsObject(path.toLocalFile());
287 288 289
    if (!fsObject.exists()) {
        return false;
    }
290
    if (fsObject.isDir()) {
291
        return isValidDirectory(path);
292
    }
293

294 295
    QString filename = fsObject.fileName();

296
    QStringList otherFiles = getLsFiles(fsObject.dir(), QStringList("--") << filename, KDevelop::OutputJob::Silent);
297
    return !otherFiles.empty();
298 299
}

Milian Wolff's avatar
Milian Wolff committed
300
VcsJob* GitPlugin::init(const QUrl &directory)
301
{
302
    DVcsJob* job = new DVcsJob(urlDir(directory), this);
303
    job->setType(VcsJob::Import);
304 305
    *job << "git" << "init";
    return job;
306 307
}

Milian Wolff's avatar
Milian Wolff committed
308
VcsJob* GitPlugin::createWorkingCopy(const KDevelop::VcsLocation & source, const QUrl& dest, KDevelop::IBasicVersionControl::RecursionMode)
309
{
310
    DVcsJob* job = new GitCloneJob(urlDir(dest), this);
311
    job->setType(VcsJob::Import);
312 313
    *job << "git" << "clone" << "--progress" << "--" << source.localUrl().url() << dest;
    return job;
314 315
}

Milian Wolff's avatar
Milian Wolff committed
316
VcsJob* GitPlugin::add(const QList<QUrl>& localLocations, KDevelop::IBasicVersionControl::RecursionMode recursion)
317 318
{
    if (localLocations.empty())
319
        return errorsFound(i18n("Did not specify the list of files"), OutputJob::Verbose);
320

321
    DVcsJob* job = new GitJob(dotGitDirectory(localLocations.front()), this);
322
    job->setType(VcsJob::Add);
323
    *job << "git" << "add" << "--" << (recursion == IBasicVersionControl::Recursive ? localLocations : preventRecursion(localLocations));
324
    return job;
325 326
}

Milian Wolff's avatar
Milian Wolff committed
327
KDevelop::VcsJob* GitPlugin::status(const QList<QUrl>& localLocations, KDevelop::IBasicVersionControl::RecursionMode recursion)
328
{
329 330 331
    if (localLocations.empty())
        return errorsFound(i18n("Did not specify the list of files"), OutputJob::Verbose);

332
    DVcsJob* job = new GitJob(urlDir(localLocations), this, OutputJob::Silent);
333
    job->setType(VcsJob::Status);
334
    
335 336 337 338 339
    if(m_oldVersion) {
        *job << "git" << "ls-files" << "-t" << "-m" << "-c" << "-o" << "-d" << "-k" << "--directory";
        connect(job, SIGNAL(readyForParsing(KDevelop::DVcsJob*)), SLOT(parseGitStatusOutput_old(KDevelop::DVcsJob*)));
    } else {
        *job << "git" << "status" << "--porcelain";
340
        job->setIgnoreError(true);
341 342 343
        connect(job, SIGNAL(readyForParsing(KDevelop::DVcsJob*)), SLOT(parseGitStatusOutput(KDevelop::DVcsJob*)));
    }
    *job << "--" << (recursion == IBasicVersionControl::Recursive ? localLocations : preventRecursion(localLocations));
344

345
    return job;
346 347
}

Milian Wolff's avatar
Milian Wolff committed
348
VcsJob* GitPlugin::diff(const QUrl& fileOrDirectory, const KDevelop::VcsRevision& srcRevision, const KDevelop::VcsRevision& dstRevision,
349
                        VcsDiff::Type /*type*/, IBasicVersionControl::RecursionMode recursion)
350
{
351
    //TODO: control different types
Milian Wolff's avatar
Milian Wolff committed
352

353
    DVcsJob* job = new GitJob(dotGitDirectory(fileOrDirectory), this, KDevelop::OutputJob::Silent);
354
    job->setType(VcsJob::Diff);
355
    *job << "git" << "diff" << "--no-color" << "--no-ext-diff";
356 357 358 359 360 361 362 363 364 365
    if(srcRevision.revisionType()==VcsRevision::Special
        && dstRevision.revisionType()==VcsRevision::Special
        && srcRevision.specialType()==VcsRevision::Base
        && dstRevision.specialType()==VcsRevision::Working)
        *job << "HEAD";
    else {
        QString revstr = revisionInterval(srcRevision, dstRevision);
        if(!revstr.isEmpty())
            *job << revstr;
    }
Milian Wolff's avatar
Milian Wolff committed
366 367 368 369 370 371 372 373

    *job << "--";
    if (recursion == IBasicVersionControl::Recursive) {
        *job << fileOrDirectory;
    } else {
        *job << preventRecursion(QList<QUrl>() << fileOrDirectory);
    }

374
    connect(job, SIGNAL(readyForParsing(KDevelop::DVcsJob*)), SLOT(parseGitDiffOutput(KDevelop::DVcsJob*)));
375
    return job;
376 377
}

Milian Wolff's avatar
Milian Wolff committed
378
VcsJob* GitPlugin::revert(const QList<QUrl>& localLocations, IBasicVersionControl::RecursionMode recursion)
379
{
380 381 382
    if(localLocations.isEmpty() )
        return errorsFound(i18n("Could not revert changes"), OutputJob::Verbose);
    
383 384 385 386
    QDir repo = urlDir(repositoryRoot(localLocations.first()));
    QString modified;
    for (const auto& file: localLocations) {
        if (hasModifications(repo, file)) {
Milian Wolff's avatar
Milian Wolff committed
387
            modified.append(file.toDisplayString(QUrl::PreferLocalFile) + "<br/>");
388 389 390 391 392 393 394 395 396 397
        }
    }
    if (!modified.isEmpty()) {
        auto res = KMessageBox::questionYesNo(nullptr, i18n("The following files have uncommited changes, "
                                              "which will be lost. Continue?") + "<br/><br/>" + modified);
        if (res != KMessageBox::Yes) {
            return errorsFound(QString(), OutputJob::Silent);
        }
    }

398
    DVcsJob* job = new GitJob(dotGitDirectory(localLocations.front()), this);
399
    job->setType(VcsJob::Revert);
400 401
    *job << "git" << "checkout" << "--";
    *job << (recursion == IBasicVersionControl::Recursive ? localLocations : preventRecursion(localLocations));
402
    
403
    return job;
404 405 406
}


407 408 409
//TODO: git doesn't like empty messages, but "KDevelop didn't provide any message, it may be a bug" looks ugly...
//If no files specified then commit already added files
VcsJob* GitPlugin::commit(const QString& message,
Milian Wolff's avatar
Milian Wolff committed
410
                             const QList<QUrl>& localLocations,
411 412
                             KDevelop::IBasicVersionControl::RecursionMode recursion)
{
413
    if (localLocations.empty() || message.isEmpty())
414
        return errorsFound(i18n("No files or message specified"));
415

416 417
    QDir dir = dotGitDirectory(localLocations.front());
    DVcsJob* job = new DVcsJob(dir, this);
418
    job->setType(VcsJob::Commit);
Milian Wolff's avatar
Milian Wolff committed
419
    QList<QUrl> files = (recursion == IBasicVersionControl::Recursive ? localLocations : preventRecursion(localLocations));
420
    addNotVersionedFiles(dir, files);
421
    
422
    *job << "git" << "commit" << "-m" << message;
423
    *job << "--" << files;
424
    return job;
425
}
426

Milian Wolff's avatar
Milian Wolff committed
427
void GitPlugin::addNotVersionedFiles(const QDir& dir, const QList<QUrl>& files)
428 429
{
    QStringList otherStr = getLsFiles(dir, QStringList() << "--others", KDevelop::OutputJob::Silent);
Milian Wolff's avatar
Milian Wolff committed
430
    QList<QUrl> toadd, otherFiles;
431 432
    
    foreach(const QString& file, otherStr) {
Milian Wolff's avatar
Milian Wolff committed
433
        QUrl v = QUrl::fromLocalFile(dir.absoluteFilePath(file));
434 435 436 437 438
        
        otherFiles += v;
    }
    
    //We add the files that are not versioned
Milian Wolff's avatar
Milian Wolff committed
439
    foreach(const QUrl& file, files) {
440 441 442 443
        if(otherFiles.contains(file) && QFileInfo(file.toLocalFile()).isFile())
            toadd += file;
    }
    
444 445 446 447
    if(!toadd.isEmpty()) {
        VcsJob* job = add(toadd);
        job->exec();
    }
448 449
}

450 451
bool isEmptyDirStructure(const QDir &dir)
{
452
    foreach (const QFileInfo &i, dir.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot)) {
453 454 455 456 457 458 459 460 461
        if (i.isDir()) {
            if (!isEmptyDirStructure(QDir(i.filePath()))) return false;
        } else if (i.isFile()) {
            return false;
        }
    }
    return true;
}

Milian Wolff's avatar
Milian Wolff committed
462
VcsJob* GitPlugin::remove(const QList<QUrl>& files)
463
{
464 465
    if (files.isEmpty())
        return errorsFound(i18n("No files to remove"));
466 467 468
    QDir dotGitDir = dotGitDirectory(files.front());


Milian Wolff's avatar
Milian Wolff committed
469
    QList<QUrl> files_(files);
470

Milian Wolff's avatar
Milian Wolff committed
471
    QMutableListIterator<QUrl> i(files_);
472
    while (i.hasNext()) {
Milian Wolff's avatar
Milian Wolff committed
473
        QUrl file = i.next();
474
        QFileInfo fileInfo(file.toLocalFile());
475 476 477 478

        QStringList otherStr = getLsFiles(dotGitDir, QStringList() << "--others" << "--" << file.toLocalFile(), KDevelop::OutputJob::Silent);
        if(!otherStr.isEmpty()) {
            //remove files not under version control
Milian Wolff's avatar
Milian Wolff committed
479
            QList<QUrl> otherFiles;
480
            foreach(const QString &f, otherStr) {
Milian Wolff's avatar
Milian Wolff committed
481
                otherFiles << QUrl::fromLocalFile(dotGitDir.path()+'/'+f);
482 483 484 485 486
            }
            if (fileInfo.isFile()) {
                //if it's an unversioned file we are done, don't use git rm on it
                i.remove();
            }
487
            kDebug() << "other files" << otherFiles;
488 489 490
            KIO::NetAccess::synchronousRun(KIO::trash(otherFiles), 0);
        }

491
        if (fileInfo.isDir()) {
492 493 494
            if (isEmptyDirStructure(QDir(file.toLocalFile()))) {
                //remove empty folders, git doesn't do that
                kDebug() << "empty folder, removing" << file;
495
                KIO::NetAccess::synchronousRun(KIO::trash(file), 0);
496
                //we already deleted it, don't use git rm on it
497 498 499 500 501 502
                i.remove();
            }
        }
    }

    if (files_.isEmpty()) return 0;
503

504 505
    DVcsJob* job = new GitJob(dotGitDir, this);
    job->setType(VcsJob::Remove);
Kevin Funk's avatar
Kevin Funk committed
506 507 508
    // git refuses to delete files with local modifications
    // use --force to overcome this
    *job << "git" << "rm" << "-r" << "--force";
509 510
    *job << "--" << files_;
    return job;
511 512
}

Milian Wolff's avatar
Milian Wolff committed
513
VcsJob* GitPlugin::log(const QUrl& localLocation,
514
                const KDevelop::VcsRevision& src, const KDevelop::VcsRevision& dst)
515
{
516
    DVcsJob* job = new GitJob(dotGitDirectory(localLocation), this, KDevelop::OutputJob::Silent);
517
    job->setType(VcsJob::Log);
518
    *job << "git" << "log" << "--date=raw" << "--name-status" << "-M80%" << "--follow";
519 520 521
    QString rev = revisionInterval(dst, src);
    if(!rev.isEmpty())
        *job << rev;
522
    *job << "--" << localLocation;
523
    connect(job, SIGNAL(readyForParsing(KDevelop::DVcsJob*)), this, SLOT(parseGitLogOutput(KDevelop::DVcsJob*)));
524
    return job;
525 526
}

527

Milian Wolff's avatar
Milian Wolff committed
528
VcsJob* GitPlugin::log(const QUrl& localLocation, const KDevelop::VcsRevision& rev, unsigned long int limit)
529
{
530
    DVcsJob* job = new GitJob(dotGitDirectory(localLocation), this, KDevelop::OutputJob::Silent);
531
    job->setType(VcsJob::Log);
532
    *job << "git" << "log" << "--date=raw" << "--name-status" << "-M80%" << "--follow";
533 534 535
    QString revStr = toRevisionName(rev, QString());
    if(!revStr.isEmpty())
        *job << revStr;
536 537 538 539 540
    if(limit>0)
        *job << QString("-%1").arg(limit);
    
    *job << "--" << localLocation;
    connect(job, SIGNAL(readyForParsing(KDevelop::DVcsJob*)), this, SLOT(parseGitLogOutput(KDevelop::DVcsJob*)));
541
    return job;
542 543
}

Milian Wolff's avatar
Milian Wolff committed
544
KDevelop::VcsJob* GitPlugin::annotate(const QUrl &localLocation, const KDevelop::VcsRevision&)
545
{
546
    DVcsJob* job = new GitJob(dotGitDirectory(localLocation), this, KDevelop::OutputJob::Silent);
547
    job->setType(VcsJob::Annotate);
548
    *job << "git" << "blame" << "--porcelain" << "-w";
549
    *job << "--" << localLocation;
550
    connect(job, SIGNAL(readyForParsing(KDevelop::DVcsJob*)), this, SLOT(parseGitBlameOutput(KDevelop::DVcsJob*)));
551
    return job;
552 553
}

554 555
void GitPlugin::parseGitBlameOutput(DVcsJob *job)
{
556
    QVariantList results;
Milian Wolff's avatar
Milian Wolff committed
557
    VcsAnnotationLine* annotation = 0;
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
    QStringList lines = job->output().split('\n');
    
    bool skipNext=false;
    QMap<QString, VcsAnnotationLine> definedRevisions;
    for(QStringList::const_iterator it=lines.constBegin(), itEnd=lines.constEnd();
        it!=itEnd; ++it)
    {
        if(skipNext) {
            skipNext=false;
            results += qVariantFromValue(*annotation);
            
            continue;
        }
        
        if(it->isEmpty())
            continue;
        
        QString name = it->left(it->indexOf(' '));
        QString value = it->right(it->size()-name.size()-1);
577

578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
        if(name=="author")
            annotation->setAuthor(value);
        else if(name=="author-mail") {} //TODO: do smth with the e-mail?
        else if(name=="author-tz") {} //TODO: does it really matter?
        else if(name=="author-time")
            annotation->setDate(QDateTime::fromTime_t(value.toUInt()));
        else if(name=="summary")
            annotation->setCommitMessage(value);
        else if(name.startsWith("committer")) {} //We will just store the authors
        else if(name=="previous") {} //We don't need that either
        else if(name=="filename") { skipNext=true; }
        else if(name=="boundary") {
            definedRevisions.insert("boundary", VcsAnnotationLine());
        }
        else
        {
            QStringList values = value.split(' ');
            
596
            VcsRevision rev;
Milian Wolff's avatar
Milian Wolff committed
597
            rev.setRevisionValue(name.left(8), KDevelop::VcsRevision::GlobalNumber);
598 599 600 601 602 603 604
            
            skipNext = definedRevisions.contains(name);
            
            if(!skipNext)
                definedRevisions.insert(name, VcsAnnotationLine());
            
            annotation = &definedRevisions[name];
605
            annotation->setLineNumber(values[1].toInt() - 1);
606
            annotation->setRevision(rev);
607 608 609 610
        }
    }
    job->setResults(results);
}
611

612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627

DVcsJob* GitPlugin::lsFiles(const QDir &repository, const QStringList &args,
                            OutputJob::OutputJobVerbosity verbosity)
{
    DVcsJob* job = new DVcsJob(repository, this, verbosity);
    *job << "git" << "ls-files" << args;
    return job;
}

DVcsJob* GitPlugin::gitStash(const QDir& repository, const QStringList& args, OutputJob::OutputJobVerbosity verbosity)
{
    DVcsJob* job = new DVcsJob(repository, this, verbosity);
    *job << "git" << "stash" << args;
    return job;
}

Milian Wolff's avatar
Milian Wolff committed
628
VcsJob* GitPlugin::tag(const QUrl& repository, const QString& commitMessage, const VcsRevision& rev, const QString& tagName)
629 630 631 632 633 634 635 636
{
    DVcsJob* job = new DVcsJob(urlDir(repository), this);
    *job << "git" << "tag" << "-m" << commitMessage << tagName;
    if(rev.revisionValue().isValid())
        *job << rev.revisionValue().toString();
    return job;
}

Milian Wolff's avatar
Milian Wolff committed
637
VcsJob* GitPlugin::switchBranch(const QUrl &repository, const QString &branch)
638
{
639
    QDir d=urlDir(repository);
640 641
    
    if(hasModifications(d) && KMessageBox::questionYesNo(0, i18n("There are pending changes, do you want to stash them first?"))==KMessageBox::Yes) {
642
        QScopedPointer<DVcsJob> stash(gitStash(d, QStringList(), KDevelop::OutputJob::Verbose));
643 644 645 646
        stash->exec();
    }
    
    DVcsJob* job = new DVcsJob(d, this);
647 648
    *job << "git" << "checkout" << branch;
    return job;
649 650
}

Milian Wolff's avatar
Milian Wolff committed
651
VcsJob* GitPlugin::branch(const QUrl& repository, const KDevelop::VcsRevision& rev, const QString& branchName)
652
{
653 654 655 656
    Q_ASSERT(!branchName.isEmpty());
    
    DVcsJob* job = new DVcsJob(urlDir(repository), this);
    *job << "git" << "branch" << "--" << branchName;
657
    
658 659
    if(!rev.prettyValue().isEmpty())
        *job << rev.revisionValue().toString();
660
    return job;
661 662
}

Milian Wolff's avatar
Milian Wolff committed
663
VcsJob* GitPlugin::deleteBranch(const QUrl& repository, const QString& branchName)
664
{
665 666 667
    DVcsJob* job = new DVcsJob(urlDir(repository), this, OutputJob::Silent);
    *job << "git" << "branch" << "-D" << branchName;
    connect(job, SIGNAL(readyForParsing(KDevelop::DVcsJob*)), SLOT(parseGitCurrentBranch(KDevelop::DVcsJob*)));
668
    return job;
669 670
}

Milian Wolff's avatar
Milian Wolff committed
671
VcsJob* GitPlugin::renameBranch(const QUrl& repository, const QString& oldBranchName, const QString& newBranchName)
672
{
673 674 675
    DVcsJob* job = new DVcsJob(urlDir(repository), this, OutputJob::Silent);
    *job << "git" << "branch" << "-m" << newBranchName << oldBranchName;
    connect(job, SIGNAL(readyForParsing(KDevelop::DVcsJob*)), SLOT(parseGitCurrentBranch(KDevelop::DVcsJob*)));
676 677 678
    return job;
}

Milian Wolff's avatar
Milian Wolff committed
679
VcsJob* GitPlugin::currentBranch(const QUrl& repository)
680
{
681
    DVcsJob* job = new DVcsJob(urlDir(repository), this, OutputJob::Silent);
682
    job->setIgnoreError(true);
683
    *job << "git" << "symbolic-ref" << "-q" << "--short" << "HEAD";
684 685
    connect(job, SIGNAL(readyForParsing(KDevelop::DVcsJob*)), SLOT(parseGitCurrentBranch(KDevelop::DVcsJob*)));
    return job;
686 687
}

688
void GitPlugin::parseGitCurrentBranch(DVcsJob* job)
689
{
690
    QString out = job->output().trimmed();
691

692
    job->setResults(out);
693 694
}

Milian Wolff's avatar
Milian Wolff committed
695
VcsJob* GitPlugin::branches(const QUrl &repository)
696 697 698 699 700 701 702 703 704 705
{
    DVcsJob* job=new DVcsJob(urlDir(repository));
    *job << "git" << "branch" << "-a";
    connect(job, SIGNAL(readyForParsing(KDevelop::DVcsJob*)), SLOT(parseGitBranchOutput(KDevelop::DVcsJob*)));
    return job;
}

void GitPlugin::parseGitBranchOutput(DVcsJob* job)
{
    QStringList branchListDirty = job->output().split('\n', QString::SkipEmptyParts);
706 707 708 709

    QStringList branchList;
    foreach(QString branch, branchListDirty)
    {
710 711 712 713
        // Skip pointers to another branches (one example of this is "origin/HEAD -> origin/master");
        // "git rev-list" chokes on these entries and we do not need duplicate branches altogether.
        if (branch.contains("->"))
            continue;
714 715 716 717 718

        // Skip entries such as '(no branch)'
        if (branch.contains("(no branch)"))
            continue;

719 720
        if (branch.startsWith('*'))
            branch = branch.right(branch.size()-2);
721
        
722
        branchList<<branch.trimmed();
723
    }
724 725
    
    job->setResults(branchList);
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
}

/* Few words about how this hardcore works:
1. get all commits (with --paretns)
2. select master (root) branch and get all unicial commits for branches (git-rev-list br2 ^master ^br3)
3. parse allCommits. While parsing set mask (columns state for every row) for BRANCH, INITIAL, CROSS,
   MERGE and INITIAL are also set in DVCScommit::setParents (depending on parents count)
   another setType(INITIAL) is used for "bottom/root/first" commits of branches
4. find and set merges, HEADS. It's an ittaration through all commits.
    - first we check if parent is from the same branch, if no then we go through all commits searching parent's index
      and set CROSS/HCROSS for rows (in 3 rows are set EMPTY after commit with parent from another tree met)
    - then we check branchesShas[i][0] to mark heads

4 can be a seporate function. TODO: All this porn require refactoring (rewriting is better)!

It's a very dirty implementation.
FIXME:
1. HEAD which is head has extra line to connect it with further commit
2. If you menrge branch2 to master, only new commits of branch2 will be visible (it's fine, but there will be
extra merge rectangle in master. If there are no extra commits in branch2, but there are another branches, then the place for branch2 will be empty (instead of be used for branch3).
3. Commits that have additional commit-data (not only history merging, but changes to fix conflicts) are shown incorrectly
*/

QList<DVcsEvent> GitPlugin::getAllCommits(const QString &repo)
{
751 752
    initBranchHash(repo);
    
753 754
    QStringList args;
    args << "--all" << "--pretty" << "--parents";
755 756 757
    QScopedPointer<DVcsJob> job(gitRevList(repo, args));
    bool ret = job->exec();
    Q_ASSERT(ret && job->status()==VcsJob::JobSucceeded && "TODO: provide a fall back in case of failing");
Milian Wolff's avatar
Milian Wolff committed
758
    Q_UNUSED(ret);
759 760 761 762 763 764 765 766 767 768
    QStringList commits = job->output().split('\n', QString::SkipEmptyParts);

    static QRegExp rx_com("commit \\w{40,40}");

    QList<DVcsEvent>commitList;
    DVcsEvent item;

    //used to keep where we have empty/cross/branch entry
    //true if it's an active branch (then cross or branch) and false if not
    QVector<bool> additionalFlags(branchesShas.count());
769
    additionalFlags.fill(false);
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

    //parse output
    for(int i = 0; i < commits.count(); ++i)
    {
        if (commits[i].contains(rx_com))
        {
            kDebug() << "commit found in " << commits[i];
            item.setCommit(commits[i].section(' ', 1, 1).trimmed());
//             kDebug() << "commit is: " << commits[i].section(' ', 1);

            QStringList parents;
            QString parent = commits[i].section(' ', 2);
            int section = 2;
            while (!parent.isEmpty())
            {
                /*                kDebug() << "Parent is: " << parent;*/
                parents.append(parent.trimmed());
                section++;
                parent = commits[i].section(' ', section);
            }
            item.setParents(parents);

            //Avoid Merge string
            while (!commits[i].contains("Author: "))
                    ++i;

            item.setAuthor(commits[i].section("Author: ", 1).trimmed());
//             kDebug() << "author is: " << commits[i].section("Author: ", 1);

            item.setDate(commits[++i].section("Date:   ", 1).trimmed());
//             kDebug() << "date is: " << commits[i].section("Date:   ", 1);

            QString log;
            i++; //next line!
            while (i < commits.count() && !commits[i].contains(rx_com))
                log += commits[i++];
            --i; //while took commit line
            item.setLog(log.trimmed());
//             kDebug() << "log is: " << log;

            //mask is used in CommitViewDelegate to understand what we should draw for each branch
            QList<int> mask;

            //set mask (properties for each graph column in row)
            for(int i = 0; i < branchesShas.count(); ++i)
            {
                kDebug()<<"commit: " << item.getCommit();
                if (branchesShas[i].contains(item.getCommit()))
                {
                    mask.append(item.getType()); //we set type in setParents

                    //check if parent from the same branch, if not then we have found a root of the branch
                    //and will use empty column for all futher (from top to bottom) revisions
                    //FIXME: we should set CROSS between parent and child (and do it when find merge point)
                    additionalFlags[i] = false;
                    foreach(const QString &sha, item.getParents())
                    {
                        if (branchesShas[i].contains(sha))
                            additionalFlags[i] = true;
                    }
                    if (additionalFlags[i] == false)
                       item.setType(DVcsEvent::INITIAL); //hasn't parents from the same branch, used in drawing
                }
                else
                {
                    if (additionalFlags[i] == false)
                        mask.append(DVcsEvent::EMPTY);
                    else
                        mask.append(DVcsEvent::CROSS);
                }
                kDebug() << "mask " << i << "is " << mask[i];
            }
            item.setProperties(mask);
            commitList.append(item);
        }
    }

    //find and set merges, HEADS, require refactoring!
    for(QList<DVcsEvent>::iterator iter = commitList.begin();
        iter != commitList.end(); ++iter)
    {
        QStringList parents = iter->getParents();
        //we need only only child branches
        if (parents.count() != 1)
            break;

        QString parent = parents[0];
        QString commit = iter->getCommit();
        bool parent_checked = false;
        int heads_checked = 0;

        for(int i = 0; i < branchesShas.count(); ++i)
        {
            //check parent
            if (branchesShas[i].contains(commit))
            {
                if (!branchesShas[i].contains(parent))
                {
                    //parent and child are not in same branch
                    //since it is list, than parent has i+1 index
                    //set CROSS and HCROSS
                    for(QList<DVcsEvent>::iterator f_iter = iter;
                        f_iter != commitList.end(); ++f_iter)
                    {
                        if (parent == f_iter->getCommit())
                        {
                            for(int j = 0; j < i; ++j)
                            {
                                if(branchesShas[j].contains(parent))
                                    f_iter->setPropetry(j, DVcsEvent::MERGE);
                                else
                                    f_iter->setPropetry(j, DVcsEvent::HCROSS);
                            }
                            f_iter->setType(DVcsEvent::MERGE);
                            f_iter->setPropetry(i, DVcsEvent::MERGE_RIGHT);
                            kDebug() << parent << " is parent of " << commit;
                            kDebug() << f_iter->getCommit() << " is merge";
                            parent_checked = true;
                            break;
                        }
                        else
                            f_iter->setPropetry(i, DVcsEvent::CROSS);
                    }
                }
            }
            //mark HEADs

            if (!branchesShas[i].empty() && commit == branchesShas[i][0])
            {
                iter->setType(DVcsEvent::HEAD);
                iter->setPropetry(i, DVcsEvent::HEAD);
                heads_checked++;
                kDebug() << "HEAD found";
            }
            //some optimization
            if (heads_checked == branchesShas.count() && parent_checked)
                break;
        }
    }

    return commitList;
}

void GitPlugin::initBranchHash(const QString &repo)
{
Milian Wolff's avatar
Milian Wolff committed
915 916
    const QUrl repoUrl = QUrl::fromLocalFile(repo);
    QStringList gitBranches = runSynchronously(branches(repoUrl)).toStringList();
917
    kDebug() << "BRANCHES: " << gitBranches;
918 919
    //Now root branch is the current branch. In future it should be the longest branch
    //other commitLists are got with git-rev-lits branch ^br1 ^ br2
Milian Wolff's avatar
Milian Wolff committed
920
    QString root = runSynchronously(currentBranch(repoUrl)).toString();
921 922 923
    QScopedPointer<DVcsJob> job(gitRevList(repo, QStringList(root)));
    bool ret = job->exec();
    Q_ASSERT(ret && job->status()==VcsJob::JobSucceeded && "TODO: provide a fall back in case of failing");
924
    Q_UNUSED(ret);
925 926 927
    QStringList commits = job->output().split('\n', QString::SkipEmptyParts);
//     kDebug() << "\n\n\n commits" << commits << "\n\n\n";
    branchesShas.append(commits);
928
    foreach(const QString &branch, gitBranches)
Andreas Pakulat's avatar