gitplugin.cpp 36.4 KB
Newer Older
1 2
/***************************************************************************
 *   Copyright 2008 Evgeniy Ivanov <powerfox@kde.ru>                       *
3
 *   Copyright 2009 Hugo Parente Lima <hugo.pl@gmail.com>                  *
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 *                                                                         *
 *   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>
26 27 28 29 30
#include <KLocalizedString>
#include <KAboutData>
#include <KDebug>
#include <QFileInfo>
#include <QDir>
31

32 33
#include <interfaces/icore.h>
#include <interfaces/iprojectcontroller.h>
34
#include <interfaces/iproject.h>
35

36 37
#include <vcs/vcsjob.h>
#include <vcs/vcsrevision.h>
38
#include <vcs/vcsevent.h>
39
#include <vcs/dvcs/dvcsjob.h>
40
#include <vcs/vcsannotation.h>
41
#include <vcs/widgets/standardvcslocationwidget.h>
42
#include <QDateTime>
43
#include <KIO/CopyJob>
44 45

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

48 49
using namespace KDevelop;

50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
QDir dotGitDirectory(const KUrl& dirPath)
{
    const QString initialPath(dirPath.toLocalFile(KUrl::RemoveTrailingSlash));
    const QFileInfo finfo(initialPath);
    QDir dir;
    if (finfo.isFile()) {
        dir = finfo.absoluteDir();
    } else {
        dir = QDir(initialPath);
        dir.makeAbsolute();
    }
    
    static const QString gitDir(".git");
    while (!dir.cd(gitDir) && dir.cdUp()) {} // cdUp, until there is a sub-directory called .git
    return dir;
}

67
GitPlugin::GitPlugin( QObject *parent, const QVariantList & )
68
    : DistributedVersionControlPlugin(parent, KDevGitFactory::componentData())
69 70 71 72
{
    KDEV_USE_EXTENSION_INTERFACE( KDevelop::IBasicVersionControl )
    KDEV_USE_EXTENSION_INTERFACE( KDevelop::IDistributedVersionControl )

73 74 75
    QString EasterEgg = i18n("Thanks for the translation! Have a nice day, mr. translator!");
    Q_UNUSED(EasterEgg)

76
    core()->uiController()->addToolView(i18n("Git"), dvcsViewFactory());
Andreas Pakulat's avatar
Andreas Pakulat committed
77
    setXMLFile("kdevgit.rc");
78 79 80
}

GitPlugin::~GitPlugin()
81
{}
82

83 84 85 86 87 88 89
DVcsJob* GitPlugin::errorsFound(const QString& error, KDevelop::OutputJob::OutputJobVerbosity verbosity)
{
    DVcsJob* j = new DVcsJob(this, verbosity);
    *j << "echo" << i18n("error: %1", error) << "-n";
    return j;
}

90 91 92 93 94 95
void GitPlugin::unload()
{
    core()->uiController()->removeToolView( dvcsViewFactory() );
}


96
QString GitPlugin::name() const
97
{
98 99 100 101 102
    return QLatin1String("Git");
}

bool GitPlugin::isValidDirectory(const KUrl & dirPath)
{
103 104
    KUrl possibleRepoRoot = m_lastRepoRoot;
    if (!m_lastRepoRoot.isValid() || !m_lastRepoRoot.isParentOf(dirPath)) {
105
        QDir dir=dotGitDirectory(dirPath);
106

107 108
        if (".git" != dir.dirName()) {  // We didn't find .git, so no need to call git
            kDebug() << "Dir:" << dirPath << " is not inside work tree of git \"" << dirPath << '"';
109 110 111 112 113 114 115
            return false;
        }
        dir.cdUp();
        possibleRepoRoot.setDirectory(dir.absolutePath());
    }

    // We might have found a valid repository, call git to verify it
116
    KDevelop::VcsJob* job = gitRevParse(possibleRepoRoot.toLocalFile(), QStringList(QString("--is-inside-work-tree")), KDevelop::OutputJob::Silent);
117 118 119 120 121 122

    if (!job) {
        kDebug() << "Failed creating job";
        return false;
    }

123
    job->exec();
124 125 126
    if (job->status() == KDevelop::VcsJob::JobSucceeded) {
        kDebug() << "Dir:" << dirPath << " is inside work tree of git (" << possibleRepoRoot << ')';
        m_lastRepoRoot = possibleRepoRoot;
127
        return true;
128
    } else if (m_lastRepoRoot == possibleRepoRoot) {   // Not a repository anymore
129
        m_lastRepoRoot.clear(); // Restart from scratch
130
        return isValidDirectory(dirPath);
131
    }
132

133 134 135 136 137
    return false;
}

bool GitPlugin::isVersionControlled(const KUrl &path)
{
138
    QFileInfo fsObject(path.toLocalFile());
139
    if (fsObject.isDir()) {
140
        return isValidDirectory(path);
141
    }
142

143 144 145 146 147
    QString workDir = fsObject.path();
    QString filename = fsObject.fileName();

    QStringList listfiles("--");
    listfiles.append(filename);
148
    QStringList otherFiles = getLsFiles(workDir, listfiles, KDevelop::OutputJob::Silent);
149
    return !otherFiles.empty();
150 151 152 153 154 155 156 157 158 159
}

VcsJob* GitPlugin::init(const KUrl &directory)
{
    DVcsJob* job = new DVcsJob(this);
    if (prepareJob(job, directory.toLocalFile(), GitPlugin::Init) ) {
        *job << "git";
        *job << "init";
        return job;
    }
160
    delete job;
161
    return errorsFound(i18n("Could not initialize the repository"), OutputJob::Verbose);
162 163
}

164
VcsJob* GitPlugin::createWorkingCopy(const KDevelop::VcsLocation & localOrRepoLocationSrc, const KUrl& localRepositoryRoot, KDevelop::IBasicVersionControl::RecursionMode)
165 166 167
{
    DVcsJob* job = new DVcsJob(this);
    if (prepareJob(job, localRepositoryRoot.toLocalFile(), GitPlugin::Init) ) {
168
        *job << "git" << "clone" << "--" << localOrRepoLocationSrc.localUrl().prettyUrl();
169 170
        return job;
    }
171
    delete job;
172
    return errorsFound(i18n("Could not create the working copy"), OutputJob::Verbose);
173 174 175 176 177 178
}

VcsJob* GitPlugin::add(const KUrl::List& localLocations, KDevelop::IBasicVersionControl::RecursionMode recursion)
{
    Q_UNUSED(recursion)
    if (localLocations.empty())
179
        return 0;
180 181

    DVcsJob* job = new DVcsJob(this);
182
    if (prepareJob(job, localLocations.front().toLocalFile()) ) {
183 184
        *job << "git";
        *job << "add";
185
        *job << "--";
186 187 188 189
        addFileList(job, localLocations);

        return job;
    }
190
    delete job;
191
    return errorsFound(i18n("Could not add the files"), OutputJob::Verbose);
192 193 194 195 196 197 198 199 200 201 202
}

KDevelop::VcsJob* GitPlugin::status(const KUrl::List& localLocations,
                            KDevelop::IBasicVersionControl::RecursionMode recursion)
{
    Q_UNUSED(recursion)
    //it's a hack!!! See VcsCommitDialog::setCommitCandidates and the usage of DVcsJob/IDVCSexecutor
    //We need results just in status, so we set them here before execution in VcsCommitDialog::setCommitCandidates
    QString repo = localLocations[0].toLocalFile();
    QList<QVariant> statuses;
    qDebug("GitPlugin::status");
203 204 205 206
    statuses << getCachedFiles(repo, KDevelop::OutputJob::Silent)
             << getModifiedFiles(repo, KDevelop::OutputJob::Silent)
             << getOtherFiles(repo, KDevelop::OutputJob::Silent);
    DVcsJob * noOp = empty_cmd(KDevelop::OutputJob::Silent);
207 208 209 210
    noOp->setResults(QVariant(statuses));
    return noOp;
}

211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
QString toRevisionName(const KDevelop::VcsRevision& rev)
{
    switch(rev.revisionType()) {
        case VcsRevision::Special:
            switch(rev.revisionValue().value<VcsRevision::RevisionSpecialType>()) {
                case VcsRevision::Head:
                    return "^HEAD";
                case VcsRevision::Base:
                    return "HEAD";
                case VcsRevision::Working:
                    return "";
                case VcsRevision::Previous:
                case VcsRevision::Start:
                    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:
            Q_ASSERT(false);
    }
    return QString();
}

237 238 239
VcsJob* GitPlugin::diff(const KUrl& fileOrDirectory, const KDevelop::VcsRevision& srcRevision, const KDevelop::VcsRevision& dstRevision,
                        VcsDiff::Type type, IBasicVersionControl::RecursionMode recursion)
{
240 241
    //TODO: control different types
    
242 243 244
    DVcsJob* job = new DVcsJob(this);
    if (prepareJob(job, fileOrDirectory.toLocalFile()) ) {
        KUrl::List files;
245 246
        if(QFileInfo(fileOrDirectory.toLocalFile()).isDir() && recursion==IBasicVersionControl::NonRecursive)
            files = getLsFiles(fileOrDirectory.toLocalFile(), QStringList(), KDevelop::OutputJob::Silent);
247 248
        else
            files = fileOrDirectory;
249 250 251
        QDir dotgit=dotGitDirectory(fileOrDirectory);
        if(dotgit.cdUp())
            job->setDirectory(dotgit);
252
        
253 254 255 256 257
        *job << "git" << "diff" << "--no-prefix";
        if(dstRevision.revisionType()==VcsRevision::Special)
            *job << toRevisionName(srcRevision);
        else
            *job << toRevisionName(srcRevision)+".."+toRevisionName(dstRevision);
258 259 260
        *job << "--";
        addFileList(job, files);
        
261
        connect(job, SIGNAL(readyForParsing(DVcsJob*)), SLOT(parseGitDiffOutput(DVcsJob*)));
262 263 264
        return job;
    }
    
265
    delete job;
266
    return errorsFound(i18n("Could not create the patch"), OutputJob::Verbose);
267 268 269 270 271 272 273 274 275 276 277 278 279 280
}

VcsJob* GitPlugin::revert(const KUrl::List& localLocations, IBasicVersionControl::RecursionMode recursion)
{
    DVcsJob* job = new DVcsJob(this);
    if (!localLocations.isEmpty() && prepareJob(job, localLocations.first().toLocalFile()) ) {
        *job << "git" << "checkout";
        *job << "--";
        addFileList(job, localLocations);
        
        return job;
    }
    
    delete job;
281
    return errorsFound(i18n("Could not revert changes"), OutputJob::Verbose);
282 283 284
}


285 286 287 288 289 290 291 292
//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)
{
    Q_UNUSED(recursion)

293
    if (localLocations.empty() || message.isEmpty())
294
        return 0;
295 296

    DVcsJob* job = new DVcsJob(this);
297
    if (prepareJob(job, localLocations.front().toLocalFile()) ) {
298 299 300 301 302
        *job << "git";
        *job << "commit";
        *job << "-m";
        //Note: the message is quoted somewhere else, so if we quote here then we have quotes in the commit log
        *job << message;
303 304
        *job << "--";
        addFileList(job, localLocations);
305 306
        return job;
    }
307
    delete job;
308
    return errorsFound(i18n("Committing failed"), OutputJob::Verbose);
309
}
310

311 312 313
VcsJob* GitPlugin::remove(const KUrl::List& files)
{
    if (files.empty())
314
        return 0;
315 316

    DVcsJob* job = new DVcsJob(this);
317
    if (prepareJob(job, files.front().toLocalFile()) ) {
318 319
        *job << "git";
        *job << "rm";
320
        *job << "--";
321 322 323
        addFileList(job, files);
        return job;
    }
324
    delete job;
325
    return errorsFound(i18n("Could not remove the files"), OutputJob::Verbose);
326 327
}

328 329 330 331 332 333 334 335

VcsJob* GitPlugin::log(const KUrl& localLocation,
                const KDevelop::VcsRevision& rev,
                unsigned long limit)
{
    Q_UNUSED(rev)
    Q_UNUSED(limit)
    DVcsJob* job = new DVcsJob(this);
336
    if (prepareJob(job, localLocation.toLocalFile()) ) {
337 338
        *job << "git";
        *job << "log";
339
        *job << "--date=raw";
340
        *job << "--";
341
        addFileList(job, localLocation);
342
        connect(job, SIGNAL(readyForParsing(DVcsJob*)), this, SLOT(parseGitLogOutput(DVcsJob*)));
343 344
        return job;
    }
345
    delete job;
346
    return errorsFound(i18n("Could not generate the log"), OutputJob::Verbose);
347 348
}

349 350
KDevelop::VcsJob* GitPlugin::annotate(const KUrl &localLocation, const KDevelop::VcsRevision&)
{
351 352 353 354 355 356
    DVcsJob* job = new DVcsJob(this);
    if (prepareJob(job, localLocation.toLocalFile()) ) {
        *job << "git";
        *job << "blame";
        *job << "--root";
        *job << "-t";
357
        *job << "--";
358 359 360
        addFileList(job, localLocation);
        connect(job, SIGNAL(readyForParsing(DVcsJob*)), this, SLOT(parseGitBlameOutput(DVcsJob*)));
    }
361 362
    delete job;
    return errorsFound(i18n("Could not read the annotations"), OutputJob::Verbose);
363 364
}

365 366
void GitPlugin::parseGitBlameOutput(DVcsJob *job)
{
367 368
    QList<QVariant> results;
    int lineNumber = 0;
369 370
    /*static? */QRegExp regex("(\\w{8}) .* ?\\((.*) (\\d+) [-+]\\d+\\s+\\d+\\)");
    foreach(const QString& line, job->output().split('\n')) {
371 372 373 374 375 376 377 378 379 380 381 382 383 384
        if (regex.indexIn(line) == 0) {
            VcsAnnotationLine annotation;
            annotation.setAuthor(regex.cap(2));
            annotation.setDate(QDateTime::fromTime_t(regex.cap(3).toUInt()));
            annotation.setLineNumber(lineNumber);
            VcsRevision rev;
            rev.setRevisionValue(regex.cap(1), KDevelop::VcsRevision::GlobalNumber);
            annotation.setRevision(rev);
            results << QVariant::fromValue(annotation);
        }
        lineNumber++;
    }
    job->setResults(results);
}
385 386 387 388 389 390 391 392 393 394

