gitplugin.cpp 52.3 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

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

K_PLUGIN_FACTORY(KDevGitFactory, registerPlugin<GitPlugin>(); )
63
K_EXPORT_PLUGIN(KDevGitFactory(KAboutData("kdevgit","kdevgit",ki18n("Git"),"0.1",ki18n("A plugin to support git version control systems"), KAboutData::License_GPL)))
64

65 66
using namespace KDevelop;

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

77 78 79
namespace
{
    
80 81
QDir dotGitDirectory(const KUrl& dirPath)
{
82 83
    const QFileInfo finfo(dirPath.toLocalFile());
    QDir dir = finfo.isDir() ? QDir(dirPath.toLocalFile()) : finfo.absoluteDir();
84 85
    
    static const QString gitDir(".git");
86
    while (!dir.exists(gitDir) && dir.cdUp()) {} // cdUp, until there is a sub-directory called .git
87

88 89 90
    return dir;
}

91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
/**
 * 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,
 */
static KUrl::List preventRecursion(const KUrl::List& urls)
{
    KUrl::List ret;
    foreach(const KUrl& url, urls) {
        QDir d(url.toLocalFile());
        if(d.exists()) {
            QStringList entries = d.entryList(QDir::Files | QDir::NoDotAndDotDot);
            foreach(const QString& entry, entries) {
                KUrl entryUrl = d.absoluteFilePath(entry);
                ret += entryUrl;
            }
        } else
            ret += url;
    }
    return ret;
}

112 113 114 115 116 117 118 119
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:
120
                    return "";
121 122 123 124 125 126
                case VcsRevision::Working:
                    return "";
                case VcsRevision::Previous:
                    Q_ASSERT(!currentRevision.isEmpty());
                    return currentRevision + "^1";
                case VcsRevision::Start:
127 128
                    return "";
                case VcsRevision::UserSpecialType: //Not used
129 130 131 132 133 134 135 136 137 138 139 140 141 142
                    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();
}

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

164 165 166 167 168 169 170 171
QDir urlDir(const KUrl& url)
{
    QFileInfo f(url.toLocalFile());
    if(f.isDir())
        return QDir(url.toLocalFile());
    else
        return f.absoluteDir();
}
172 173
QDir urlDir(const KUrl::List& urls) { return urlDir(urls.first()); } //TODO: could be improved

174 175
}

176
GitPlugin::GitPlugin( QObject *parent, const QVariantList & )
177
    : DistributedVersionControlPlugin(parent, KDevGitFactory::componentData()), m_oldVersion(false)
178
{
179 180
    if (KStandardDirs::findExe("git").isEmpty()) {
        m_hasError = true;
Laurent Montel's avatar
Laurent Montel committed
181
        m_errorDescription = i18n("git is not installed");
182 183 184
        return;
    }

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

189
    m_hasError = false;
190
    setObjectName("Git");
191 192 193 194 195
    
    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);
196 197 198 199
    
    m_watcher = new KDirWatch(this);
    connect(m_watcher, SIGNAL(dirty(QString)), SLOT(fileChanged(QString)));
    connect(m_watcher, SIGNAL(created(QString)), SLOT(fileChanged(QString)));
200 201 202
}

GitPlugin::~GitPlugin()
203
{}
204

205 206 207 208 209 210 211 212 213 214 215 216 217 218
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));
}

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

void GitPlugin::additionalMenuEntries(QMenu* menu, const KUrl::List& urls)
{
    m_urls = urls;
    
    QDir dir=urlDir(urls);
229
    bool hasSt = hasStashes(dir);
230
    menu->addSeparator()->setText(i18n("Git Stashes"));
231 232 233
    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);
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
}

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;
}

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

263
QString GitPlugin::name() const
264
{
265 266 267
    return QLatin1String("Git");
}

268 269
KUrl GitPlugin::repositoryRoot(const KUrl& path)
{
270
    return KUrl(dotGitDirectory(path).absolutePath());
271 272
}

