gitplugin.cpp 53.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
 *                                                                         *
 *   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"

25
#include <QDateTime>
Dāvis Mosāns's avatar
Dāvis Mosāns committed
26
#include <QDebug>
27 28 29 30
#include <QDir>
#include <QFileInfo>
#include <QMenu>
#include <QTimer>
31

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

Milian Wolff's avatar
Milian Wolff committed
36 37
#include <util/path.h>

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 "gitclonejob.h"
45 46 47
#include <interfaces/contextmenuextension.h>
#include <interfaces/iruncontroller.h>
#include "stashmanagerdialog.h"
48 49 50 51

#include <KDirWatch>
#include <KIO/CopyJob>
#include <KLocalizedString>
52
#include <KMessageBox>
53
#include <KTextEdit>
54
#include <KTextEditor/Document>
55

56
#include "gitjob.h"
57
#include "gitmessagehighlighter.h"
58
#include "gitplugincheckinrepositoryjob.h"
59
#include "gitnameemaildialog.h"
Dāvis Mosāns's avatar
Dāvis Mosāns committed
60 61 62
#include "debug.h"

Q_LOGGING_CATEGORY(PLUGIN_GIT, "kdevplatform.plugins.git")
63

64 65
using namespace KDevelop;

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

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

QDir dotGitDirectory(const QUrl& dirPath)
80
{
81
    const QFileInfo finfo(dirPath.toLocalFile());
82
    QDir dir = finfo.isDir() ? QDir(finfo.filePath()): finfo.absoluteDir();
Dāvis Mosāns's avatar
Dāvis Mosāns committed
83

84
    static const QString gitDir = QStringLiteral(".git");
85
    while (!dir.exists(gitDir) && dir.cdUp()) {} // cdUp, until there is a sub-directory called .git
86

87
    if (dir.isRoot()) {
Kevin Funk's avatar
Kevin Funk committed
88
        qCWarning(PLUGIN_GIT) << "couldn't find the git root for" << dirPath;
89 90
    }

91 92 93
    return dir;
}

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

115 116 117 118 119 120
QString toRevisionName(const KDevelop::VcsRevision& rev, QString currentRevision=QString())
{
    switch(rev.revisionType()) {
        case VcsRevision::Special:
            switch(rev.revisionValue().value<VcsRevision::RevisionSpecialType>()) {
                case VcsRevision::Head:
121
                    return QStringLiteral("^HEAD");
122
                case VcsRevision::Base:
123
                    return QString();
124
                case VcsRevision::Working:
125
                    return QString();
126 127 128 129
                case VcsRevision::Previous:
                    Q_ASSERT(!currentRevision.isEmpty());
                    return currentRevision + "^1";
                case VcsRevision::Start:
130
                    return QString();
131
                case VcsRevision::UserSpecialType: //Not used
132 133 134 135 136 137 138 139 140 141 142 143 144 145
                    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();
}

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

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

177 178
}

179
GitPlugin::GitPlugin( QObject *parent, const QVariantList & )
180
    : DistributedVersionControlPlugin(parent, QStringLiteral("kdevgit")), m_oldVersion(false), m_usePrefix(true)
181
{
182
    if (QStandardPaths::findExecutable(QStringLiteral("git")).isEmpty()) {
183
        m_hasError = true;
Laurent Montel's avatar
Laurent Montel committed
184
        m_errorDescription = i18n("git is not installed");
185 186 187
        return;
    }

188 189
    KDEV_USE_EXTENSION_INTERFACE( KDevelop::IBasicVersionControl )
    KDEV_USE_EXTENSION_INTERFACE( KDevelop::IDistributedVersionControl )
190
    KDEV_USE_EXTENSION_INTERFACE( KDevelop::IBranchingVersionControl )
191

192
    m_hasError = false;
193
    setObjectName(QStringLiteral("Git"));
Dāvis Mosāns's avatar
Dāvis Mosāns committed
194

195 196
    DVcsJob* versionJob = new DVcsJob(QDir::tempPath(), this, KDevelop::OutputJob::Silent);
    *versionJob << "git" << "--version";
197
    connect(versionJob, &DVcsJob::readyForParsing, this, &GitPlugin::parseGitVersionOutput);
198
    ICore::self()->runController()->registerJob(versionJob);
Dāvis Mosāns's avatar
Dāvis Mosāns committed
199

200
    m_watcher = new KDirWatch(this);
201 202
    connect(m_watcher, &KDirWatch::dirty, this, &GitPlugin::fileChanged);
    connect(m_watcher, &KDirWatch::created, this, &GitPlugin::fileChanged);
203 204 205
}

GitPlugin::~GitPlugin()
206
{}
207

208 209 210 211 212
bool emptyOutput(DVcsJob* job)
{
    QScopedPointer<DVcsJob> _job(job);
    if(job->exec() && job->status()==VcsJob::JobSucceeded)
        return job->rawOutput().trimmed().isEmpty();
Dāvis Mosāns's avatar
Dāvis Mosāns committed
213

214 215 216 217 218
    return false;
}

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

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

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

Milian Wolff's avatar
Milian Wolff committed
232
void GitPlugin::additionalMenuEntries(QMenu* menu, const QList<QUrl>& urls)
233 234
{
    m_urls = urls;
Dāvis Mosāns's avatar
Dāvis Mosāns committed
235

236
    QDir dir=urlDir(urls);
237
    bool hasSt = hasStashes(dir);
238
    menu->addSeparator()->setText(i18n("Git Stashes"));
239 240 241
    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);
242 243 244 245 246 247 248 249 250 251
}

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