DVcsJob* GitPlugin::var(const QString & repository)
{
    DVcsJob* job = new DVcsJob(this);
    if (prepareJob(job, repository) ) {
        *job << "git";
        *job << "var";
        *job << "-l";
        return job;
    }
395
    delete job;
396
    return errorsFound(i18n("Could not retrieve some repository variable"), OutputJob::Verbose);
397 398 399 400 401 402 403 404 405 406 407 408
}

DVcsJob* GitPlugin::switchBranch(const QString &repository, const QString &branch)
{
    ///TODO Check if the branch exists. or send only existed branch names here!
    DVcsJob* job = new DVcsJob(this);
    if (prepareJob(job, repository) ) {
        *job << "git";
        *job << "checkout";
        *job << branch;
        return job;
    }
409
    
410
    delete job;
411
    return errorsFound(i18n("Could not switch the branch"), OutputJob::Verbose);
412 413 414 415 416 417 418 419 420 421 422 423
}

DVcsJob* GitPlugin::branch(const QString &repository, const QString &basebranch, const QString &branch,
                             const QStringList &args)
{
    DVcsJob* job = new DVcsJob(this);
    if (prepareJob(job, repository) ) {
        *job << "git";
        *job << "branch";
        //Empty branch has 'something' so it breaks the command
        if (!args.isEmpty())
            *job << args;
424
        *job << "--";
425 426 427 428 429 430
        if (!branch.isEmpty())
            *job << branch;
        if (!basebranch.isEmpty())
            *job << basebranch;
        return job;
    }
431
    delete job;
432
    return errorsFound(i18n("Could not create the new branch"), OutputJob::Verbose);
433 434 435 436 437
}

