File: fileviewgitplugin.cpp

package info (click to toggle)
dolphin-plugins 4%3A16.08.3-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 792 kB
  • ctags: 870
  • sloc: cpp: 8,133; sh: 7; makefile: 3
file content (677 lines) | stat: -rw-r--r-- 26,832 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
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
571
572
573
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
/******************************************************************************
 *   Copyright (C) 2010 by Peter Penz <peter.penz@gmx.at>                     *
 *   Copyright (C) 2010 by Sebastian Doerner <sebastian@sebastian-doerner.de> *
 *   Copyright (C) 2010 by Johannes Steffen <jsteffen@st.ovgu.de>             *
 *                                                                            *
 *   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) any later version.                                      *
 *                                                                            *
 *   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, write to the                            *
 *   Free Software Foundation, Inc.,                                          *
 *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA               *
 ******************************************************************************/

#include "fileviewgitplugin.h"
#include "checkoutdialog.h"
#include "commitdialog.h"
#include "tagdialog.h"
#include "pushdialog.h"
#include "gitwrapper.h"
#include "pulldialog.h"

#include <KLocalizedString>
#include <KUrl>
#include <KRun>
#include <KShell>
#include <KPluginFactory>

#include <QTemporaryFile>
#include <QProcess>
#include <QString>
#include <QStringList>
#include <QTextCodec>
#include <QDir>

K_PLUGIN_FACTORY(FileViewGitPluginFactory, registerPlugin<FileViewGitPlugin>();)

FileViewGitPlugin::FileViewGitPlugin(QObject* parent, const QList<QVariant>& args) :
    KVersionControlPlugin(parent),
    m_pendingOperation(false),
    m_addAction(0),
    m_removeAction(0),
    m_checkoutAction(0),
    m_commitAction(0),
    m_tagAction(0),
    m_pushAction(0),
    m_pullAction(0)
{
    Q_UNUSED(args);

    m_revertAction = new QAction(this);
    m_revertAction->setIcon(QIcon::fromTheme("document-revert"));
    m_revertAction->setText(xi18nd("@action:inmenu", "<application>Git</application> Revert"));
    connect(m_revertAction, SIGNAL(triggered()),
            this, SLOT(revertFiles()));

    m_addAction = new QAction(this);
    m_addAction->setIcon(QIcon::fromTheme("list-add"));
    m_addAction->setText(xi18nd("@action:inmenu", "<application>Git</application> Add"));
    connect(m_addAction, SIGNAL(triggered()),
            this, SLOT(addFiles()));

    m_showLocalChangesAction = new QAction(this);
    m_showLocalChangesAction->setIcon(QIcon::fromTheme("view-split-left-right"));
    m_showLocalChangesAction->setText(xi18nd("@item:inmenu", "Show Local <application>Git</application> Changes"));
    connect(m_showLocalChangesAction, SIGNAL(triggered()),
            this, SLOT(showLocalChanges()));

    m_removeAction = new QAction(this);
    m_removeAction->setIcon(QIcon::fromTheme("list-remove"));
    m_removeAction->setText(xi18nd("@action:inmenu", "<application>Git</application> Remove"));
    connect(m_removeAction, SIGNAL(triggered()),
            this, SLOT(removeFiles()));

    m_checkoutAction = new QAction(this);
//     m_checkoutAction->setIcon(QIcon::fromTheme("svn_switch")); does not exist in normal kde SC
    m_checkoutAction->setText(xi18nd("@action:inmenu", "<application>Git</application> Checkout..."));
    connect(m_checkoutAction, SIGNAL(triggered()),
            this, SLOT(checkout()));

    m_commitAction = new QAction(this);
    m_commitAction->setIcon(QIcon::fromTheme("svn-commit"));
    m_commitAction->setText(xi18nd("@action:inmenu", "<application>Git</application> Commit..."));
    connect(m_commitAction, SIGNAL(triggered()),
            this, SLOT(commit()));

    m_tagAction = new QAction(this);
//     m_tagAction->setIcon(QIcon::fromTheme("svn-commit"));
    m_tagAction->setText(xi18nd("@action:inmenu", "<application>Git</application> Create Tag..."));
    connect(m_tagAction, SIGNAL(triggered()),
            this, SLOT(createTag()));
    m_pushAction = new QAction(this);
//     m_pushAction->setIcon(QIcon::fromTheme("svn-commit"));
    m_pushAction->setText(xi18nd("@action:inmenu", "<application>Git</application> Push..."));
    connect(m_pushAction, SIGNAL(triggered()),
            this, SLOT(push()));
    m_pullAction = new QAction(this);
    m_pullAction->setText(xi18nd("@action:inmenu", "<application>Git</application> Pull..."));
    connect(m_pullAction, SIGNAL(triggered()),
            this, SLOT(pull()));

    connect(&m_process, SIGNAL(finished(int, QProcess::ExitStatus)),
            this, SLOT(slotOperationCompleted(int, QProcess::ExitStatus)));
    connect(&m_process, SIGNAL(error(QProcess::ProcessError)),
            this, SLOT(slotOperationError()));
}