void GitPlugin::ctxPopStash()
{
252
    VcsJob* job = gitStash(urlDir(m_urls), QStringList(QStringLiteral("pop")), KDevelop::OutputJob::Verbose);
253 254 255 256 257 258 259
    ICore::self()->runController()->registerJob(job);
}

void GitPlugin::ctxStashManager()
{
    QPointer<StashManagerDialog> d = new StashManagerDialog(urlDir(m_urls), this, 0);
    d->exec();
Dāvis Mosāns's avatar
Dāvis Mosāns committed
260

261 262 263
    delete d;
}

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

271
QString GitPlugin::name() const
272
{
273
    return QStringLiteral("Git");
274 275
}

Milian Wolff's avatar
Milian Wolff committed
276
QUrl GitPlugin::repositoryRoot(const QUrl& path)
277
{
Milian Wolff's avatar
Milian Wolff committed
278
    return QUrl::fromLocalFile(dotGitDirectory(path).absolutePath());
279 280
}

Milian Wolff's avatar
Milian Wolff committed
281
bool GitPlugin::isValidDirectory(const QUrl & dirPath)
282
{
283
    QDir dir=dotGitDirectory(dirPath);
284

285
    return dir.cd(QStringLiteral(".git")) && dir.exists(QStringLiteral("HEAD"));
286 287
}

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

298 299
    QString filename = fsObject.fileName();

300
    QStringList otherFiles = getLsFiles(fsObject.dir(), QStringList(QStringLiteral("--")) << filename, KDevelop::OutputJob::Silent);
301
    return !otherFiles.empty();
302 303
}

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

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

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

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

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

336
    DVcsJob* job = new GitJob(urlDir(localLocations), this, OutputJob::Silent);
337
    job->setType(VcsJob::Status);
Dāvis Mosāns's avatar
Dāvis Mosāns committed
338

339 340
    if(m_oldVersion) {
        *job << "git" << "ls-files" << "-t" << "-m" << "-c" << "-o" << "-d" << "-k" << "--directory";
341
        connect(job, &DVcsJob::readyForParsing, this, &GitPlugin::parseGitStatusOutput_old);
342 343
    } else {
        *job << "git" << "status" << "--porcelain";
344
        job->setIgnoreError(true);
345
        connect(job, &DVcsJob::readyForParsing, this, &GitPlugin::parseGitStatusOutput);
346 347
    }
    *job << "--" << (recursion == IBasicVersionControl::Recursive ? localLocations : preventRecursion(localLocations));
348

349
    return job;
350 351
}

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

357
    DVcsJob* job = new GitJob(dotGitDirectory(fileOrDirectory), this, KDevelop::OutputJob::Silent);
358
    job->setType(VcsJob::Diff);
359
    *job << "git" << "diff" << "--no-color" << "--no-ext-diff";
360 361 362 363 364
    if (!usePrefix()) {
        // KDE's ReviewBoard now requires p1 patchfiles, so `git diff --no-prefix` to generate p0 patches
        // has become optional.
        *job << "--no-prefix";
    }
365 366 367 368 369 370 371 372 373 374
    if(srcRevision.revisionType()==VcsRevision::Special
        && dstRevision.revisionType()==VcsRevision::Special
        && srcRevision.specialType()==VcsRevision::Base
        && dstRevision.specialType()==VcsRevision::Working)
        *job << "HEAD";
    else {
        QString revstr = revisionInterval(srcRevision, dstRevision);
        if(!revstr.isEmpty())
            *job << revstr;
    }