273 274
bool GitPlugin::isValidDirectory(const KUrl & dirPath)
{
275
    QDir dir=dotGitDirectory(dirPath);
276

277
    return dir.cd(".git") && dir.exists("HEAD");
278 279 280 281
}

bool GitPlugin::isVersionControlled(const KUrl &path)
{
282
    QFileInfo fsObject(path.toLocalFile());
283 284 285
    if (!fsObject.exists()) {
        return false;
    }
286
    if (fsObject.isDir()) {
287
        return isValidDirectory(path);
288
    }
289

290 291
    QString filename = fsObject.fileName();

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

VcsJob* GitPlugin::init(const KUrl &directory)
{
298
    DVcsJob* job = new DVcsJob(urlDir(directory), this);
299
    job->setType(VcsJob::Import);
300 301
    *job << "git" << "init";
    return job;
302 303
}

304
VcsJob* GitPlugin::createWorkingCopy(const KDevelop::VcsLocation & source, const KUrl& dest, KDevelop::IBasicVersionControl::RecursionMode)
305
{
306
    DVcsJob* job = new GitCloneJob(urlDir(dest), this);
307
    job->setType(VcsJob::Import);
308 309
    *job << "git" << "clone" << "--progress" << "--" << source.localUrl().url() << dest;
    return job;
310 311 312 313 314
}

VcsJob* GitPlugin::add(const KUrl::List& localLocations, KDevelop::IBasicVersionControl::RecursionMode recursion)
{
    if (localLocations.empty())
315
        return errorsFound(i18n("Did not specify the list of files"), OutputJob::Verbose);
316

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

323
KDevelop::VcsJob* GitPlugin::status(const KUrl::List& localLocations, KDevelop::IBasicVersionControl::RecursionMode recursion)
324
{
325 326 327
    if (localLocations.empty())
        return errorsFound(i18n("Did not specify the list of files"), OutputJob::Verbose);

328
    DVcsJob* job = new GitJob(urlDir(localLocations), this, OutputJob::Silent);
329
    job->setType(VcsJob::Status);
330
    
331 332 333 334 335
    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";
336
        job->setIgnoreError(true);
337 338 339
        connect(job, SIGNAL(readyForParsing(KDevelop::DVcsJob*)), SLOT(parseGitStatusOutput(KDevelop::DVcsJob*)));
    }
    *job << "--" << (recursion == IBasicVersionControl::Recursive ? localLocations : preventRecursion(localLocations));
340

341
    return job;
342 343
}

344
VcsJob* GitPlugin::diff(const KUrl& fileOrDirectory, const KDevelop::VcsRevision& srcRevision, const KDevelop::VcsRevision& dstRevision,
345
                        VcsDiff::Type /*type*/, IBasicVersionControl::RecursionMode recursion)
346
{
347 348
    //TODO: control different types
    
349
    DVcsJob* job = new GitJob(dotGitDirectory(fileOrDirectory), this, KDevelop::OutputJob::Silent);
350
    job->setType(VcsJob::Diff);
351
    *job << "git" << "diff" << "--no-prefix" << "--no-color" << "--no-ext-diff";
352 353 354 355 356 357 358 359 360 361
    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;
    }
362 363
    
    *job << "--" << (recursion == IBasicVersionControl::Recursive ? fileOrDirectory : preventRecursion(fileOrDirectory));
364
    
365
    connect(job, SIGNAL(readyForParsing(KDevelop::DVcsJob*)), SLOT(parseGitDiffOutput(KDevelop::DVcsJob*)));
366
    return job;
367 368 369 370
}

VcsJob* GitPlugin::revert(const KUrl::List& localLocations, IBasicVersionControl::RecursionMode recursion)
{
371 372 373
    if(localLocations.isEmpty() )
        return errorsFound(i18n("Could not revert changes"), OutputJob::Verbose);
    
374
    DVcsJob* job = new GitJob(dotGitDirectory(localLocations.front()), this);
375
    job->setType(VcsJob::Revert);
376 377
    *job << "git" << "checkout" << "--";
    *job << (recursion == IBasicVersionControl::Recursive ? localLocations : preventRecursion(localLocations));
378
    
379
    return job;
380 381 382
}