FileViewGitPlugin::~FileViewGitPlugin()
{
    GitWrapper::freeInstance();
}

QString FileViewGitPlugin::fileName() const
{
    return QLatin1String(".git");
}

int FileViewGitPlugin::readUntilZeroChar(QIODevice* device, char* buffer, const int maxChars) {
    if (buffer == 0) { // discard until next \0
        char c;
        while (device->getChar(&c) && c != '\0')
            ;
        return 0;
    }
    int index = -1;
    while (++index < maxChars) {
        if (!device->getChar(&buffer[index])) {
            buffer[index] = '\0';
            return index == 0 ? 0 : index + 1;
        }
        if (buffer[index] == '\0') {  // line end or we put it there (see above)
            return index + 1;
        }
    }
    return maxChars;
}

bool FileViewGitPlugin::beginRetrieval(const QString& directory)
{
    Q_ASSERT(directory.endsWith('/'));

    GitWrapper::instance()->setWorkingDirectory(directory);
    m_currentDir = directory;

    // ----- find path below git base dir -----
    QProcess process;
    process.setWorkingDirectory(directory);
    process.start(QLatin1String("git rev-parse --show-prefix"));
    QString dirBelowBaseDir = "";
    while (process.waitForReadyRead()) {
        char buffer[512];
        while (process.readLine(buffer, sizeof(buffer)) > 0)  {
            dirBelowBaseDir = QString(buffer).trimmed(); // ends in "/" or is empty
        }
    }

    m_versionInfoHash.clear();

    // ----- find files with special status -----
    process.start(QLatin1String("git status --porcelain -z -u --ignored"));
    while (process.waitForReadyRead()) {
        char buffer[1024];
        while (readUntilZeroChar(&process, buffer, sizeof(buffer)) > 0 ) {
            QString line = QTextCodec::codecForLocale()->toUnicode(buffer);
            // ----- recognize file status -----
            char X = line[0].toAscii();  // X and Y from the table in `man git-status`
            char Y = line[1].toAscii();
            const QString fileName= line.mid(3);
            ItemVersion state = NormalVersion;
            switch (X) {
                case '!':
                    state = IgnoredVersion;
                    break;
                case '?':
                    state = UnversionedVersion;
                    break;
                case 'C': // handle copied as added version
                case 'A':
                    state = AddedVersion;
                    break;
                case 'D':
                    state = RemovedVersion;
                    break;
                case 'M':
                    state = LocallyModifiedVersion;
                    break;
                case 'R':
                    state = LocallyModifiedVersion;
                    // Renames list the old file name directly afterwards, separated by \0.
                    readUntilZeroChar(&process, 0, 0); // discard old file name
                    break;
            }
            // overwrite status depending on the working tree
            switch (Y) {
                case 'D': // handle "deleted in working tree" as "modified in working tree"
                case 'M':
                    state = LocallyModifiedUnstagedVersion;
                    break;
            }
            // overwrite status in case of conflicts (lower part of the table in `man git-status`)
            if (X == 'U' ||
                Y == 'U' ||
                (X == 'A' && Y == 'A') ||
                (X == 'D' && Y == 'D')) {
                state = ConflictingVersion;
            }

            // ----- decide what to record about that file -----
            if (state == NormalVersion || !fileName.startsWith(dirBelowBaseDir)) {
                continue;
            }
            /// File name relative to the current working directory.
            const QString relativeFileName = fileName.mid(dirBelowBaseDir.length());
            //if file is part of a sub-directory, record the directory
            if (relativeFileName.contains('/')) {
                if (state == IgnoredVersion)
                    continue;
                if (state == AddedVersion || state == RemovedVersion) {
                    state = LocallyModifiedVersion;
                }
                const QString absoluteDirName = directory + relativeFileName.left(relativeFileName.indexOf('/'));
                if (m_versionInfoHash.contains(absoluteDirName)) {
                    ItemVersion oldState = m_versionInfoHash.value(absoluteDirName);
                    //only keep the most important state for a directory
                    if (oldState == ConflictingVersion)
                        continue;
                    if (oldState == LocallyModifiedUnstagedVersion && state != ConflictingVersion)
                        continue;
                    if (oldState == LocallyModifiedVersion &&
                        state != LocallyModifiedUnstagedVersion && state != ConflictingVersion)
                        continue;
                    m_versionInfoHash.insert(absoluteDirName, state);
                } else {
                    m_versionInfoHash.insert(absoluteDirName, state);
                }
            } else { //normal file, no directory
                    m_versionInfoHash.insert(directory + relativeFileName, state);
            }
        }
    }
    return true;
}