Milian Wolff's avatar
Milian Wolff committed
375 376 377 378 379 380 381 382

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

383
    connect(job, &DVcsJob::readyForParsing, this, &GitPlugin::parseGitDiffOutput);
384
    return job;
385 386
}

Milian Wolff's avatar
Milian Wolff committed
387
VcsJob* GitPlugin::revert(const QList<QUrl>& localLocations, IBasicVersionControl::RecursionMode recursion)
388
{
389 390
    if(localLocations.isEmpty() )
        return errorsFound(i18n("Could not revert changes"), OutputJob::Verbose);
Dāvis Mosāns's avatar
Dāvis Mosāns committed
391

392 393 394 395
    QDir repo = urlDir(repositoryRoot(localLocations.first()));
    QString modified;
    for (const auto& file: localLocations) {
        if (hasModifications(repo, file)) {
Milian Wolff's avatar
Milian Wolff committed
396
            modified.append(file.toDisplayString(QUrl::PreferLocalFile) + "<br/>");
397 398 399 400 401 402 403 404 405 406
        }
    }
    if (!modified.isEmpty()) {
        auto res = KMessageBox::questionYesNo(nullptr, i18n("The following files have uncommited changes, "
                                              "which will be lost. Continue?") + "<br/><br/>" + modified);
        if (res != KMessageBox::Yes) {
            return errorsFound(QString(), OutputJob::Silent);
        }
    }

407
    DVcsJob* job = new GitJob(dotGitDirectory(localLocations.front()), this);
408
    job->setType(VcsJob::Revert);
409 410
    *job << "git" << "checkout" << "--";
    *job << (recursion == IBasicVersionControl::Recursive ? localLocations : preventRecursion(localLocations));
Dāvis Mosāns's avatar
Dāvis Mosāns committed
411

412
    return job;
413 414 415
}


416 417 418
//TODO: git doesn't like empty messages, but "KDevelop didn't provide any message, it may be a bug" looks ugly...
//If no files specified then commit already added files
VcsJob* GitPlugin::commit(const QString& message,
Milian Wolff's avatar
Milian Wolff committed
419
                             const QList<QUrl>& localLocations,
420 421
                             KDevelop::IBasicVersionControl::RecursionMode recursion)
{
422
    if (localLocations.empty() || message.isEmpty())
423
        return errorsFound(i18n("No files or message specified"));
424 425 426 427

    const QDir dir = dotGitDirectory(localLocations.front());
    if (!ensureValidGitIdentity(dir)) {
        return errorsFound(i18n("Email or name for Git not specified"));
428
    }
429

430
    DVcsJob* job = new DVcsJob(dir, this);
431
    job->setType(VcsJob::Commit);
Milian Wolff's avatar
Milian Wolff committed
432
    QList<QUrl> files = (recursion == IBasicVersionControl::Recursive ? localLocations : preventRecursion(localLocations));
433
    addNotVersionedFiles(dir, files);
Dāvis Mosāns's avatar
Dāvis Mosāns committed
434

435
    *job << "git" << "commit" << "-m" << message;
436
    *job << "--" << files;
437
    return job;
438
}
439

440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
bool GitPlugin::ensureValidGitIdentity(const QDir& dir)
{
    const QUrl url = QUrl::fromLocalFile(dir.absolutePath());

    const QString name = readConfigOption(url, QStringLiteral("user.name"));
    const QString email = readConfigOption(url, QStringLiteral("user.email"));
    if (!email.isEmpty() && !name.isEmpty()) {
        return true; // already okay
    }

    GitNameEmailDialog dialog;
    dialog.setName(name);
    dialog.setEmail(email);
    if (!dialog.exec()) {
        return false;
    }

    runSynchronously(setConfigOption(url, QStringLiteral("user.name"), dialog.name(), dialog.isGlobal()));
    runSynchronously(setConfigOption(url, QStringLiteral("user.email"), dialog.email(), dialog.isGlobal()));
    return true;
}