VcsJob* GitPlugin::reset(const KUrl& repository, const QStringList &args, const KUrl::List& files)
{
    if (files.empty())
438
        return 0;
439 440

    DVcsJob* job = new DVcsJob(this);
441
    if (prepareJob(job, repository.toLocalFile()) ) {
442 443 444 445 446
        *job << "git";
        *job << "reset";
        //Empty branch has 'something' so it breaks the command
        if (!args.isEmpty())
            *job << args;
447
        *job << "--";
448 449 450
        addFileList(job, files);
        return job;
    }
451
    delete job;
452
    return errorsFound(i18n("Could not reset"), OutputJob::Verbose);
453 454
}

455 456
DVcsJob* GitPlugin::lsFiles(const QString &repository, const QStringList &args,
    KDevelop::OutputJob::OutputJobVerbosity verbosity)
457
{
458
    DVcsJob* job = new DVcsJob(this, verbosity);
459 460 461 462 463 464 465 466
    if (prepareJob(job, repository) ) {
        *job << "git";
        *job << "ls-files";
        //Empty branch has 'something' so it breaks the command
        if (!args.isEmpty())
            *job << args;
        return job;
    }
467
    delete job;
468
    return errorsFound(i18n("Could not list files"), OutputJob::Verbose);
469 470 471 472
}

