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

34 35
#include <interfaces/icore.h>
#include <interfaces/iprojectcontroller.h>
36
#include <interfaces/iproject.h>
37

38 39
#include <vcs/vcsjob.h>
#include <vcs/vcsrevision.h>
40
#include <vcs/vcsevent.h>
41
#include <vcs/dvcs/dvcsjob.h>
42
#include <vcs/vcsannotation.h>
43
#include <vcs/widgets/standardvcslocationwidget.h>
44
#include <KIO/CopyJob>
45
#include "gitclonejob.h"
46 47 48 49
#include <interfaces/contextmenuextension.h>
#include <QMenu>
#include <interfaces/iruncontroller.h>
#include "stashmanagerdialog.h"
50
#include <KMessageBox>
51
#include "gitjob.h"
52 53

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

56 57
using namespace KDevelop;

58 59 60
namespace
{
    
61 62
QDir dotGitDirectory(const KUrl& dirPath)
{
63 64
    const QFileInfo finfo(dirPath.toLocalFile());
    QDir dir = finfo.isDir() ? QDir(dirPath.toLocalFile()) : finfo.absoluteDir();
65 66
    
    static const QString gitDir(".git");
67
    while (!dir.exists(gitDir) && dir.cdUp()) {} // cdUp, until there is a sub-directory called .git
68

69 70 71
    return dir;
}

72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
/**
 * 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;
}

93 94 95 96 97 98 99 100
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:
101
                    return "";
102 103 104 105 106 107
                case VcsRevision::Working:
                    return "";
                case VcsRevision::Previous:
                    Q_ASSERT(!currentRevision.isEmpty());
                    return currentRevision + "^1";
                case VcsRevision::Start:
108 109
                    return "";
                case VcsRevision::UserSpecialType: //Not used
110 111 112 113 114 115 116 117 118 119 120 121 122 123
                    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();
}

124
QString revisionInterval(const KDevelop::VcsRevision& rev, const KDevelop::VcsRevision& limit)
125 126
{
    QString ret;
127 128 129 130 131 132 133 134 135
//     qDebug() << "prrrrrrrrrr" << toRevisionName(rev, "xxx") << toRevisionName(limit, "yyy");
    
    if(rev.revisionType()==VcsRevision::Special &&
                rev.revisionValue().value<VcsRevision::RevisionSpecialType>()==VcsRevision::Start) //if we want it to the begining just put the revisionInterval
        ret = toRevisionName(limit, QString());
    else {
        QString dstRevisionName = toRevisionName(limit);
        ret = toRevisionName(rev, dstRevisionName)+".."+dstRevisionName;
    }
136
    
137
//     qDebug() << "=======>" << ret;
138 139 140
    return ret;
}

141 142 143
QDir urlDir(const KUrl& url) { return QFileInfo(url.toLocalFile()).absoluteDir(); }
QDir urlDir(const KUrl::List& urls) { return urlDir(urls.first()); } //TODO: could be improved

144 145
}

146
GitPlugin::GitPlugin( QObject *parent, const QVariantList & )
147
    : DistributedVersionControlPlugin(parent, KDevGitFactory::componentData()), m_oldVersion(false)
148 149 150 151
{
    KDEV_USE_EXTENSION_INTERFACE( KDevelop::IBasicVersionControl )
    KDEV_USE_EXTENSION_INTERFACE( KDevelop::IDistributedVersionControl )

152
    core()->uiController()->addToolView(i18n("Git"), dvcsViewFactory());
153
    setObjectName("Git");
154 155 156 157 158
    
    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);
159 160 161
}

GitPlugin::~GitPlugin()
162
{}
163

164 165 166 167 168 169 170 171 172 173 174 175 176 177
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));
}

178
bool GitPlugin::hasModifications(const QDir& d)
179
{
180
    return !emptyOutput(lsFiles(d, QStringList("-m"), OutputJob::Silent));
181 182 183 184 185 186 187
}

void GitPlugin::additionalMenuEntries(QMenu* menu, const KUrl::List& urls)
{
    m_urls = urls;
    
    QDir dir=urlDir(urls);
188
    bool modif = hasModifications(dotGitDirectory(urls.first()));
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
    bool canApply = !modif && hasStashes(dir);
    menu->addSeparator()->setText(i18n("Git Stashes"));
    menu->addAction(i18n("Stash Manager"), this, SLOT(ctxStashManager()))->setEnabled(canApply);
    menu->addAction(i18n("Push Stash"), this, SLOT(ctxPushStash()))->setEnabled(modif);
    menu->addAction(i18n("Pop Stash"), this, SLOT(ctxPopStash()))->setEnabled(canApply);
}

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

216
DVcsJob* GitPlugin::errorsFound(const QString& error, KDevelop::OutputJob::OutputJobVerbosity verbosity=OutputJob::Verbose)
217
{
218
    DVcsJob* j = new DVcsJob(QDir::temp(), this, verbosity);
219 220 221 222
    *j << "echo" << i18n("error: %1", error) << "-n";
    return j;
}

223 224 225 226 227 228
void GitPlugin::unload()
{
    core()->uiController()->removeToolView( dvcsViewFactory() );
}


229
QString GitPlugin::name() const
230
{
231 232 233
    return QLatin1String("Git");
}

234 235
KUrl GitPlugin::repositoryRoot(const KUrl& path)
{
236
    return KUrl(dotGitDirectory(path).absolutePath());
237 238
}

239 240
bool GitPlugin::isValidDirectory(const KUrl & dirPath)
{
241
    QDir dir=dotGitDirectory(dirPath);
242

243
    return dir.exists(".git");
244 245 246 247
}

bool GitPlugin::isVersionControlled(const KUrl &path)
{
248
    QFileInfo fsObject(path.toLocalFile());
249
    if (fsObject.isDir()) {
250
        return isValidDirectory(path);
251
    }
252

253 254
    QString filename = fsObject.fileName();

255
    QStringList otherFiles = getLsFiles(fsObject.dir(), QStringList("--") << filename, KDevelop::OutputJob::Silent);
256
    return !otherFiles.empty();
257 258 259 260
}

VcsJob* GitPlugin::init(const KUrl &directory)
{
261 262 263
    DVcsJob* job = new DVcsJob(urlDir(directory), this);
    *job << "git" << "init";
    return job;
264 265
}

266
VcsJob* GitPlugin::createWorkingCopy(const KDevelop::VcsLocation & source, const KUrl& dest, KDevelop::IBasicVersionControl::RecursionMode)
267
{
268 269 270
    DVcsJob* job = new GitCloneJob(urlDir(dest), this);
    *job << "git" << "clone" << "--progress" << "--" << source.localUrl().url() << dest;
    return job;
271 272 273 274 275
}

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

278
    DVcsJob* job = new GitJob(dotGitDirectory(localLocations.front()), this);
279
    *job << "git" << "add" << "--" << (recursion == IBasicVersionControl::Recursive ? localLocations : preventRecursion(localLocations));
280
    return job;
281 282
}

283
KDevelop::VcsJob* GitPlugin::status(const KUrl::List& localLocations, KDevelop::IBasicVersionControl::RecursionMode recursion)
284
{
285 286 287
    if (localLocations.empty())
        return errorsFound(i18n("Did not specify the list of files"), OutputJob::Verbose);

288
    DVcsJob* job = new GitJob(urlDir(localLocations), this, OutputJob::Silent);
289
    
290 291 292 293 294 295 296 297
    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";
        connect(job, SIGNAL(readyForParsing(KDevelop::DVcsJob*)), SLOT(parseGitStatusOutput(KDevelop::DVcsJob*)));
    }
    *job << "--" << (recursion == IBasicVersionControl::Recursive ? localLocations : preventRecursion(localLocations));
298

299
    return job;
300 301
}

302 303 304
VcsJob* GitPlugin::diff(const KUrl& fileOrDirectory, const KDevelop::VcsRevision& srcRevision, const KDevelop::VcsRevision& dstRevision,
                        VcsDiff::Type type, IBasicVersionControl::RecursionMode recursion)
{
305 306
    //TODO: control different types
    
307
    DVcsJob* job = new GitJob(dotGitDirectory(fileOrDirectory), this);
308 309 310 311 312 313
    *job << "git" << "diff" << "--no-prefix";
    QString revstr = revisionInterval(srcRevision, dstRevision);
    if(!revstr.isEmpty())
        *job << revstr;
    
    *job << "--" << (recursion == IBasicVersionControl::Recursive ? fileOrDirectory : preventRecursion(fileOrDirectory));
314
    
315
    connect(job, SIGNAL(readyForParsing(KDevelop::DVcsJob*)), SLOT(parseGitDiffOutput(KDevelop::DVcsJob*)));
316
    return job;
317 318 319 320
}

VcsJob* GitPlugin::revert(const KUrl::List& localLocations, IBasicVersionControl::RecursionMode recursion)
{
321 322 323
    if(localLocations.isEmpty() )
        return errorsFound(i18n("Could not revert changes"), OutputJob::Verbose);
    
324
    DVcsJob* job = new GitJob(dotGitDirectory(localLocations.front()), this);
325 326
    *job << "git" << "checkout" << "--";
    *job << (recursion == IBasicVersionControl::Recursive ? localLocations : preventRecursion(localLocations));
327
    
328
    return job;
329 330 331
}


332 333 334 335 336 337
//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)
{
338
    if (localLocations.empty() || message.isEmpty())
339
        return errorsFound(i18n("No files or message specified"));
340

341
    DVcsJob* job = new GitJob(dotGitDirectory(localLocations.front()), this);
342
    
343
    *job << "git" << "commit" << "-m" << message;
344
    *job << "--" << (recursion == IBasicVersionControl::Recursive ? localLocations : preventRecursion(localLocations));
345
    return job;
346
}
347

348 349
VcsJob* GitPlugin::remove(const KUrl::List& files)
{
350 351 352
    if (files.isEmpty())
        return errorsFound(i18n("No files to remove"));

353
    DVcsJob* job = new GitJob(dotGitDirectory(files.front()), this);
354
    *job << "git" << "rm" << "-r";
355 356
    *job << "--" << files;
    return job;
357 358
}

359
VcsJob* GitPlugin::log(const KUrl& localLocation,
360
                const KDevelop::VcsRevision& src, const KDevelop::VcsRevision& dst)
361
{
362
    DVcsJob* job = new GitJob(dotGitDirectory(localLocation), this);
363 364 365 366
    *job << "git" << "log" << "--date=raw";
    QString rev = revisionInterval(dst, src);
    if(!rev.isEmpty())
        *job << rev;
367
    *job << "--" << localLocation;
368
    connect(job, SIGNAL(readyForParsing(KDevelop::DVcsJob*)), this, SLOT(parseGitLogOutput(KDevelop::DVcsJob*)));
369
    return job;
370 371
}

372

373
VcsJob* GitPlugin::log(const KUrl& localLocation, const KDevelop::VcsRevision& rev, unsigned long int limit)
374
{
375
    DVcsJob* job = new GitJob(dotGitDirectory(localLocation), this, KDevelop::OutputJob::Silent);
376 377 378 379 380 381
    *job << "git" << "log" << "--date=raw" << toRevisionName(rev, QString());
    if(limit>0)
        *job << QString("-%1").arg(limit);
    
    *job << "--" << localLocation;
    connect(job, SIGNAL(readyForParsing(KDevelop::DVcsJob*)), this, SLOT(parseGitLogOutput(KDevelop::DVcsJob*)));
382
    return job;
383 384
}

385 386
KDevelop::VcsJob* GitPlugin::annotate(const KUrl &localLocation, const KDevelop::VcsRevision&)
{
387
    DVcsJob* job = new GitJob(dotGitDirectory(localLocation), this, KDevelop::OutputJob::Silent);
388 389
    *job << "git" << "blame" << "--porcelain";
    *job << "--" << localLocation;
390
    connect(job, SIGNAL(readyForParsing(KDevelop::DVcsJob*)), this, SLOT(parseGitBlameOutput(KDevelop::DVcsJob*)));
391
    return job;
392 393
}

394 395
void GitPlugin::parseGitBlameOutput(DVcsJob *job)
{
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
    QVariantList results;
    VcsAnnotationLine* annotation;
    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);
        
        qDebug() << "last line" << *it;
        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(' ');
            
437
            VcsRevision rev;
438 439 440 441 442 443 444 445 446 447
            rev.setRevisionValue(name, KDevelop::VcsRevision::GlobalNumber);
            
            skipNext = definedRevisions.contains(name);
            
            if(!skipNext)
                definedRevisions.insert(name, VcsAnnotationLine());
            
            annotation = &definedRevisions[name];
            annotation->setLineNumber(values[1].toInt());
            annotation->setRevision(rev);
448 449 450 451
        }
    }
    job->setResults(results);
}
452 453 454

DVcsJob* GitPlugin::switchBranch(const QString &repository, const QString &branch)
{
455 456 457
    QDir d(repository);
    
    if(hasModifications(d) && KMessageBox::questionYesNo(0, i18n("There are pending changes, do you want to stash them first?"))==KMessageBox::Yes) {
458
        QScopedPointer<DVcsJob> stash(gitStash(d, QStringList(), KDevelop::OutputJob::Verbose));
459 460 461 462
        stash->exec();
    }
    
    DVcsJob* job = new DVcsJob(d, this);
463 464
    *job << "git" << "checkout" << branch;
    return job;
465 466 467 468 469
}

DVcsJob* GitPlugin::branch(const QString &repository, const QString &basebranch, const QString &branch,
                             const QStringList &args)
{
470
    DVcsJob* job = new DVcsJob(QDir(repository), this, KDevelop::OutputJob::Silent);
471 472 473 474 475 476 477 478
    *job << "git" << "branch" << args;
    
    *job << "--";
    if (!branch.isEmpty())
        *job << branch;
    if (!basebranch.isEmpty())
        *job << basebranch;
    return job;
479 480
}

481
DVcsJob* GitPlugin::lsFiles(const QDir &repository, const QStringList &args,
482
                            OutputJob::OutputJobVerbosity verbosity)
483
{
484
    DVcsJob* job = new DVcsJob(repository, this, verbosity);
485 486
    *job << "git" << "ls-files" << args;
    return job;
487 488
}

489 490 491 492 493 494 495
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;
}

496 497
QString GitPlugin::curBranch(const QString &repository)
{
498 499
    kDebug() << "Getting branch list";
    
500
    QScopedPointer<DVcsJob> job(new DVcsJob(QDir(repository), this, OutputJob::Silent));
501
    *job << "git" << "symbolic-ref" << "HEAD";
502 503
    if (job->exec() && job->status() == KDevelop::VcsJob::JobSucceeded) {
        QString out = job->output();
504 505 506
        int slashPos = out.lastIndexOf('/')+1;
        kDebug() << "Getting branch list" << out.mid(slashPos, out.size()-slashPos).trimmed();
        return out.mid(slashPos, out.size()-slashPos).trimmed();
507
    }
508
    return QString();
509 510 511 512
}

QStringList GitPlugin::branches(const QString &repository)
{
513
    QStringList branchListDirty;
514 515 516 517 518 519 520
    QScopedPointer<DVcsJob> job(branch(repository));
    kDebug() << "Getting branch list";
    
    if (job->exec() && job->status() == KDevelop::VcsJob::JobSucceeded)
        branchListDirty = job->output().split('\n', QString::SkipEmptyParts);
    else
        return QStringList();
521 522 523 524 525 526 527 528 529 530 531 532

    QStringList branchList;
    foreach(QString branch, branchListDirty)
    {
        if (branch.contains('*'))
        {
            branch = branch.prepend('\n').section("\n*", 1);
        }
        else
        {
            branch = branch.prepend('\n').section('\n', 1);
        }
533 534
        
        branch = branch.trimmed();
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
        branchList<<branch;
    }
    return branchList;
}

/* 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)
{
    static bool hasHash = false;
    if (!hasHash)
    {
        initBranchHash(repo);
        hasHash = true;
    }
    QStringList args;
    args << "--all" << "--pretty" << "--parents";
571 572 573
    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");
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
    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());
    foreach(int flag, additionalFlags)
        flag = false;

    //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)
{
    QStringList branches = GitPlugin::branches(repo);
    kDebug() << "BRANCHES: " << branches;
    //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
    QString root = GitPlugin::curBranch(repo);
736 737 738
    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");
739 740 741 742 743 744 745 746 747 748 749 750 751 752
    QStringList commits = job->output().split('\n', QString::SkipEmptyParts);
//     kDebug() << "\n\n\n commits" << commits << "\n\n\n";
    branchesShas.append(commits);
    foreach(const QString &branch, branches)
    {
        if (branch == root)
            continue;
        QStringList args(branch);
        foreach(const QString &branch_arg, branches)
        {
            if (branch_arg != branch)
                //man gitRevList for '^'
                args<<'^' + branch_arg;
        }
753 754 755
        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");
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
        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';
        }
    }
}

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
void GitPlugin::parseGitLogOutput(DVcsJob * job)
{
    QList<QVariant> commits;
    static QRegExp commitRegex( "^commit (\\w{8})\\w{32}" );
    static QRegExp infoRegex( "^(\\w+):(.*)" );

    QString contents = job->output();
    QTextStream s(&contents);

    VcsEvent item;
    QString message;
    bool pushCommit = false;
    while (!s.atEnd()) {
        QString line = s.readLine();
        if (commitRegex.exactMatch(line)) {
            if (pushCommit) {
                item.setMessage(message.trimmed());
                commits.append(QVariant::fromValue(item));
            } 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()));
            }
        } else if (line.startsWith("    ")) {
            message += line.remove(0, 4);
            message += '\n';
        }
    }
834
    
835 836 837 838 839
    item.setMessage(message.trimmed());
    commits.append(QVariant::fromValue(item));
    job->setResults(commits);
}

840 841
void GitPlugin::parseGitDiffOutput(DVcsJob* job)
{
842 843
    VcsDiff diff;
    diff.setDiff(job->output());
844
    diff.setBaseDiff(repositoryRoot(KUrl(job->directory().absolutePath())));
845 846
    
    job->setResults(qVariantFromValue(diff));
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
static VcsStatusInfo::State lsfilesToState(char id)
{
    switch(id) {
        case 'H': return VcsStatusInfo::ItemUpToDate; //Cached
        case 'S': return VcsStatusInfo::ItemUpToDate; //Skip work tree
        case 'M': return VcsStatusInfo::ItemHasConflicts; //unmerged
        case 'R': return VcsStatusInfo::ItemDeleted; //removed/deleted
        case 'C': return VcsStatusInfo::ItemModified; //modified/changed
        case 'K': return VcsStatusInfo::ItemDeleted; //to be killed
        case '?': return VcsStatusInfo::ItemUnknown; //other
    }
    Q_ASSERT(false);
    return VcsStatusInfo::ItemUnknown;
}

void GitPlugin::parseGitStatusOutput_old(DVcsJob* job)
{
    QStringList outputLines = job->output().split('\n', QString::SkipEmptyParts);
    
    KUrl d = job->directory().absolutePath();
    QMap<KUrl, VcsStatusInfo::State> allStatus;
    foreach(const QString& line, outputLines) {
        VcsStatusInfo::State status = lsfilesToState(line[0].toAscii());
        
        KUrl url = d;
        url.addPath(line.right(line.size()-2));
        
        allStatus[url] = status;
    }
    
    QVariantList statuses;
    QMap< KUrl, VcsStatusInfo::State >::const_iterator it = allStatus.constBegin(), itEnd=allStatus.constEnd();
    for(; it!=itEnd; ++it) {
        
        VcsStatusInfo status;
        status.setUrl(it.key());
        status.setState(it.value());
        
        statuses.append(qVariantFromValue<VcsStatusInfo>(status));
    }
    
    job->setResults(statuses);
}

893 894
void GitPlugin::parseGitStatusOutput(DVcsJob* job)
{
895
    QStringList outputLines = job->output().split('\n', QString::SkipEmptyParts);
896
    const KUrl workingDir = job->directory().absolutePath();
897
    const KUrl dotGit = dotGitDirectory(workingDir).absolutePath();
898 899
    
    QVariantList statuses;
900
    QList<KUrl> processedFiles;
901
    
902
    foreach(const QString& line, outputLines) {
903 904 905 906 907 908 909
        //every line is 2 chars for the status, 1 space then the file desc
        QString curr=line.right(line.size()-3);
        QString state = line.left(2);
        
        int arrow = curr.indexOf("-> ");
        if(arrow>=0)
            curr = curr.right(curr.size()-arrow-3);
910
        
911
        KUrl fileUrl = dotGit;
912 913
        fileUrl.addPath(curr);
        processedFiles.append(fileUrl);
914 915 916
        
        VcsStatusInfo status;
        status.setUrl(fileUrl);
917 918 919
        status.setState(messageToState(state));
        
        kDebug() << "Checking git status for " << line << curr << messageToState(state);
920 921 922
        
        statuses.append(qVariantFromValue<VcsStatusInfo>(status));
    }
923 924 925 926 927
    QStringList paths;
    QStringList oldcmd=job->dvcsCommand();
    QStringList::const_iterator it=oldcmd.constBegin()+oldcmd.indexOf("--")+1, itEnd=oldcmd.constEnd();
    for(; it!=itEnd; ++it)
        paths += *it;
928
    
929
    //here we add the already up to date files
930
    QStringList files = getLsFiles(job->directory(), QStringList() << "-c" << "--" << paths, OutputJob::Silent);
931 932 933 934 935 936 937 938 939 940 941 942
    foreach(const QString& file, files) {
        KUrl fileUrl = workingDir;
        fileUrl.addPath(file);
        
        if(!processedFiles.contains(fileUrl)) {
            VcsStatusInfo status;
            status.setUrl(fileUrl);
            status.setState(VcsStatusInfo::ItemUpToDate);
            
            statuses.append(qVariantFromValue<VcsStatusInfo>(status));
        }
    }
943 944 945
    job->setResults(statuses);
}

946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
void GitPlugin::parseGitVersionOutput(DVcsJob* job)
{
    QStringList versionString = job->output().trimmed().split(' ').last().split('.');
    static QList<int> minimumVersion = QList<int>() << 1 << 7;
    
    kDebug() << "checking git version" << versionString << "against" << minimumVersion;
    m_oldVersion = false;
    foreach(int num, minimumVersion) {
        QString curr = versionString.takeFirst();
        int valcurr = curr.toInt();
        m_oldVersion |= valcurr<num;
    }
    kDebug() << "the current git version is old: " << m_oldVersion;
}

961
QStringList GitPlugin::getLsFiles(const QDir &directory, const QStringList &args,
962
    KDevelop::OutputJob::OutputJobVerbosity verbosity)
963
{
964
    QScopedPointer<DVcsJob> job(lsFiles(directory, args, verbosity));
965 966 967
    if (job->exec() && job->status() == KDevelop::VcsJob::JobSucceeded)
        return job->output().split('\n', QString::SkipEmptyParts);
    
968 969 970
    return QStringList();
}

971 972
DVcsJob* GitPlugin::gitRevParse(const QString &repository, const QStringList &args,
    KDevelop::OutputJob::OutputJobVerbosity verbosity)
973
{
974
    DVcsJob* job = new DVcsJob(QDir(repository), this, verbosity);
975
    *job << "git" << "rev-parse" << args;
976

977
    return job;
978 979 980 981
}

DVcsJob* GitPlugin::gitRevList(const QString &repository, const QStringList &args)
{
982 983
    DVcsJob* job = new DVcsJob(QDir(repository), this);
    {
984
        *job << "git" << "rev-list" << args;
985 986 987 988
        return job;
    }
}

989
VcsStatusInfo::State GitPlugin::messageToState(const QString& msg)
990
{
991 992 993 994 995 996
    Q_ASSERT(msg.size()==1 || msg.size()==2);
    VcsStatusInfo::State ret = VcsStatusInfo::ItemUnknown;
    
    if(msg.contains('U') || msg == "AA" || msg == "DD")
        ret = VcsStatusInfo::ItemHasConflicts;
    else switch(msg[0].toAscii())
997 998
    {
        case 'M':
999 1000
            ret = VcsStatusInfo::ItemModified;
            break;
1001
        case 'A':
1002 1003
            ret = VcsStatusInfo::ItemAdded;
            break;
1004 1005 1006 1007 1008 1009 1010
        case 'R':
        case 'C':
            ret = VcsStatusInfo::ItemModified;
            break;
        case ' ':
            ret = msg[1] == 'M' ? VcsStatusInfo::ItemModified : VcsStatusInfo::ItemDeleted;
            break;
1011
        case 'D':
1012 1013 1014 1015 1016
            ret = VcsStatusInfo::ItemDeleted;
            break;
        case '?':
            ret = VcsStatusInfo::ItemUnknown;
            break;
1017 1018 1019
        default:
            kDebug() << "Git status not identified:" << msg;
            break;
1020
    }
1021 1022
    
    return ret;
1023 1024
}

1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
StandardCopyJob::StandardCopyJob(IPlugin* parent, const KUrl& source, const KUrl& dest,
                                 OutputJob::OutputJobVerbosity verbosity)
    : VcsJob(parent, verbosity)
    , m_source(source), m_dest(dest)
    , m_plugin(parent)
    , m_status(JobNotStarted)
{}

void StandardCopyJob::start()
{
    KIO::CopyJob* job=KIO::copy(m_source, m_dest);
    connect(job, SIGNAL(result(KJob*)), SLOT(result(KJob*)));
    job->start();
    m_status=JobRunning;
}

void StandardCopyJob::result(KJob* job)
{
    m_status=job->error() == 0? JobSucceeded : JobFailed; emitResult();
}

VcsJob* GitPlugin::copy(const KUrl& localLocationSrc, const KUrl& localLocationDstn)
{
    //TODO: Probably we should "git add" after
    return new StandardCopyJob(this, localLocationSrc, localLocationDstn, KDevelop::OutputJob::Silent);
}

VcsJob* GitPlugin::move(const KUrl& source, const KUrl& destination)
{
1054 1055
    DVcsJob* job = new DVcsJob(urlDir(source), this, KDevelop::OutputJob::Verbose);
    {
1056 1057 1058 1059 1060
        *job << "git" << "mv" << source.toLocalFile() << destination.toLocalFile();
        return job;
    }
}

1061 1062 1063 1064 1065 1066 1067
void GitPlugin::parseGitRepoLocationOutput(DVcsJob* job)
{
    job->setResults(qVariantFromValue(KUrl(job->output())));
}

VcsJob* GitPlugin::repositoryLocation(const KUrl& localLocation)
{
1068
    DVcsJob* job = new DVcsJob(urlDir(localLocation), this);
1069 1070 1071 1072
    //Probably we should check first if origin is the proper remote we have to use but as a first attempt it works
    *job << "git" << "config" << "remote.origin.url";
    connect(job, SIGNAL(readyForParsing(KDevelop::DVcsJob*)), SLOT(parseGitRepoLocationOutput(KDevelop::DVcsJob*)));
    return job;
1073 1074
}

1075 1076
VcsJob* GitPlugin::pull(const KDevelop::VcsLocation& localOrRepoLocationSrc, const KUrl& localRepositoryLocation)
{
1077
    DVcsJob* job = new DVcsJob(urlDir(localRepositoryLocation), this);
1078 1079 1080 1081
    job->setCommunicationMode(KProcess::MergedChannels);
    *job << "git" << "pull";
    if(!localOrRepoLocationSrc.localUrl().isEmpty())
        *job << localOrRepoLocationSrc.localUrl().url();
1082
    return job;
1083 1084 1085 1086
}

VcsJob* GitPlugin::push(const KUrl& localRepositoryLocation, const KDevelop::VcsLocation& localOrRepoLocationDst)
{
1087
    DVcsJob* job = new DVcsJob(urlDir(localRepositoryLocation), this);
1088
    job->setCommunicationMode(KProcess::MergedChannels);
1089 1090 1091
    *job << "git" << "push";
    if(!localOrRepoLocationDst.localUrl().isEmpty())
        *job << localOrRepoLocationDst.localUrl().url();
1092
    return job;
1093 1094 1095 1096
}

VcsJob* GitPlugin::resolve(const KUrl::List& localLocations, IBasicVersionControl::RecursionMode recursion)
{
1097
    return add(localLocations, recursion);
1098 1099 1100 1101
}

VcsJob* GitPlugin::update(const KUrl::List& localLocations, const KDevelop::VcsRevision& rev, IBasicVersionControl::RecursionMode recursion)
{
1102 1103 1104
    if(rev.revisionType()==VcsRevision::Special && rev.revisionValue().value<VcsRevision::RevisionSpecialType>()==VcsRevision::Head) {
        return pull(VcsLocation(), localLocations.first());
    } else {
1105 1106
        DVcsJob* job = new DVcsJob(urlDir(localLocations.first().toLocalFile()), this);
        {
1107 1108
            //Probably we should check first if origin is the proper remote we have to use but as a first attempt it works
            *job << "git" << "checkout" << rev.revisionValue().toString() << "--";
1109
            *job << (recursion == IBasicVersionControl::Recursive ? localLocations : preventRecursion(localLocations));