Milian Wolff's avatar
Milian Wolff committed
462
void GitPlugin::addNotVersionedFiles(const QDir& dir, const QList<QUrl>& files)
463
{
464
    QStringList otherStr = getLsFiles(dir, QStringList() << QStringLiteral("--others"), KDevelop::OutputJob::Silent);
Milian Wolff's avatar
Milian Wolff committed
465
    QList<QUrl> toadd, otherFiles;
Dāvis Mosāns's avatar
Dāvis Mosāns committed
466

467
    foreach(const QString& file, otherStr) {
Milian Wolff's avatar
Milian Wolff committed
468
        QUrl v = QUrl::fromLocalFile(dir.absoluteFilePath(file));
Dāvis Mosāns's avatar
Dāvis Mosāns committed
469

470 471
        otherFiles += v;
    }
Dāvis Mosāns's avatar
Dāvis Mosāns committed
472

473
    //We add the files that are not versioned
Milian Wolff's avatar
Milian Wolff committed
474
    foreach(const QUrl& file, files) {
475 476 477
        if(otherFiles.contains(file) && QFileInfo(file.toLocalFile()).isFile())
            toadd += file;
    }
Dāvis Mosāns's avatar
Dāvis Mosāns committed
478

479 480 481 482
    if(!toadd.isEmpty()) {
        VcsJob* job = add(toadd);
        job->exec();
    }
483 484
}

485 486
bool isEmptyDirStructure(const QDir &dir)
{
487
    foreach (const QFileInfo &i, dir.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot)) {
488 489 490 491 492 493 494 495 496
        if (i.isDir()) {
            if (!isEmptyDirStructure(QDir(i.filePath()))) return false;
        } else if (i.isFile()) {
            return false;
        }
    }
    return true;
}

Milian Wolff's avatar
Milian Wolff committed
497
VcsJob* GitPlugin::remove(const QList<QUrl>& files)
498
{
499 500
    if (files.isEmpty())
        return errorsFound(i18n("No files to remove"));
501 502 503
    QDir dotGitDir = dotGitDirectory(files.front());


Milian Wolff's avatar
Milian Wolff committed
504
    QList<QUrl> files_(files);
505

Milian Wolff's avatar
Milian Wolff committed
506
    QMutableListIterator<QUrl> i(files_);
507
    while (i.hasNext()) {
Milian Wolff's avatar
Milian Wolff committed
508
        QUrl file = i.next();
509
        QFileInfo fileInfo(file.toLocalFile());
510

511
        QStringList otherStr = getLsFiles(dotGitDir, QStringList() << QStringLiteral("--others") << QStringLiteral("--") << file.toLocalFile(), KDevelop::OutputJob::Silent);
512 513
        if(!otherStr.isEmpty()) {
            //remove files not under version control
Milian Wolff's avatar
Milian Wolff committed
514
            QList<QUrl> otherFiles;
515
            foreach(const QString &f, otherStr) {
Milian Wolff's avatar
Milian Wolff committed
516
                otherFiles << QUrl::fromLocalFile(dotGitDir.path()+'/'+f);
517 518 519 520 521
            }
            if (fileInfo.isFile()) {
                //if it's an unversioned file we are done, don't use git rm on it
                i.remove();
            }
522 523 524

            auto trashJob = KIO::trash(otherFiles);
            trashJob->exec();
Dāvis Mosāns's avatar
Dāvis Mosāns committed
525
            qCDebug(PLUGIN_GIT) << "other files" << otherFiles;
526 527
        }

528
        if (fileInfo.isDir()) {
529 530
            if (isEmptyDirStructure(QDir(file.toLocalFile()))) {
                //remove empty folders, git doesn't do that
531 532
                auto trashJob = KIO::trash(file);
                trashJob->exec();
Dāvis Mosāns's avatar
Dāvis Mosāns committed
533
                qCDebug(PLUGIN_GIT) << "empty folder, removing" << file;
534
                //we already deleted it, don't use git rm on it
535 536 537 538 539 540
                i.remove();
            }
        }
    }

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

542 543
    DVcsJob* job = new GitJob(dotGitDir, this);
    job->setType(VcsJob::Remove);
Kevin Funk's avatar
Kevin Funk committed
544 545 546
    // git refuses to delete files with local modifications
    // use --force to overcome this
    *job << "git" << "rm" << "-r" << "--force";
547 548
    *job << "--" << files_;
    return job;
549 550
}

Milian Wolff's avatar
Milian Wolff committed
551
VcsJob* GitPlugin::log(const QUrl& localLocation,
552
                const KDevelop::VcsRevision& src, const KDevelop::VcsRevision& dst)
553
{
554
    DVcsJob* job = new GitJob(dotGitDirectory(localLocation), this, KDevelop::OutputJob::Silent);
555
    job->setType(VcsJob::Log);
556
    *job << "git" << "log" << "--date=raw" << "--name-status" << "-M80%" << "--follow";
557 558 559
    QString rev = revisionInterval(dst, src);
    if(!rev.isEmpty())
        *job << rev;
560
    *job << "--" << localLocation;
561
    connect(job, &DVcsJob::readyForParsing, this, &GitPlugin::parseGitLogOutput);
562
    return job;
563 564
}