void FileViewGitPlugin::endRetrieval()
{
}

KVersionControlPlugin::ItemVersion FileViewGitPlugin::itemVersion(const KFileItem& item) const
{
    const QString itemUrl = item.localPath();
    if (m_versionInfoHash.contains(itemUrl)) {
        return m_versionInfoHash.value(itemUrl);
    } else {
        // files that are not in our map are normal, tracked files by definition
        return NormalVersion;
    }
}

QList<QAction*> FileViewGitPlugin::actions(const KFileItemList &items) const
{
    if (items.count() == 1 && items.first().isDir()) {
        QString directory = items.first().localPath();
        if (!directory.endsWith(QLatin1Char('/'))) {
            directory += QLatin1Char('/');
        }

        if (directory == m_currentDir) {
            return contextMenuDirectoryActions(directory);
        } else {
            return contextMenuFilesActions(items);
        }
    } else {
        return contextMenuFilesActions(items);
    }
}

QList<QAction*> FileViewGitPlugin::contextMenuFilesActions(const KFileItemList& items) const
{
    Q_ASSERT(!items.isEmpty());

    if (!m_pendingOperation){
        m_contextDir = QFileInfo(items.first().localPath()).canonicalPath();
        m_contextItems.clear();
        foreach(const KFileItem& item, items){
            m_contextItems.append(item);
        }

        //see which actions should be enabled
        int versionedCount = 0;
        int addableCount = 0;
        int revertCount = 0;
        foreach(const KFileItem& item, items){
            const ItemVersion state = itemVersion(item);
            if (state != UnversionedVersion && state != RemovedVersion &&
                state != IgnoredVersion) {
                ++versionedCount;
            }
            if (state == UnversionedVersion || state == LocallyModifiedUnstagedVersion ||
                state == IgnoredVersion) {
                ++addableCount;
            }
            if (state == LocallyModifiedVersion || state == LocallyModifiedUnstagedVersion ||
                state == ConflictingVersion) {
                ++revertCount;
            }
        }

        m_addAction->setEnabled(addableCount == items.count());
        m_revertAction->setEnabled(revertCount == items.count());
        m_removeAction->setEnabled(versionedCount == items.count());
    }
    else{
        m_addAction->setEnabled(false);
        m_revertAction->setEnabled(false);
        m_removeAction->setEnabled(false);
    }

    QList<QAction*> actions;
    actions.append(m_addAction);
    actions.append(m_removeAction);
    actions.append(m_revertAction);
    return actions;
}