QString GitPlugin::curBranch(const QString &repository)
{
473
    QString branchName;
474 475 476 477 478
    DVcsJob* job = branch(repository);
    if (job)
    {
        kDebug() << "Getting branch list";
        job->exec();
479 480 481
        
        if (job->status() == KDevelop::VcsJob::JobSucceeded)
            branchName = job->output();
482 483
    }

484 485 486 487
    branchName = branchName.prepend('\n').section("\n*", 1);
    branchName = branchName.section('\n', 0, 0).trimmed();
    kDebug() << "Current branch is: " << branchName;
    return branchName;
488 489 490 491
}

QStringList GitPlugin::branches(const QString &repository)
{
492
    QStringList branchListDirty;
493 494 495 496 497
    DVcsJob* job = branch(repository);
    if (job)
    {
        kDebug() << "Getting branch list";
        job->exec();
498 499 500 501 502
        
        if (job->status() == KDevelop::VcsJob::JobSucceeded)
            branchListDirty = job->output().split('\n', QString::SkipEmptyParts);
        else
            return QStringList();
503 504 505 506 507 508 509 510 511 512 513 514 515
    }

    QStringList branchList;
    foreach(QString branch, branchListDirty)
    {
        if (branch.contains('*'))
        {
            branch = branch.prepend('\n').section("\n*", 1);
        }
        else
        {
            branch = branch.prepend('\n').section('\n', 1);
        }
516 517
        
        branch = branch.trimmed();
518 519 520 521 522
        branchList<<branch;
    }
    return branchList;
}