565

Milian Wolff's avatar
Milian Wolff committed
566
VcsJob* GitPlugin::log(const QUrl& localLocation, const KDevelop::VcsRevision& rev, unsigned long int limit)
567
{
568
    DVcsJob* job = new GitJob(dotGitDirectory(localLocation), this, KDevelop::OutputJob::Silent);
569
    job->setType(VcsJob::Log);
570
    *job << "git" << "log" << "--date=raw" << "--name-status" << "-M80%" << "--follow";
571 572 573
    QString revStr = toRevisionName(rev, QString());
    if(!revStr.isEmpty())
        *job << revStr;
574
    if(limit>0)
575
        *job << QStringLiteral("-%1").arg(limit);
Dāvis Mosāns's avatar
Dāvis Mosāns committed
576

577
    *job << "--" << localLocation;
578
    connect(job, &DVcsJob::readyForParsing, this, &GitPlugin::parseGitLogOutput);
579
    return job;
580 581
}

Milian Wolff's avatar
Milian Wolff committed
582
KDevelop::VcsJob* GitPlugin::annotate(const QUrl &localLocation, const KDevelop::VcsRevision&)
583
{
584
    DVcsJob* job = new GitJob(dotGitDirectory(localLocation), this, KDevelop::OutputJob::Silent);
585
    job->setType(VcsJob::Annotate);
586
    *job << "git" << "blame" << "--porcelain" << "-w";
587
    *job << "--" << localLocation;
588
    connect(job, &DVcsJob::readyForParsing, this, &GitPlugin::parseGitBlameOutput);
589
    return job;
590 591
}

592 593
void GitPlugin::parseGitBlameOutput(DVcsJob *job)
{
594
    QVariantList results;
Milian Wolff's avatar
Milian Wolff committed
595
    VcsAnnotationLine* annotation = 0;
596
    QStringList lines = job->output().split('\n');
Dāvis Mosāns's avatar
Dāvis Mosāns committed
597

598 599 600 601 602 603 604 605
    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);
Dāvis Mosāns's avatar
Dāvis Mosāns committed
606

607 608
            continue;
        }
Dāvis Mosāns's avatar
Dāvis Mosāns committed
609

610 611
        if(it->isEmpty())
            continue;
Dāvis Mosāns's avatar
Dāvis Mosāns committed
612

613 614
        QString name = it->left(it->indexOf(' '));
        QString value = it->right(it->size()-name.size()-1);
615

616
        if(name==QLatin1String("author"))
617
            annotation->setAuthor(value);
618 619 620
        else if(name==QLatin1String("author-mail")) {} //TODO: do smth with the e-mail?
        else if(name==QLatin1String("author-tz")) {} //TODO: does it really matter?
        else if(name==QLatin1String("author-time"))
621
            annotation->setDate(QDateTime::fromTime_t(value.toUInt()));
622
        else if(name==QLatin1String("summary"))
623
            annotation->setCommitMessage(value);
624
        else if(name.startsWith(QStringLiteral("committer"))) {} //We will just store the authors
625 626 627
        else if(name==QLatin1String("previous")) {} //We don't need that either
        else if(name==QLatin1String("filename")) { skipNext=true; }
        else if(name==QLatin1String("boundary")) {
628
            definedRevisions.insert(QStringLiteral("boundary"), VcsAnnotationLine());
629 630 631 632
        }
        else
        {
            QStringList values = value.split(' ');
Dāvis Mosāns's avatar
Dāvis Mosāns committed
633

634
            VcsRevision rev;
Milian Wolff's avatar
Milian Wolff committed
635
            rev.setRevisionValue(name.left(8), KDevelop::VcsRevision::GlobalNumber);
Dāvis Mosāns's avatar
Dāvis Mosāns committed
636

637
            skipNext = definedRevisions.contains(name);
Dāvis Mosāns's avatar
Dāvis Mosāns committed
638

639 640
            if(!skipNext)
                definedRevisions.insert(name, VcsAnnotationLine());
Dāvis Mosāns's avatar
Dāvis Mosāns committed
641

642
            annotation = &definedRevisions[name];
643
            annotation->setLineNumber(values[1].toInt() - 1);
644
            annotation->setRevision(rev);
645 646 647 648
        }
    }
    job->setResults(results);
}
649