383 384 385 386 387 388
//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,
                             const KUrl::List& localLocations,
                             KDevelop::IBasicVersionControl::RecursionMode recursion)
{
389
    if (localLocations.empty() || message.isEmpty())
390
        return errorsFound(i18n("No files or message specified"));
391

392 393
    QDir dir = dotGitDirectory(localLocations.front());
    DVcsJob* job = new DVcsJob(dir, this);
394
    job->setType(VcsJob::Commit);
395 396
    KUrl::List files = (recursion == IBasicVersionControl::Recursive ? localLocations : preventRecursion(localLocations));
    addNotVersionedFiles(dir, files);
397
    
398
    *job << "git" << "commit" << "-m" << message;
399
    *job << "--" << files;
400
    return job;
401
}
402

403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
void GitPlugin::addNotVersionedFiles(const QDir& dir, const KUrl::List& files)
{
    QStringList otherStr = getLsFiles(dir, QStringList() << "--others", KDevelop::OutputJob::Silent);
    KUrl::List toadd, otherFiles;
    
    foreach(const QString& file, otherStr) {
        KUrl v(dir.absolutePath());
        v.addPath(file);
        
        otherFiles += v;
    }
    
    //We add the files that are not versioned
    foreach(const KUrl& file, files) {
        if(otherFiles.contains(file) && QFileInfo(file.toLocalFile()).isFile())
            toadd += file;
    }
    
421 422 423 424
    if(!toadd.isEmpty()) {
        VcsJob* job = add(toadd);
        job->exec();
    }
425 426
}

427 428
bool isEmptyDirStructure(const QDir &dir)
{
429
    foreach (const QFileInfo &i, dir.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot)) {
430 431 432 433 434 435 436 437 438
        if (i.isDir()) {
            if (!isEmptyDirStructure(QDir(i.filePath()))) return false;
        } else if (i.isFile()) {
            return false;
        }
    }
    return true;
}

439 440
VcsJob* GitPlugin::remove(const KUrl::List& files)
{
441 442
    if (files.isEmpty())
        return errorsFound(i18n("No files to remove"));
443 444 445 446 447 448 449 450 451
    QDir dotGitDir = dotGitDirectory(files.front());


    KUrl::List files_(files);

    QMutableListIterator<KUrl> i(files_);
    while (i.hasNext()) {
        KUrl file = i.next();
        QFileInfo fileInfo(file.toLocalFile());
452 453 454 455 456 457 458 459 460 461 462 463

        QStringList otherStr = getLsFiles(dotGitDir, QStringList() << "--others" << "--" << file.toLocalFile(), KDevelop::OutputJob::Silent);
        if(!otherStr.isEmpty()) {
            //remove files not under version control
            KUrl::List otherFiles;
            foreach(const QString &f, otherStr) {
                otherFiles << KUrl::fromLocalFile(dotGitDir.path()+'/'+f);
            }
            if (fileInfo.isFile()) {
                //if it's an unversioned file we are done, don't use git rm on it
                i.remove();
            }
464
            kDebug() << "other files" << otherFiles;
465 466 467
            KIO::NetAccess::synchronousRun(KIO::trash(otherFiles), 0);
        }

468
        if (fileInfo.isDir()) {
469 470 471
            if (isEmptyDirStructure(QDir(file.toLocalFile()))) {
                //remove empty folders, git doesn't do that
                kDebug() << "empty folder, removing" << file;
472
                KIO::NetAccess::synchronousRun(KIO::trash(file), 0);
473
                //we already deleted it, don't use git rm on it
474 475 476 477 478 479
                i.remove();
            }
        }
    }

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

481 482
    DVcsJob* job = new GitJob(dotGitDir, this);
    job->setType(VcsJob::Remove);
Kevin Funk's avatar
Kevin Funk committed
483 484 485
    // git refuses to delete files with local modifications
    // use --force to overcome this
    *job << "git" << "rm" << "-r" << "--force";
486 487
    *job << "--" << files_;
    return job;
488 489
}