523
QList<QVariant> GitPlugin::getOtherFiles(const QString& directory, OutputJob::OutputJobVerbosity verbosity)
524
{
525
    QStringList otherFiles = getLsFiles(directory, QStringList(QString("--others")), verbosity );
526 527 528 529 530 531 532 533 534 535 536 537

    QList<QVariant> others;
    foreach(const QString &file, otherFiles)
    {
        VcsStatusInfo status;
        status.setUrl(stripPathToDir(directory) + file);
        status.setState(VcsStatusInfo::ItemUnknown);
        others.append(qVariantFromValue<VcsStatusInfo>(status));
    }
    return others;
}

538
QList<QVariant> GitPlugin::getModifiedFiles(const QString &directory, KDevelop::OutputJob::OutputJobVerbosity verbosity)
539
{
540
    DVcsJob* job = new DVcsJob(this, verbosity);
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
    if (prepareJob(job, directory) )
        *job << "git";
        *job << "diff-files";
    if (job)
        job->exec();
    QStringList output;
    if (job->status() == KDevelop::VcsJob::JobSucceeded)
        output = job->output().split('\n', QString::SkipEmptyParts);
    else
        return QList<QVariant>();

    QList<QVariant> modifiedFiles;
    foreach(const QString &line, output)
    {
        KUrl file(stripPathToDir(directory) + line.section('\t', 1).trimmed());

        VcsStatusInfo status;
        status.setUrl(file);
559
        status.setState(charToState(line.section(' ', 4, 4)[0].toAscii()) );
560
        kDebug() << line[97] << " " << file.toLocalFile();
561 562 563 564 565 566 567

        modifiedFiles.append(qVariantFromValue<VcsStatusInfo>(status));
    }

    return modifiedFiles;
}