650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665

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

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

Milian Wolff's avatar
Milian Wolff committed
666
VcsJob* GitPlugin::tag(const QUrl& repository, const QString& commitMessage, const VcsRevision& rev, const QString& tagName)
667 668 669 670 671 672 673 674
{
    DVcsJob* job = new DVcsJob(urlDir(repository), this);
    *job << "git" << "tag" << "-m" << commitMessage << tagName;
    if(rev.revisionValue().isValid())
        *job << rev.revisionValue().toString();
    return job;
}

Milian Wolff's avatar
Milian Wolff committed
675
VcsJob* GitPlugin::switchBranch(const QUrl &repository, const QString &branch)
676
{
677
    QDir d=urlDir(repository);
Dāvis Mosāns's avatar
Dāvis Mosāns committed
678

679
    if(hasModifications(d) && KMessageBox::questionYesNo(0, i18n("There are pending changes, do you want to stash them first?"))==KMessageBox::Yes) {
680
        QScopedPointer<DVcsJob> stash(gitStash(d, QStringList(), KDevelop::OutputJob::Verbose));
681 682
        stash->exec();
    }
Dāvis Mosāns's avatar
Dāvis Mosāns committed
683

684
    DVcsJob* job = new DVcsJob(d, this);
685 686
    *job << "git" << "checkout" << branch;
    return job;
687 688
}

Milian Wolff's avatar
Milian Wolff committed
689
VcsJob* GitPlugin::branch(const QUrl& repository, const KDevelop::VcsRevision& rev, const QString& branchName)
690
{
691
    Q_ASSERT(!branchName.isEmpty());
Dāvis Mosāns's avatar
Dāvis Mosāns committed
692

693 694
    DVcsJob* job = new DVcsJob(urlDir(repository), this);
    *job << "git" << "branch" << "--" << branchName;
Dāvis Mosāns's avatar
Dāvis Mosāns committed
695

696 697
    if(!rev.prettyValue().isEmpty())
        *job << rev.revisionValue().toString();
698
    return job;
699 700
}

Milian Wolff's avatar
Milian Wolff committed
701
VcsJob* GitPlugin::deleteBranch(const QUrl& repository, const QString& branchName)
702
{
703 704
    DVcsJob* job = new DVcsJob(urlDir(repository), this, OutputJob::Silent);
    *job << "git" << "branch" << "-D" << branchName;
705
    connect(job, &DVcsJob::readyForParsing, this, &GitPlugin::parseGitCurrentBranch);
706
    return job;
707 708
}

Milian Wolff's avatar
Milian Wolff committed
709
VcsJob* GitPlugin::renameBranch(const QUrl& repository, const QString& oldBranchName, const QString& newBranchName)
710
{
711 712
    DVcsJob* job = new DVcsJob(urlDir(repository), this, OutputJob::Silent);
    *job << "git" << "branch" << "-m" << newBranchName << oldBranchName;
713
    connect(job, &DVcsJob::readyForParsing, this, &GitPlugin::parseGitCurrentBranch);
714 715 716
    return job;
}

Milian Wolff's avatar
Milian Wolff committed
717
VcsJob* GitPlugin::currentBranch(const QUrl& repository)
718
{
719
    DVcsJob* job = new DVcsJob(urlDir(repository), this, OutputJob::Silent);
720
    job->setIgnoreError(true);
721
    *job << "git" << "symbolic-ref" << "-q" << "--short" << "HEAD";
722
    connect(job, &DVcsJob::readyForParsing, this, &GitPlugin::parseGitCurrentBranch);
723
    return job;
724 725
}

726
void GitPlugin::parseGitCurrentBranch(DVcsJob* job)
727
{
728
    QString out = job->output().trimmed();
729

730
    job->setResults(out);
731 732
}

Milian Wolff's avatar
Milian Wolff committed
733
VcsJob* GitPlugin::branches(const QUrl &repository)
734 735 736
{
    DVcsJob* job=new DVcsJob(urlDir(repository));
    *job << "git" << "branch" << "-a";
737
    connect(job, &DVcsJob::readyForParsing, this, &GitPlugin::parseGitBranchOutput);
738 739 740 741 742 743
    return job;
}

void GitPlugin::parseGitBranchOutput(DVcsJob* job)
{
    QStringList branchListDirty = job->output().split('\n', QString::SkipEmptyParts);
744 745 746 747

    QStringList branchList;
    foreach(QString branch, branchListDirty)
    {
748