490
VcsJob* GitPlugin::log(const KUrl& localLocation,
491
                const KDevelop::VcsRevision& src, const KDevelop::VcsRevision& dst)
492
{
493
    DVcsJob* job = new GitJob(dotGitDirectory(localLocation), this, KDevelop::OutputJob::Silent);
494
    job->setType(VcsJob::Log);
495
    *job << "git" << "log" << "--date=raw" << "--name-status" << "-M80%" << "--follow";
496 497 498
    QString rev = revisionInterval(dst, src);
    if(!rev.isEmpty())
        *job << rev;
499
    *job << "--" << localLocation;
500
    connect(job, SIGNAL(readyForParsing(KDevelop::DVcsJob*)), this, SLOT(parseGitLogOutput(KDevelop::DVcsJob*)));
501
    return job;
502 503
}

504

505
VcsJob* GitPlugin::log(const KUrl& localLocation, const KDevelop::VcsRevision& rev, unsigned long int limit)
506
{
507
    DVcsJob* job = new GitJob(dotGitDirectory(localLocation), this, KDevelop::OutputJob::Silent);
508
    job->setType(VcsJob::Log);
509
    *job << "git" << "log" << "--date=raw" << "--name-status" << "-M80%" << "--follow";
510 511 512
    QString revStr = toRevisionName(rev, QString());
    if(!revStr.isEmpty())
        *job << revStr;
513 514 515 516 517
    if(limit>0)
        *job << QString("-%1").arg(limit);
    
    *job << "--" << localLocation;
    connect(job, SIGNAL(readyForParsing(KDevelop::DVcsJob*)), this, SLOT(parseGitLogOutput(KDevelop::DVcsJob*)));
518
    return job;
519 520
}

521 522
KDevelop::VcsJob* GitPlugin::annotate(const KUrl &localLocation, const KDevelop::VcsRevision&)
{
523
    DVcsJob* job = new GitJob(dotGitDirectory(localLocation), this, KDevelop::OutputJob::Silent);
524
    job->setType(VcsJob::Annotate);
525
    *job << "git" << "blame" << "--porcelain" << "-w";
526
    *job << "--" << localLocation;
527
    connect(job, SIGNAL(readyForParsing(KDevelop::DVcsJob*)), this, SLOT(parseGitBlameOutput(KDevelop::DVcsJob*)));
528
    return job;
529 530
}

531 532
void GitPlugin::parseGitBlameOutput(DVcsJob *job)
{
533
    QVariantList results;
Milian Wolff's avatar
Milian Wolff committed
534
    VcsAnnotationLine* annotation = 0;
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
    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);
        
Milian Wolff's avatar
Milian Wolff committed
555
        kDebug() << "last line" << *it;
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
        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(' ');
            
574
            VcsRevision rev;
Milian Wolff's avatar
Milian Wolff committed
575
            rev.setRevisionValue(name.left(8), KDevelop::VcsRevision::GlobalNumber);
576 577 578 579 580 581 582
            
            skipNext = definedRevisions.contains(name);
            
            if(!skipNext)
                definedRevisions.insert(name, VcsAnnotationLine());
            
            annotation = &definedRevisions[name];
583
            annotation->setLineNumber(values[1].toInt() - 1);
584
            annotation->setRevision(rev);
585 586 587 588
        }
    }
    job->setResults(results);
}
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

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;
}

VcsJob* GitPlugin::tag(const KUrl& repository, const QString& commitMessage, const VcsRevision& rev, const QString& tagName)
{
    DVcsJob* job = new DVcsJob(urlDir(repository), this);
    *job << "git" << "tag" << "-m" << commitMessage << tagName;
    if(rev.revisionValue().isValid())
        *job << rev.revisionValue().toString();
    return job;
}