568
QList<QVariant> GitPlugin::getCachedFiles(const QString &directory, KDevelop::OutputJob::OutputJobVerbosity verbosity)
569
{
570
    DVcsJob* job = gitRevParse(directory, QStringList(QString("--branches")), verbosity);
571 572 573 574 575 576 577 578
    job->exec();
    QStringList shaArg;
    if (job->output().isEmpty())
    {
        //there is no branches, which means there is no commit yet
        //let's create an empty tree to use with git-diff-index
        //TODO: in newer version of git (AFAIK 1.5.5) we can do:
        //"git diff-index $(git rev-parse -q --verify HEAD  || echo 4b825dc642cb6eb9a060e54bf8d69288fbee4904)"
579
        DVcsJob* job = new DVcsJob(this, verbosity);
580 581 582 583 584 585 586 587 588 589 590
        if (prepareJob(job, directory) )
        {
            *job << "git";
            *job << "mktree";
            job->setStandardInputFile("/dev/null");
        }
        if (job && job->exec() && job->status() == KDevelop::VcsJob::JobSucceeded)
            shaArg<<job->output().split('\n', QString::SkipEmptyParts);
    }
    else
        shaArg<<"HEAD";
591
    job = new DVcsJob(this, verbosity);
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
    if (prepareJob(job, directory) )
        *job << "git" << "diff-index" << "--cached" << shaArg;
    if (job)
        job->exec();
    QStringList output;
    if (job->status() == KDevelop::VcsJob::JobSucceeded)
        output = job->output().split('\n', QString::SkipEmptyParts);
    else
        return QList<QVariant>();

    QList<QVariant> cachedFiles;

    foreach(const QString &line, output)
    {
        KUrl file(stripPathToDir(directory) + line.section('\t', 1).trimmed());

        VcsStatusInfo status;
        status.setUrl(file);
610 611 612
        
        status.setState(VcsStatusInfo::State(charToState(line.section(' ', 4, 4)[0].toAscii() ) +
                                             VcsStatusInfo::ItemAdded) );
613

614
        kDebug() << line[97] << " " << file.toLocalFile();
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878

        cachedFiles.append(qVariantFromValue<VcsStatusInfo>(status));
    }

    return cachedFiles;
}