QList<QAction*> FileViewGitPlugin::contextMenuDirectoryActions(const QString& directory) const
{
    QList<QAction*> actions;
    if (!m_pendingOperation){
        m_contextDir = directory;
    }
    m_checkoutAction->setEnabled(!m_pendingOperation);
    actions.append(m_checkoutAction);

    bool canCommit = false;
    bool showChanges = false;
    QHash<QString, ItemVersion>::const_iterator it = m_versionInfoHash.constBegin();
    while (it != m_versionInfoHash.constEnd()) {
        const ItemVersion state = it.value();
        if (state == LocallyModifiedVersion || state == AddedVersion || state == RemovedVersion) {
            canCommit = true;
        }
        if (state == LocallyModifiedUnstagedVersion || state == LocallyModifiedVersion) {
            showChanges = true;
        }
        if (state == ConflictingVersion) {
            canCommit = false;
            showChanges = true;
            break;
        }
        ++it;
    }

    m_showLocalChangesAction->setEnabled(!m_pendingOperation && showChanges);
    actions.append(m_showLocalChangesAction);

    m_commitAction->setEnabled(!m_pendingOperation && canCommit);
    actions.append(m_commitAction);

    m_tagAction->setEnabled(!m_pendingOperation);
    actions.append(m_tagAction);
    m_pushAction->setEnabled(!m_pendingOperation);
    actions.append(m_pushAction);
    m_pullAction->setEnabled(!m_pendingOperation);
    actions.append(m_pullAction);

    return actions;
}

void FileViewGitPlugin::addFiles()
{
    execGitCommand(QLatin1String("add"), QStringList(),
                   xi18nd("@info:status", "Adding files to <application>Git</application> repository..."),
                   xi18nd("@info:status", "Adding files to <application>Git</application> repository failed."),
                   xi18nd("@info:status", "Added files to <application>Git</application> repository."));
}

void FileViewGitPlugin::removeFiles()
{
    QStringList arguments;
    arguments << "-r"; //recurse through directories
    arguments << "--force"; //also remove files that have not been committed yet
    execGitCommand(QLatin1String("rm"), arguments,
                   xi18nd("@info:status", "Removing files from <application>Git</application> repository..."),
                   xi18nd("@info:status", "Removing files from <application>Git</application> repository failed."),
                   xi18nd("@info:status", "Removed files from <application>Git</application> repository."));
}

void FileViewGitPlugin::revertFiles()
{
    execGitCommand(QLatin1String("checkout"), { "--" },
                   xi18nd("@info:status", "Reverting files from <application>Git</application> repository..."),
                   xi18nd("@info:status", "Reverting files from <application>Git</application> repository failed."),
                   xi18nd("@info:status", "Reverted files from <application>Git</application> repository."));
}

void FileViewGitPlugin::showLocalChanges()
{
    Q_ASSERT(!m_contextDir.isEmpty());

    KRun::runCommand(QLatin1String("git difftool --dir-diff ."), nullptr, m_contextDir);
}

void FileViewGitPlugin::checkout()
{
    CheckoutDialog dialog;
    if (dialog.exec() == QDialog::Accepted){
        QProcess process;
        process.setWorkingDirectory(m_contextDir);
        QStringList arguments;
        arguments << "checkout";
        if (dialog.force()) {
            arguments << "-f";
        }
        const QString newBranchName = dialog.newBranchName();
        if (!newBranchName.isEmpty()) {
            arguments << "-b";
            arguments << newBranchName;
        }
        const QString checkoutIdentifier = dialog.checkoutIdentifier();
        if (!checkoutIdentifier.isEmpty()) {
            arguments << checkoutIdentifier;
        }
        //to appear in messages
        const QString currentBranchName = newBranchName.isEmpty() ? checkoutIdentifier : newBranchName;
        process.start(QLatin1String("git"), arguments);
        process.setReadChannel(QProcess::StandardError); //git writes info messages to stderr as well
        QString completedMessage;
        while (process.waitForReadyRead()) {
            char buffer[512];
            while (process.readLine(buffer, sizeof(buffer)) > 0){
                const QString currentLine(buffer);
                if (currentLine.startsWith(QLatin1String("Switched to branch"))) {
                    completedMessage = xi18nd("@info:status", "Switched to branch '%1'", currentBranchName);
                }
                if (currentLine.startsWith(QLatin1String("HEAD is now at"))) {
                    const QString headIdentifier = currentLine.
                        mid(QString("HEAD is now at ").length()).trimmed();
                    completedMessage = xi18nd("@info:status Git HEAD pointer, parameter includes "
                    "short SHA-1 & commit message ", "HEAD is now at %1", headIdentifier);
                }
                //special output for checkout -b
                if (currentLine.startsWith(QLatin1String("Switched to a new branch"))) {
                    completedMessage = xi18nd("@info:status", "Switched to a new branch '%1'", currentBranchName);
                }
            }
        }
        if (process.exitCode() == 0 && process.exitStatus() == QProcess::NormalExit) {
            if (!completedMessage.isEmpty()) {
                emit operationCompletedMessage(completedMessage);
                emit itemVersionsChanged();
            }
        }
        else {
            emit errorMessage(xi18nd("@info:status", "<application>Git</application> Checkout failed."
            " Maybe your working directory is dirty."));
        }
    }
}