VcsJob* GitPlugin::switchBranch(const KUrl &repository, const QString &branch)
616
{
617
    QDir d=urlDir(repository);
618 619
    
    if(hasModifications(d) && KMessageBox::questionYesNo(0, i18n("There are pending changes, do you want to stash them first?"))==KMessageBox::Yes) {
620
        QScopedPointer<DVcsJob> stash(gitStash(d, QStringList(), KDevelop::OutputJob::Verbose));
621 622 623 624
        stash->exec();
    }
    
    DVcsJob* job = new DVcsJob(d, this);
625 626
    *job << "git" << "checkout" << branch;
    return job;
627 628
}

629
VcsJob* GitPlugin::branch(const KUrl& repository, const KDevelop::VcsRevision& rev, const QString& branchName)
630
{
631 632 633 634
    Q_ASSERT(!branchName.isEmpty());
    
    DVcsJob* job = new DVcsJob(urlDir(repository), this);
    *job << "git" << "branch" << "--" << branchName;
635
    
636 637
    if(!rev.prettyValue().isEmpty())
        *job << rev.revisionValue().toString();
638
    return job;
639 640
}

641
VcsJob* GitPlugin::deleteBranch(const KUrl& repository, const QString& branchName)
642
{
643 644 645
    DVcsJob* job = new DVcsJob(urlDir(repository), this, OutputJob::Silent);
    *job << "git" << "branch" << "-D" << branchName;
    connect(job, SIGNAL(readyForParsing(KDevelop::DVcsJob*)), SLOT(parseGitCurrentBranch(KDevelop::DVcsJob*)));
646
    return job;
647 648
}

649
VcsJob* GitPlugin::renameBranch(const KUrl& repository, const QString& oldBranchName, const QString& newBranchName)
650
{
651 652 653
    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*)));
654 655 656
    return job;
}

657
VcsJob* GitPlugin::currentBranch(const KUrl& repository)
658
{
659
    DVcsJob* job = new DVcsJob(urlDir(repository), this, OutputJob::Silent);
660
    job->setIgnoreError(true);
661
    *job << "git" << "symbolic-ref" << "-q" << "--short" << "HEAD";
662 663
    connect(job, SIGNAL(readyForParsing(KDevelop::DVcsJob*)), SLOT(parseGitCurrentBranch(KDevelop::DVcsJob*)));
    return job;
664 665
}

666
void GitPlugin::parseGitCurrentBranch(DVcsJob* job)
667
{
668
    QString out = job->output().trimmed();
669

670
    job->setResults(out);
671 672 673 674 675 676 677 678 679 680 681 682 683
}

VcsJob* GitPlugin::branches(const KUrl &repository)
{
    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);
684 685 686 687

    QStringList branchList;
    foreach(QString branch, branchListDirty)
    {
688 689 690 691
        // 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;
692 693 694 695 696

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

697 698
        if (branch.startsWith('*'))
            branch = branch.right(branch.size()-2);
699
        
700
        branchList<<branch.trimmed();
701
    }
702 703
    
    job->setResults(branchList);
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
}