/* 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";
    DVcsJob* job = gitRevList(repo, args);
    if (job)
        job->exec();
    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);
    DVcsJob* job = gitRevList(repo, QStringList(root));
    if (job)
        job->exec();
    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;
        }
        DVcsJob* job = gitRevList(repo, args);
        if (job)
            job->exec();
        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';
        }
    }
}

879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
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';
        }
    }
    item.setMessage(message.trimmed());
    commits.append(QVariant::fromValue(item));
    job->setResults(commits);
}

921 922
void GitPlugin::parseGitDiffOutput(DVcsJob* job)
{
923 924
    VcsDiff diff;
    diff.setDiff(job->output());
925
    diff.setBaseDiff(KUrl(job->getDirectory().absolutePath()));
926 927
    
    job->setResults(qVariantFromValue(diff));
928 929
}

930 931
QStringList GitPlugin::getLsFiles(const QString &directory, const QStringList &args,
    KDevelop::OutputJob::OutputJobVerbosity verbosity)
932
{
933
    DVcsJob* job = lsFiles(directory, args, verbosity);
934 935 936 937 938 939 940 941 942 943 944
    if (job)
    {
        job->exec();
        if (job->status() == KDevelop::VcsJob::JobSucceeded)
            return job->output().split('\n', QString::SkipEmptyParts);
        else
            return QStringList();
    }
    return QStringList();
}

945 946
DVcsJob* GitPlugin::gitRevParse(const QString &repository, const QStringList &args,
    KDevelop::OutputJob::OutputJobVerbosity verbosity)
947 948
{
    //Use prepareJob() here only if you like "dead" recursion and KDevelop crashes
949
    DVcsJob* job = new DVcsJob(this, verbosity);
950 951 952 953 954 955 956 957 958 959 960
    QString workDir = repository;
    QFileInfo fsObject(workDir);
    if (fsObject.isFile())
        workDir = fsObject.path();

    job->clear();
    job->setDirectory(workDir);
    *job << "git";
    *job << "rev-parse";
    foreach(const QString &arg, args)
        *job << arg;
961

962
    return job;
963 964 965 966 967 968 969 970 971 972 973 974
}

DVcsJob* GitPlugin::gitRevList(const QString &repository, const QStringList &args)
{
    DVcsJob* job = new DVcsJob(this);
    if (prepareJob(job, repository) ) {
        *job << "git";
        *job << "rev-list";
        foreach(const QString &arg, args)
            *job << arg;
        return job;
    }
975 976
    
    delete job;
977
    return errorsFound(i18n("Could not get the rev list"), OutputJob::Verbose);
978 979
}

980
KDevelop::VcsStatusInfo::State GitPlugin::charToState(char ch)
981 982 983 984 985 986 987 988 989
{
    switch (ch)
    {
        case 'M':
            return VcsStatusInfo::ItemModified;
        case 'A':
            return VcsStatusInfo::ItemAdded;
        case 'D':
            return VcsStatusInfo::ItemDeleted;
990
        default://TODO: hasConflicts
991 992 993 994 995
            return VcsStatusInfo::ItemUnknown;
    }
    return VcsStatusInfo::ItemUnknown;
}

996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
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)
{
    DVcsJob* job = new DVcsJob(this);
    if (prepareJob(job, source.toLocalFile())) {
        *job << "git" << "mv" << source.toLocalFile() << destination.toLocalFile();
        return job;
    }
    
    delete job;
    return 0;
}

1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
void GitPlugin::parseGitRepoLocationOutput(DVcsJob* job)
{
    job->setResults(qVariantFromValue(KUrl(job->output())));
}

VcsJob* GitPlugin::repositoryLocation(const KUrl& localLocation)
{
    DVcsJob* job = new DVcsJob(this);
    if (prepareJob(job, localLocation.toLocalFile())) {
        //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(DVcsJob*)), SLOT(parseGitRepoLocationOutput(DVcsJob*)));
        return job;
    }
    
    delete job;
1051
    return errorsFound(i18n("Could not get the repository location"), OutputJob::Verbose);
1052 1053
}

1054 1055
VcsJob* GitPlugin::pull(const KDevelop::VcsLocation& localOrRepoLocationSrc, const KUrl& localRepositoryLocation)
{
1056
    return empty_cmd();
1057 1058 1059 1060
}

VcsJob* GitPlugin::push(const KUrl& localRepositoryLocation, const KDevelop::VcsLocation& localOrRepoLocationDst)
{
1061
    return empty_cmd();
1062 1063 1064 1065
}

VcsJob* GitPlugin::resolve(const KUrl::List& localLocations, IBasicVersionControl::RecursionMode recursion)
{
1066
    return empty_cmd();
1067 1068 1069 1070
}

VcsJob* GitPlugin::update(const KUrl::List& localLocations, const KDevelop::VcsRevision& rev, IBasicVersionControl::RecursionMode recursion)
{
1071
    return empty_cmd();
1072 1073
}

1074 1075 1076 1077
KDevelop::VcsLocationWidget* GitPlugin::vcsLocation(QWidget* parent) const
{
    return new KDevelop::StandardVcsLocationWidget(parent);
}