void FileViewGitPlugin::commit()
{
    CommitDialog dialog;
    if (dialog.exec() == QDialog::Accepted) {
        QTemporaryFile tmpCommitMessageFile;
        tmpCommitMessageFile.open();
        tmpCommitMessageFile.write(dialog.commitMessage());
        tmpCommitMessageFile.close();
        QProcess process;
        process.setWorkingDirectory(m_contextDir);
        process.start(QString("git commit") + (dialog.amend() ? " --amend" : "")+ " -F " + tmpCommitMessageFile.fileName());
        QString completedMessage;
        while (process.waitForReadyRead()){
            char buffer[512];
            while (process.readLine(buffer, sizeof(buffer)) > 0) {
                if (strlen(buffer) > 0 && buffer[0] == '[') {
                    completedMessage = QTextCodec::codecForLocale()->toUnicode(buffer).trimmed();
                    break;
                }
            }
        }
        if (!completedMessage.isEmpty()) {
            emit operationCompletedMessage(completedMessage);
            emit itemVersionsChanged();
        }
    }
}

void FileViewGitPlugin::createTag()
{
   TagDialog dialog;
    if (dialog.exec() == QDialog::Accepted) {
        QTemporaryFile tempTagMessageFile;
        tempTagMessageFile.open();
        tempTagMessageFile.write(dialog.tagMessage());
        tempTagMessageFile.close();
        QProcess process;
        process.setWorkingDirectory(m_contextDir);
        process.setReadChannel(QProcess::StandardError);
        process.start(QString("git tag -a -F %1 %2 %3").arg(tempTagMessageFile.fileName()).
            arg(dialog.tagName()).arg(dialog.baseBranch()));
        QString completedMessage;
        bool gotTagAlreadyExistsMessage = false;
        while (process.waitForReadyRead()) {
            char buffer[512];
            while (process.readLine(buffer, sizeof(buffer)) > 0) {
                QString line(buffer);
                if (line.contains("already exists")) {
                    gotTagAlreadyExistsMessage = true;
                }
            }
        }
        if (process.exitCode() == 0 && process.exitStatus() == QProcess::NormalExit) {
            completedMessage = xi18nd("@info:status","Successfully created tag '%1'", dialog.tagName());
            emit operationCompletedMessage(completedMessage);
        } else {
            //I don't know any other error, but in case one occurs, the user doesn't get FALSE error messages
            emit errorMessage(gotTagAlreadyExistsMessage ?
                xi18nd("@info:status", "<application>Git</application> tag creation failed."
                                      " A tag with the name '%1' already exists.", dialog.tagName()) :
                xi18nd("@info:status", "<application>Git</application> tag creation failed.")
            );
        }
    }
}

void FileViewGitPlugin::push()
{
    PushDialog dialog;
    if (dialog.exec() == QDialog::Accepted) {
        m_process.setWorkingDirectory(m_contextDir);

        m_errorMsg = xi18nd("@info:status", "Pushing branch %1 to %2:%3 failed.",
                        dialog.localBranch(), dialog.destination(), dialog.remoteBranch());
        m_operationCompletedMsg = xi18nd("@info:status", "Pushed branch %1 to %2:%3.",
                        dialog.localBranch(), dialog.destination(), dialog.remoteBranch());
        emit infoMessage(xi18nd("@info:status", "Pushing branch %1 to %2:%3...",
                 dialog.localBranch(), dialog.destination(), dialog.remoteBranch()));

        m_command = "push";
        m_pendingOperation = true;
        m_process.start(QString("git push%4 %1 %2:%3").arg(dialog.destination()).
            arg(dialog.localBranch()).arg(dialog.remoteBranch()).
            arg(dialog.force() ? QLatin1String(" --force") : QLatin1String("")));
    }
}