/* 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)
{
729 730
    initBranchHash(repo);
    
731 732
    QStringList args;
    args << "--all" << "--pretty" << "--parents";
733 734 735
    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
736
    Q_UNUSED(ret);
737 738 739 740 741 742 743 744 745 746
    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());
747
    additionalFlags.fill(false);
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

    //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)
{
893 894
    QStringList gitBranches = runSynchronously(branches(KUrl(repo))).toStringList();
    kDebug() << "BRANCHES: " << gitBranches;
895 896
    //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
897
    QString root = runSynchronously(currentBranch(repo)).toString();
898 899 900
    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");
901
    Q_UNUSED(ret);
902 903 904
    QStringList commits = job->output().split('\n', QString::SkipEmptyParts);
//     kDebug() << "\n\n\n commits" << commits << "\n\n\n";
    branchesShas.append(commits);
905
    foreach(const QString &branch, gitBranches)
906 907 908 909
    {
        if (branch == root)
            continue;
        QStringList args(branch);
910
        foreach(const QString &branch_arg, gitBranches)
911 912 913 914 915
        {
            if (branch_arg != branch)
                //man gitRevList for '^'
                args<<'^' + branch_arg;
        }
916 917 918
        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
919
        Q_UNUSED(ret);
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
        QStringList commits = job->output().split('\n', QString::SkipEmptyParts);
//         kDebug() << "\n\n\n commits" << commits << "\n\n\n";
        branchesShas.append(commits);
    }
}

//Actually we can just copy the output without parsing. So it's a kind of draft for future
void GitPlugin::parseLogOutput(const DVcsJob * job, QList<DVcsEvent>& commits) const
{
//     static QRegExp rx_sep( "[-=]+" );
//     static QRegExp rx_date( "date:\\s+([^;]*);\\s+author:\\s+([^;]*).*" );

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

    QStringList lines = job->output().split('\n', QString::SkipEmptyParts);

    DVcsEvent item;
    QString commitLog;

    for (int i=0; i<lines.count(); ++i) {
        QString s = lines[i];
        kDebug() << "line:" << s ;

        if (rx_com.exactMatch(s)) {
            kDebug() << "MATCH COMMIT";
            item.setCommit(s);
            s = lines[++i];
            item.setAuthor(s);
            s = lines[++i];
            item.setDate(s);
            item.setLog(commitLog);
            commits.append(item);
        }
        else
        {
            //FIXME: add this in a loop to the if, like in getAllCommits()
            commitLog += s +'\n';
        }
    }
}

961 962 963 964 965 966 967 968 969 970 971
VcsItemEvent::Actions actionsFromString(char c)
{
    switch(c) {
        case 'A': return VcsItemEvent::Added;
        case 'D': return VcsItemEvent::Deleted;
        case 'R': return VcsItemEvent::Replaced;
        case 'M': return VcsItemEvent::Modified;
    }
    return VcsItemEvent::Modified;
}

972 973 974 975
void GitPlugin::parseGitLogOutput(DVcsJob * job)
{
    static QRegExp commitRegex( "^commit (\\w{8})\\w{32}" );
    static QRegExp infoRegex( "^(\\w+):(.*)" );
976 977 978
    static QRegExp modificationsRegex("^([A-Z])[0-9]*\t([^\t]+)\t?(.*)", Qt::CaseSensitive, QRegExp::RegExp2);
    //R099    plugins/git/kdevgit.desktop     plugins/git/kdevgit.desktop.cmake
    //M       plugins/grepview/CMakeLists.txt
979

980 981
    QList<QVariant> commits;

982
    QString contents = job->output();
983 984 985 986 987 988 989
    // check if git-log returned anything
    if (contents.isEmpty()) {
        job->setResults(commits); // empty list
        return;
    }

    // start parsing the output
990 991 992 993 994
    QTextStream s(&contents);

    VcsEvent item;
    QString message;
    bool pushCommit = false;
995
    
996 997
    while (!s.atEnd()) {
        QString line = s.readLine();
998
        
999 1000 1001 1002
        if (commitRegex.exactMatch(line)) {
            if (pushCommit) {
                item.setMessage(message.trimmed());
                commits.append(QVariant::fromValue(item));
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
1003
                item.setItems(QList<VcsItemEvent>());
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
            } else {
                pushCommit = true;
            }
            VcsRevision rev;
            rev.setRevisionValue(commitRegex.cap(1), KDevelop::VcsRevision::GlobalNumber);
            item.setRevision(rev);
            message.clear();
        } else if (infoRegex.exactMatch(line)) {
            QString cap1 = infoRegex.cap(1);
            if (cap1 == "Author") {
                item.setAuthor(infoRegex.cap(2).trimmed());
            } else if (cap1 == "Date") {
                item.setDate(QDateTime::fromTime_t(infoRegex.cap(2).trimmed().split(' ')[0].toUInt()));
            }
1018
        } else if (modificationsRegex.exactMatch(line)) {
1019 1020
            VcsItemEvent::Actions a = actionsFromString(modificationsRegex.cap(1)[0].toAscii());
            QString filenameA = modificationsRegex.cap(2);