void FileViewGitPlugin::pull()
{
    PullDialog dialog;
    if (dialog.exec()  == QDialog::Accepted) {
        m_process.setWorkingDirectory(m_contextDir);

        m_errorMsg = xi18nd("@info:status", "Pulling branch %1 from %2 failed.",
                        dialog.remoteBranch(), dialog.source());
        m_operationCompletedMsg = xi18nd("@info:status", "Pulled branch %1 from %2 successfully.",
                        dialog.remoteBranch(), dialog.source());
        emit infoMessage(xi18nd("@info:status", "Pulling branch %1 from %2...", dialog.remoteBranch(),
                    dialog.source()));

        m_command = "pull";
        m_pendingOperation = true;
        m_process.start(QString("git pull %1 %2").arg(dialog.source()).arg(dialog.remoteBranch()));
    }
}

void FileViewGitPlugin::slotOperationCompleted(int exitCode, QProcess::ExitStatus exitStatus)
{
    m_pendingOperation = false;

    QString message;
    if (m_command == QLatin1String("push")) { //output parsing for push
        message = parsePushOutput();
        m_command = "";
    }
    if (m_command == QLatin1String("pull")) {
        message = parsePullOutput();
        m_command = "";
    }

    if ((exitStatus != QProcess::NormalExit) || (exitCode != 0)) {
        emit errorMessage(message.isNull() ? m_errorMsg : message);
    } else if (m_contextItems.isEmpty()) {
        emit operationCompletedMessage(message.isNull() ? m_operationCompletedMsg : message);
        emit itemVersionsChanged();
    } else {
        startGitCommandProcess();
    }
}

void FileViewGitPlugin::slotOperationError()
{
    // don't do any operation on other items anymore
    m_contextItems.clear();
    m_pendingOperation = false;

    emit errorMessage(m_errorMsg);
}

QString FileViewGitPlugin::parsePushOutput()
{
    m_process.setReadChannel(QProcess::StandardError);
    QString message;
    char buffer[256];
    while (m_process.readLine(buffer, sizeof(buffer)) > 0) {
        const QString line(buffer);
        if (line.contains("->") || (line.contains("fatal") && message.isNull())) {
            message = line.trimmed();
        }
        if (line.contains("Everything up-to-date") && message.isNull()) {
            message = xi18nd("@info:status", "Branch is already up-to-date.");
        }
    }
    return message;
}

QString FileViewGitPlugin::parsePullOutput()
{
    char buffer[256];
    while (m_process.readLine(buffer, sizeof(buffer)) > 0) {
        const QString line(buffer);
        if (line.contains("Already up-to-date")) {
            return xi18nd("@info:status", "Branch is already up-to-date.");
        }
        if (line.contains("CONFLICT")) {
            emit itemVersionsChanged();
            return xi18nd("@info:status", "Merge conflicts occurred. Fix them and commit the result.");
        }
    }
    return QString();
}

void FileViewGitPlugin::execGitCommand(const QString& gitCommand,
                                       const QStringList& arguments,
                                       const QString& infoMsg,
                                       const QString& errorMsg,
                                       const QString& operationCompletedMsg)
{
    emit infoMessage(infoMsg);

    m_command = gitCommand;
    m_arguments = arguments;
    m_errorMsg = errorMsg;
    m_operationCompletedMsg = operationCompletedMsg;

    startGitCommandProcess();
}


void FileViewGitPlugin::startGitCommandProcess()
{
    Q_ASSERT(!m_contextItems.isEmpty());
    Q_ASSERT(m_process.state() == QProcess::NotRunning);
    m_pendingOperation = true;

    const KFileItem item = m_contextItems.takeLast();
    m_process.setWorkingDirectory(m_contextDir);
    QStringList arguments;
    arguments << m_command;
    arguments << m_arguments;
    //force explicitly selected files but no files in selected directories
    if (m_command == "add" && !item.isDir()){
        arguments<< QLatin1String("-f");
    }
    arguments << item.url().fileName();
    m_process.start(QLatin1String("git"), arguments);
    // the remaining items of m_contextItems will be executed
    // after the process has finished (see slotOperationFinished())
}

#include "fileviewgitplugin.moc"