subversionplugin.cpp 40.8 KB
Newer Older
1
/**************************************************************************
con's avatar
con committed
2 3 4
**
** This file is part of Qt Creator
**
5
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
con's avatar
con committed
6
**
7
** Contact: Nokia Corporation (qt-info@nokia.com)
con's avatar
con committed
8
**
9
** Commercial Usage
10
**
11 12 13 14
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
15
**
16
** GNU Lesser General Public License Usage
17
**
18 19 20 21 22 23
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24
**
25
** If you are unsure which license is appropriate for your use, please
hjk's avatar
hjk committed
26
** contact the sales department at http://qt.nokia.com/contact.
con's avatar
con committed
27
**
28
**************************************************************************/
hjk's avatar
hjk committed
29

con's avatar
con committed
30 31 32 33 34 35 36 37
#include "subversionplugin.h"

#include "settingspage.h"
#include "subversioneditor.h"

#include "subversionsubmiteditor.h"
#include "subversionconstants.h"
#include "subversioncontrol.h"
38
#include "checkoutwizard.h"
con's avatar
con committed
39 40 41 42

#include <vcsbase/basevcseditorfactory.h>
#include <vcsbase/vcsbaseeditor.h>
#include <vcsbase/basevcssubmiteditorfactory.h>
43
#include <vcsbase/vcsbaseoutputwindow.h>
con's avatar
con committed
44
#include <utils/synchronousprocess.h>
45
#include <utils/parameteraction.h>
con's avatar
con committed
46 47 48 49 50 51 52

#include <coreplugin/icore.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/filemanager.h>
#include <coreplugin/messagemanager.h>
#include <coreplugin/mimedatabase.h>
#include <coreplugin/uniqueidmanager.h>
53
#include <coreplugin/actionmanager/actionmanager.h>
con's avatar
con committed
54
#include <coreplugin/editormanager/editormanager.h>
55
#include <projectexplorer/projectexplorer.h>
56 57
#include <projectexplorer/session.h>
#include <projectexplorer/project.h>
hjk's avatar
hjk committed
58
#include <utils/qtcassert.h>
con's avatar
con committed
59 60

#include <QtCore/QDebug>
61
#include <QtCore/QDir>
con's avatar
con committed
62 63
#include <QtCore/QFileInfo>
#include <QtCore/QTemporaryFile>
64 65
#include <QtCore/QTextCodec>
#include <QtCore/QtPlugin>
con's avatar
con committed
66
#include <QtGui/QAction>
67 68
#include <QtGui/QFileDialog>
#include <QtGui/QMainWindow>
con's avatar
con committed
69 70
#include <QtGui/QMenu>
#include <QtGui/QMessageBox>
71 72 73
#include <QtGui/QInputDialog>

#include <limits.h>
con's avatar
con committed
74 75 76 77 78 79 80 81

using namespace Subversion::Internal;

// Timeout for normal output commands
enum { subversionShortTimeOut = 10000 };
// Timeout for submit, update
enum { subversionLongTimeOut = 120000 };

82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
static const char * const CMD_ID_SUBVERSION_MENU    = "Subversion.Menu";
static const char * const CMD_ID_ADD                = "Subversion.Add";
static const char * const CMD_ID_DELETE_FILE        = "Subversion.Delete";
static const char * const CMD_ID_REVERT             = "Subversion.Revert";
static const char * const CMD_ID_SEPARATOR0         = "Subversion.Separator0";
static const char * const CMD_ID_DIFF_PROJECT       = "Subversion.DiffAll";
static const char * const CMD_ID_DIFF_CURRENT       = "Subversion.DiffCurrent";
static const char * const CMD_ID_SEPARATOR1         = "Subversion.Separator1";
static const char * const CMD_ID_COMMIT_ALL         = "Subversion.CommitAll";
static const char * const CMD_ID_COMMIT_CURRENT     = "Subversion.CommitCurrent";
static const char * const CMD_ID_SEPARATOR2         = "Subversion.Separator2";
static const char * const CMD_ID_FILELOG_CURRENT    = "Subversion.FilelogCurrent";
static const char * const CMD_ID_ANNOTATE_CURRENT   = "Subversion.AnnotateCurrent";
static const char * const CMD_ID_SEPARATOR3         = "Subversion.Separator3";
static const char * const CMD_ID_STATUS             = "Subversion.Status";
static const char * const CMD_ID_UPDATE             = "Subversion.Update";
static const char * const CMD_ID_DESCRIBE           = "Subversion.Describe";
con's avatar
con committed
99

100 101
static const char *nonInteractiveOptionC = "--non-interactive";

con's avatar
con committed
102 103 104
static const VCSBase::VCSBaseEditorParameters editorParameters[] = {
{
    VCSBase::RegularCommandOutput,
105 106
    "Subversion Command Log Editor", // kind
    "Subversion Command Log Editor", // context
con's avatar
con committed
107 108 109
    "application/vnd.nokia.text.scs_svn_commandlog",
    "scslog"},
{   VCSBase::LogOutput,
110 111
    "Subversion File Log Editor",   // kind
    "Subversion File Log Editor",   // context
con's avatar
con committed
112 113 114
    "application/vnd.nokia.text.scs_svn_filelog",
    "scsfilelog"},
{    VCSBase::AnnotateOutput,
115 116
    "Subversion Annotation Editor",  // kind
    "Subversion Annotation Editor",  // context
con's avatar
con committed
117 118 119
    "application/vnd.nokia.text.scs_svn_annotation",
    "scsannotate"},
{   VCSBase::DiffOutput,
120 121
    "Subversion Diff Editor",  // kind
    "Subversion Diff Editor",  // context
con's avatar
con committed
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
    "text/x-patch","diff"}
};

// Utility to find a parameter set by type
static inline const VCSBase::VCSBaseEditorParameters *findType(int ie)
{
    const VCSBase::EditorContentType et = static_cast<VCSBase::EditorContentType>(ie);
    return  VCSBase::VCSBaseEditor::findType(editorParameters, sizeof(editorParameters)/sizeof(VCSBase::VCSBaseEditorParameters), et);
}

static inline QString debugCodec(const QTextCodec *c)
{
    return c ? QString::fromAscii(c->name()) : QString::fromAscii("Null codec");
}

hjk's avatar
hjk committed
137
Core::IEditor* locateEditor(const char *property, const QString &entry)
con's avatar
con committed
138
{
139
    foreach (Core::IEditor *ed, Core::EditorManager::instance()->openedEditors())
con's avatar
con committed
140 141 142 143 144
        if (ed->property(property).toString() == entry)
            return ed;
    return 0;
}

145 146 147 148 149 150 151 152 153 154 155 156 157 158
// Parse "svn status" output for added/modified/deleted files
// "M<7blanks>file"
typedef QList<SubversionSubmitEditor::StatusFilePair> StatusList;

StatusList parseStatusOutput(const QString &output)
{
    StatusList changeSet;
    const QString newLine = QString(QLatin1Char('\n'));
    const QStringList list = output.split(newLine, QString::SkipEmptyParts);
    foreach (const QString &l, list) {
        const QString line =l.trimmed();
        if (line.size() > 8) {
            const QChar state = line.at(0);
            if (state == QLatin1Char('A') || state == QLatin1Char('D') || state == QLatin1Char('M')) {
159 160
                const QString fileName = line.mid(7); // Column 8 starting from svn 1.6
                changeSet.push_back(SubversionSubmitEditor::StatusFilePair(QString(state), fileName.trimmed()));
161 162 163 164 165 166 167
            }

        }
    }
    return changeSet;
}

168 169 170 171 172 173 174 175 176 177 178
// Return a list of names for the internal svn directories
static inline QStringList svnDirectories()
{
    QStringList rc(QLatin1String(".svn"));
#ifdef Q_OS_WIN
    // Option on Windows systems to avoid hassle with some IDEs
    rc.push_back(QLatin1String("_svn"));
#endif
    return rc;
}

con's avatar
con committed
179 180 181 182
// ------------- SubversionPlugin
SubversionPlugin *SubversionPlugin::m_subversionPluginInstance = 0;

SubversionPlugin::SubversionPlugin() :
183
    VCSBase::VCSBasePlugin(QLatin1String(Subversion::Constants::SUBVERSIONCOMMITEDITOR_KIND)),
184
    m_svnDirectories(svnDirectories()),
con's avatar
con committed
185 186 187 188 189 190 191 192 193 194 195 196
    m_projectExplorer(0),
    m_addAction(0),
    m_deleteAction(0),
    m_revertAction(0),
    m_diffProjectAction(0),
    m_diffCurrentAction(0),
    m_commitAllAction(0),
    m_commitCurrentAction(0),
    m_filelogCurrentAction(0),
    m_annotateCurrentAction(0),
    m_statusAction(0),
    m_updateProjectAction(0),
197
    m_describeAction(0),
con's avatar
con committed
198 199 200
    m_submitCurrentLogAction(0),
    m_submitDiffAction(0),
    m_submitUndoAction(0),
201
    m_submitRedoAction(0),
202
    m_menuAction(0),
203
    m_submitActionTriggered(false)
con's avatar
con committed
204 205 206 207 208
{
}

SubversionPlugin::~SubversionPlugin()
{
209
    cleanCommitMessageFile();
con's avatar
con committed
210 211
}

212
void SubversionPlugin::cleanCommitMessageFile()
con's avatar
con committed
213
{
214 215 216
    if (!m_commitMessageFileName.isEmpty()) {
        QFile::remove(m_commitMessageFileName);
        m_commitMessageFileName.clear();
con's avatar
con committed
217 218 219
    }
}

220 221 222 223 224
bool SubversionPlugin::isCommitEditorOpen() const
{
    return !m_commitMessageFileName.isEmpty();
}

con's avatar
con committed
225 226 227
static const VCSBase::VCSBaseSubmitEditorParameters submitParameters = {
    Subversion::Constants::SUBVERSION_SUBMIT_MIMETYPE,
    Subversion::Constants::SUBVERSIONCOMMITEDITOR_KIND,
228
    Subversion::Constants::SUBVERSIONCOMMITEDITOR
con's avatar
con committed
229 230
};

231 232 233 234 235 236 237 238 239 240
static inline Core::Command *createSeparator(QObject *parent,
                                             Core::ActionManager *ami,
                                             const char*id,
                                             const QList<int> &globalcontext)
{
    QAction *tmpaction = new QAction(parent);
    tmpaction->setSeparator(true);
    return ami->registerAction(tmpaction, id, globalcontext);
}

241
bool SubversionPlugin::initialize(const QStringList & /*arguments */, QString *errorMessage)
con's avatar
con committed
242 243 244 245 246 247 248 249
{
    typedef VCSBase::VCSSubmitEditorFactory<SubversionSubmitEditor> SubversionSubmitEditorFactory;
    typedef VCSBase::VCSEditorFactory<SubversionEditor> SubversionEditorFactory;
    using namespace Constants;

    using namespace Core::Constants;
    using namespace ExtensionSystem;

250 251
    VCSBase::VCSBasePlugin::initialize(new SubversionControl(this));

con's avatar
con committed
252
    m_subversionPluginInstance = this;
hjk's avatar
hjk committed
253
    Core::ICore *core = Core::ICore::instance();
con's avatar
con committed
254

hjk's avatar
hjk committed
255
    if (!core->mimeDatabase()->addMimeTypes(QLatin1String(":/trolltech.subversion/Subversion.mimetypes.xml"), errorMessage))
con's avatar
con committed
256 257
        return false;

hjk's avatar
hjk committed
258
    if (QSettings *settings = core->settings())
con's avatar
con committed
259 260
        m_settings.fromSettings(settings);

261
    addAutoReleasedObject(new SettingsPage);
con's avatar
con committed
262

263
    addAutoReleasedObject(new SubversionSubmitEditorFactory(&submitParameters));
con's avatar
con committed
264 265 266

    static const char *describeSlot = SLOT(describe(QString,QString));
    const int editorCount = sizeof(editorParameters)/sizeof(VCSBase::VCSBaseEditorParameters);
267 268
    for (int i = 0; i < editorCount; i++)
        addAutoReleasedObject(new SubversionEditorFactory(editorParameters + i, this, describeSlot));
con's avatar
con committed
269

270 271
    addAutoReleasedObject(new CheckoutWizard);

con's avatar
con committed
272
    //register actions
hjk's avatar
hjk committed
273
    Core::ActionManager *ami = core->actionManager();
274
    Core::ActionContainer *toolsContainer = ami->actionContainer(M_TOOLS);
con's avatar
con committed
275

276
    Core::ActionContainer *subversionMenu =
277
        ami->createMenu(QLatin1String(CMD_ID_SUBVERSION_MENU));
con's avatar
con committed
278 279
    subversionMenu->menu()->setTitle(tr("&Subversion"));
    toolsContainer->addMenu(subversionMenu);
280
    m_menuAction = subversionMenu->menu()->menuAction();
con's avatar
con committed
281
    QList<int> globalcontext;
hjk's avatar
hjk committed
282
    globalcontext << core->uniqueIDManager()->uniqueIdentifier(C_GLOBAL);
con's avatar
con committed
283

con's avatar
con committed
284
    Core::Command *command;
285
    m_addAction = new Utils::ParameterAction(tr("Add"), tr("Add \"%1\""), Utils::ParameterAction::EnabledWithParameter, this);
286
    command = ami->registerAction(m_addAction, CMD_ID_ADD,
con's avatar
con committed
287
        globalcontext);
con's avatar
con committed
288
    command->setAttribute(Core::Command::CA_UpdateText);
con's avatar
con committed
289 290 291 292
    command->setDefaultKeySequence(QKeySequence(tr("Alt+S,Alt+A")));
    connect(m_addAction, SIGNAL(triggered()), this, SLOT(addCurrentFile()));
    subversionMenu->addAction(command);

293
    m_deleteAction = new Utils::ParameterAction(tr("Delete"), tr("Delete \"%1\""), Utils::ParameterAction::EnabledWithParameter, this);
294
    command = ami->registerAction(m_deleteAction, CMD_ID_DELETE_FILE,
con's avatar
con committed
295
        globalcontext);
con's avatar
con committed
296
    command->setAttribute(Core::Command::CA_UpdateText);
con's avatar
con committed
297 298 299
    connect(m_deleteAction, SIGNAL(triggered()), this, SLOT(deleteCurrentFile()));
    subversionMenu->addAction(command);

300
    m_revertAction = new Utils::ParameterAction(tr("Revert"), tr("Revert \"%1\""), Utils::ParameterAction::EnabledWithParameter, this);
301
    command = ami->registerAction(m_revertAction, CMD_ID_REVERT,
con's avatar
con committed
302
        globalcontext);
con's avatar
con committed
303
    command->setAttribute(Core::Command::CA_UpdateText);
con's avatar
con committed
304 305 306
    connect(m_revertAction, SIGNAL(triggered()), this, SLOT(revertCurrentFile()));
    subversionMenu->addAction(command);

307
    subversionMenu->addAction(createSeparator(this, ami, CMD_ID_SEPARATOR0, globalcontext));
con's avatar
con committed
308 309

    m_diffProjectAction = new QAction(tr("Diff Project"), this);
310
    command = ami->registerAction(m_diffProjectAction, CMD_ID_DIFF_PROJECT,
con's avatar
con committed
311 312 313 314
        globalcontext);
    connect(m_diffProjectAction, SIGNAL(triggered()), this, SLOT(diffProject()));
    subversionMenu->addAction(command);

315
    m_diffCurrentAction = new Utils::ParameterAction(tr("Diff Current File"), tr("Diff \"%1\""), Utils::ParameterAction::EnabledWithParameter, this);
con's avatar
con committed
316
    command = ami->registerAction(m_diffCurrentAction,
317
        CMD_ID_DIFF_CURRENT, globalcontext);
con's avatar
con committed
318
    command->setAttribute(Core::Command::CA_UpdateText);
con's avatar
con committed
319 320 321 322
    command->setDefaultKeySequence(QKeySequence(tr("Alt+S,Alt+D")));
    connect(m_diffCurrentAction, SIGNAL(triggered()), this, SLOT(diffCurrentFile()));
    subversionMenu->addAction(command);

323
    subversionMenu->addAction(createSeparator(this, ami, CMD_ID_SEPARATOR1, globalcontext));
con's avatar
con committed
324 325

    m_commitAllAction = new QAction(tr("Commit All Files"), this);
326
    command = ami->registerAction(m_commitAllAction, CMD_ID_COMMIT_ALL,
con's avatar
con committed
327 328 329 330
        globalcontext);
    connect(m_commitAllAction, SIGNAL(triggered()), this, SLOT(startCommitAll()));
    subversionMenu->addAction(command);

331
    m_commitCurrentAction = new Utils::ParameterAction(tr("Commit Current File"), tr("Commit \"%1\""), Utils::ParameterAction::EnabledWithParameter, this);
con's avatar
con committed
332
    command = ami->registerAction(m_commitCurrentAction,
333
        CMD_ID_COMMIT_CURRENT, globalcontext);
con's avatar
con committed
334
    command->setAttribute(Core::Command::CA_UpdateText);
con's avatar
con committed
335 336 337 338
    command->setDefaultKeySequence(QKeySequence(tr("Alt+S,Alt+C")));
    connect(m_commitCurrentAction, SIGNAL(triggered()), this, SLOT(startCommitCurrentFile()));
    subversionMenu->addAction(command);

339
    subversionMenu->addAction(createSeparator(this, ami, CMD_ID_SEPARATOR2, globalcontext));
con's avatar
con committed
340

341
    m_filelogCurrentAction = new Utils::ParameterAction(tr("Filelog Current File"), tr("Filelog \"%1\""), Utils::ParameterAction::EnabledWithParameter, this);
con's avatar
con committed
342
    command = ami->registerAction(m_filelogCurrentAction,
343
        CMD_ID_FILELOG_CURRENT, globalcontext);
con's avatar
con committed
344
    command->setAttribute(Core::Command::CA_UpdateText);
con's avatar
con committed
345 346 347 348
    connect(m_filelogCurrentAction, SIGNAL(triggered()), this,
        SLOT(filelogCurrentFile()));
    subversionMenu->addAction(command);

349
    m_annotateCurrentAction = new Utils::ParameterAction(tr("Annotate Current File"), tr("Annotate \"%1\""), Utils::ParameterAction::EnabledWithParameter, this);
con's avatar
con committed
350
    command = ami->registerAction(m_annotateCurrentAction,
351
        CMD_ID_ANNOTATE_CURRENT, globalcontext);
con's avatar
con committed
352
    command->setAttribute(Core::Command::CA_UpdateText);
con's avatar
con committed
353 354 355 356
    connect(m_annotateCurrentAction, SIGNAL(triggered()), this,
        SLOT(annotateCurrentFile()));
    subversionMenu->addAction(command);

357
    m_describeAction = new QAction(tr("Describe..."), this);
358
    command = ami->registerAction(m_describeAction, CMD_ID_DESCRIBE, globalcontext);
359 360 361
    connect(m_describeAction, SIGNAL(triggered()), this, SLOT(slotDescribe()));
    subversionMenu->addAction(command);

362
    subversionMenu->addAction(createSeparator(this, ami, CMD_ID_SEPARATOR3, globalcontext));
con's avatar
con committed
363 364

    m_statusAction = new QAction(tr("Project Status"), this);
365
    command = ami->registerAction(m_statusAction, CMD_ID_STATUS,
con's avatar
con committed
366 367 368 369 370
        globalcontext);
    connect(m_statusAction, SIGNAL(triggered()), this, SLOT(projectStatus()));
    subversionMenu->addAction(command);

    m_updateProjectAction = new QAction(tr("Update Project"), this);
371
    command = ami->registerAction(m_updateProjectAction, CMD_ID_UPDATE, globalcontext);
con's avatar
con committed
372 373 374 375 376
    connect(m_updateProjectAction, SIGNAL(triggered()), this, SLOT(updateProject()));
    subversionMenu->addAction(command);

    // Actions of the submit editor
    QList<int> svncommitcontext;
377
    svncommitcontext << Core::UniqueIDManager::instance()->uniqueIdentifier(Constants::SUBVERSIONCOMMITEDITOR);
con's avatar
con committed
378

379
    m_submitCurrentLogAction = new QAction(VCSBase::VCSBaseSubmitEditor::submitIcon(), tr("Commit"), this);
con's avatar
con committed
380 381 382
    command = ami->registerAction(m_submitCurrentLogAction, Constants::SUBMIT_CURRENT, svncommitcontext);
    connect(m_submitCurrentLogAction, SIGNAL(triggered()), this, SLOT(submitCurrentLog()));

383
    m_submitDiffAction = new QAction(VCSBase::VCSBaseSubmitEditor::diffIcon(), tr("Diff Selected Files"), this);
con's avatar
con committed
384 385 386 387 388 389 390 391 392 393 394 395 396
    command = ami->registerAction(m_submitDiffAction , Constants::DIFF_SELECTED, svncommitcontext);

    m_submitUndoAction = new QAction(tr("&Undo"), this);
    command = ami->registerAction(m_submitUndoAction, Core::Constants::UNDO, svncommitcontext);

    m_submitRedoAction = new QAction(tr("&Redo"), this);
    command = ami->registerAction(m_submitRedoAction, Core::Constants::REDO, svncommitcontext);

    return true;
}

void SubversionPlugin::extensionsInitialized()
{
397
    m_projectExplorer = ProjectExplorer::ProjectExplorerPlugin::instance();
con's avatar
con committed
398 399
}

400
bool SubversionPlugin::submitEditorAboutToClose(VCSBase::VCSBaseSubmitEditor *submitEditor)
con's avatar
con committed
401
{
402
    if (!isCommitEditorOpen())
con's avatar
con committed
403 404
        return true;

405 406
    Core::IFile *fileIFace = submitEditor->file();
    const SubversionSubmitEditor *editor = qobject_cast<SubversionSubmitEditor *>(submitEditor);
con's avatar
con committed
407 408 409 410 411 412
    if (!fileIFace || !editor)
        return true;

    // Submit editor closing. Make it write out the commit message
    // and retrieve files
    const QFileInfo editorFile(fileIFace->fileName());
413
    const QFileInfo changeFile(m_commitMessageFileName);
con's avatar
con committed
414 415 416
    if (editorFile.absoluteFilePath() != changeFile.absoluteFilePath())
        return true; // Oops?!

417 418
    // Prompt user. Force a prompt unless submit was actually invoked (that
    // is, the editor was closed or shutdown).
419
    SubversionSettings newSettings = m_settings;
420 421 422
    const VCSBase::VCSBaseSubmitEditor::PromptSubmitResult answer =
            editor->promptSubmit(tr("Closing Subversion Editor"),
                                 tr("Do you want to commit the change?"),
423
                                 tr("The commit message check failed. Do you want to commit the change?"),
424
                                 &newSettings.promptToSubmit, !m_submitActionTriggered);
425
    m_submitActionTriggered = false;
con's avatar
con committed
426
    switch (answer) {
427
    case VCSBase::VCSBaseSubmitEditor::SubmitCanceled:
con's avatar
con committed
428
        return false; // Keep editing and change file
429
    case VCSBase::VCSBaseSubmitEditor::SubmitDiscarded:
430
        cleanCommitMessageFile();
con's avatar
con committed
431 432 433 434
        return true; // Cancel all
    default:
        break;
    }
435
    setSettings(newSettings); // in case someone turned prompting off
con's avatar
con committed
436
    const QStringList fileList = editor->checkedFiles();
437
    bool closeEditor = true;
con's avatar
con committed
438 439
    if (!fileList.empty()) {
        // get message & commit
hjk's avatar
hjk committed
440
        Core::ICore::instance()->fileManager()->blockFileChange(fileIFace);
con's avatar
con committed
441
        fileIFace->save();
hjk's avatar
hjk committed
442
        Core::ICore::instance()->fileManager()->unblockFileChange(fileIFace);
443
        closeEditor= commit(m_commitMessageFileName, fileList);
con's avatar
con committed
444
    }
445
    if (closeEditor)
446
        cleanCommitMessageFile();
447
    return closeEditor;
con's avatar
con committed
448 449 450 451 452 453 454 455 456 457 458 459
}

void SubversionPlugin::diffFiles(const QStringList &files)
{
    svnDiff(files);
}

void SubversionPlugin::svnDiff(const QStringList &files, QString diffname)
{
    if (Subversion::Constants::debug)
        qDebug() << Q_FUNC_INFO << files << diffname;
    const QString source = files.empty() ? QString() : files.front();
460
    QTextCodec *codec = source.isEmpty() ? static_cast<QTextCodec *>(0) : VCSBase::VCSBaseEditor::getCodec(source);
con's avatar
con committed
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475

    if (files.count() == 1 && diffname.isEmpty())
        diffname = QFileInfo(files.front()).fileName();

    QStringList args(QLatin1String("diff"));
    args << files;

    const SubversionResponse response = runSvn(args, subversionShortTimeOut, false, codec);
    if (response.error)
        return;

    // diff of a single file? re-use an existing view if possible to support
    // the common usage pattern of continuously changing and diffing a file
    if (files.count() == 1) {
        // Show in the same editor if diff has been executed before
hjk's avatar
hjk committed
476
        if (Core::IEditor *editor = locateEditor("originalFileName", files.front())) {
con's avatar
con committed
477
            editor->createNew(response.stdOut);
478
            Core::EditorManager::instance()->activateEditor(editor);
con's avatar
con committed
479 480 481
            return;
        }
    }
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
482
    const QString title = QString::fromLatin1("svn diff %1").arg(diffname);
con's avatar
con committed
483 484 485 486 487 488 489
    Core::IEditor *editor = showOutputInEditor(title, response.stdOut, VCSBase::DiffOutput, source, codec);
    if (files.count() == 1)
        editor->setProperty("originalFileName", files.front());
}

SubversionSubmitEditor *SubversionPlugin::openSubversionSubmitEditor(const QString &fileName)
{
490
    Core::IEditor *editor = Core::EditorManager::instance()->openEditor(fileName, QLatin1String(Constants::SUBVERSIONCOMMITEDITOR_KIND));
con's avatar
con committed
491
    SubversionSubmitEditor *submitEditor = qobject_cast<SubversionSubmitEditor*>(editor);
hjk's avatar
hjk committed
492
    QTC_ASSERT(submitEditor, /**/);
493
    submitEditor->registerActions(m_submitUndoAction, m_submitRedoAction, m_submitCurrentLogAction, m_submitDiffAction);
con's avatar
con committed
494 495 496 497 498
    connect(submitEditor, SIGNAL(diffSelectedFiles(QStringList)), this, SLOT(diffFiles(QStringList)));

    return submitEditor;
}

499
void SubversionPlugin::updateActions(VCSBase::VCSBasePlugin::ActionState as)
con's avatar
con committed
500
{
501 502 503
    if (!VCSBase::VCSBasePlugin::enableMenuAction(as, m_menuAction))
        return;

con's avatar
con committed
504 505 506
    m_diffProjectAction->setEnabled(true);
    m_commitAllAction->setEnabled(true);
    m_statusAction->setEnabled(true);
507
    m_describeAction->setEnabled(true);
con's avatar
con committed
508

509 510 511 512 513 514 515 516 517 518
    const QString fileName = currentFileName();
    const QString baseName = fileName.isEmpty() ? fileName : QFileInfo(fileName).fileName();

    m_addAction->setParameter(baseName);
    m_deleteAction->setParameter(baseName);
    m_revertAction->setParameter(baseName);
    m_diffCurrentAction->setParameter(baseName);
    m_commitCurrentAction->setParameter(baseName);
    m_filelogCurrentAction->setParameter(baseName);
    m_annotateCurrentAction->setParameter(baseName);
con's avatar
con committed
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
}

void SubversionPlugin::addCurrentFile()
{
    const QString file = currentFileName();
    if (!file.isEmpty())
        vcsAdd(file);
}

void SubversionPlugin::deleteCurrentFile()
{
    const QString file = currentFileName();
    if (!file.isEmpty())
        vcsDelete(file);
}

void SubversionPlugin::revertCurrentFile()
{
    const QString file = QDir::toNativeSeparators(currentFileName());
    if (file.isEmpty())
        return;

    QStringList args(QLatin1String("diff"));
    args.push_back(file);

    const SubversionResponse diffResponse = runSvn(args, subversionShortTimeOut, false);
    if (diffResponse.error)
        return;

    if (diffResponse.stdOut.isEmpty())
        return;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
550
    if (QMessageBox::warning(0, QLatin1String("svn revert"), tr("The file has been changed. Do you want to revert it?"),
con's avatar
con committed
551 552 553
                             QMessageBox::Yes, QMessageBox::No) == QMessageBox::No)
        return;

554 555

    Core::FileChangeBlocker fcb(file);
con's avatar
con committed
556 557 558 559 560 561 562

    // revert
    args.clear();
    args.push_back(QLatin1String("revert"));
    args.append(file);

    const SubversionResponse revertResponse = runSvn(args, subversionShortTimeOut, true);
563 564
    if (!revertResponse.error) {
        fcb.setModifiedReload(true);
565
        subVersionControl()->emitFilesChanged(QStringList(file));
con's avatar
con committed
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
    }
}

// Get a unique set of toplevel directories for the current projects.
// To be used for "diff all" or "commit all".
QStringList SubversionPlugin::currentProjectsTopLevels(QString *name) const
{
    typedef QList<ProjectExplorer::Project *> ProjectList;
    ProjectList projects;
    // Compile list of projects
    if (ProjectExplorer::Project *currentProject = m_projectExplorer->currentProject()) {
        projects.push_back(currentProject);
    } else {
        if (const ProjectExplorer::SessionManager *session = m_projectExplorer->session())
            projects.append(session->projects());
    }
    // Get unique set of toplevels and concat project names
    QStringList toplevels;
    const QChar blank(QLatin1Char(' '));
    foreach (const ProjectExplorer::Project *p,  projects) {
        if (name) {
            if (!name->isEmpty())
                name->append(blank);
            name->append(p->name());
        }

        const QString projectPath = QFileInfo(p->file()->fileName()).absolutePath();
        const QString topLevel = findTopLevelForDirectory(projectPath);
        if (!topLevel.isEmpty() && !toplevels.contains(topLevel))
            toplevels.push_back(topLevel);
    }
    return toplevels;
}

void SubversionPlugin::diffProject()
{
    QString diffName;
    const QStringList topLevels = currentProjectsTopLevels(&diffName);
    if (!topLevels.isEmpty())
        svnDiff(topLevels, diffName);
}

void SubversionPlugin::diffCurrentFile()
{
    svnDiff(QStringList(currentFileName()));
}

void SubversionPlugin::startCommitCurrentFile()
{
    const QString file = QDir::toNativeSeparators(currentFileName());
    if (!file.isEmpty())
        startCommit(QStringList(file));
}

void SubversionPlugin::startCommitAll()
{
    // Make sure we have only repository for commit
    const QStringList files = currentProjectsTopLevels();
    switch (files.size()) {
    case 0:
        break;
    case 1:
        startCommit(files);
        break;
    default: {
631
        const QString msg = tr("The commit list spans several repositories (%1). Please commit them one by one.").
con's avatar
con committed
632
            arg(files.join(QString(QLatin1Char(' '))));
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
633
        QMessageBox::warning(0, QLatin1String("svn commit"), msg, QMessageBox::Ok);
con's avatar
con committed
634 635 636 637 638 639 640 641 642 643 644 645
    }
        break;
    }
}

/* Start commit of files of a single repository by displaying
 * template and files in a submit editor. On closing, the real
 * commit will start. */
void SubversionPlugin::startCommit(const QStringList &files)
{
    if (files.empty())
        return;
646 647
    if (VCSBase::VCSBaseSubmitEditor::raiseSubmitEditor())
        return;
648
    if (isCommitEditorOpen()) {
649
        VCSBase::VCSBaseOutputWindow::instance()->appendWarning(tr("Another commit is currently being executed."));
con's avatar
con committed
650 651 652 653 654 655 656 657 658 659 660 661
        return;
    }

    QStringList args(QLatin1String("status"));
    args += files;
    if (args.size() == 1)
        return;

    const SubversionResponse response = runSvn(args, subversionShortTimeOut, false);
    if (response.error)
        return;
    // Get list of added/modified/deleted files
662
    const StatusList statusOutput = parseStatusOutput(response.stdOut);
con's avatar
con committed
663
    if (statusOutput.empty()) {
664
        VCSBase::VCSBaseOutputWindow::instance()->appendWarning(tr("There are no modified files."));
con's avatar
con committed
665 666 667 668
        return;
    }

    // Create a new submit change file containing the submit template
669 670 671 672
    QTemporaryFile changeTmpFile;
    changeTmpFile.setAutoRemove(false);
    if (!changeTmpFile.open()) {
        VCSBase::VCSBaseOutputWindow::instance()->appendError(tr("Cannot create temporary file: %1").arg(changeTmpFile.errorString()));
con's avatar
con committed
673 674
        return;
    }
675
    m_commitMessageFileName = changeTmpFile.fileName();
676
    // TODO: Regitctrieve submit template from
con's avatar
con committed
677 678
    const QString submitTemplate;
    // Create a submit
679 680 681
    changeTmpFile.write(submitTemplate.toUtf8());
    changeTmpFile.flush();
    changeTmpFile.close();
con's avatar
con committed
682
    // Create a submit editor and set file list
683
    SubversionSubmitEditor *editor = openSubversionSubmitEditor(m_commitMessageFileName);
684
    editor->setStatusList(statusOutput);
con's avatar
con committed
685 686 687 688 689 690 691 692 693 694 695
}

bool SubversionPlugin::commit(const QString &messageFile,
                              const QStringList &subVersionFileList)
{
    if (Subversion::Constants::debug)
        qDebug() << Q_FUNC_INFO << messageFile << subVersionFileList;
    // Transform the status list which is sth
    // "[ADM]<blanks>file" into an args list. The files of the status log
    // can be relative or absolute depending on where the command was run.
    QStringList args = QStringList(QLatin1String("commit"));
696
    args << QLatin1String(nonInteractiveOptionC) << QLatin1String("--file") << messageFile;
con's avatar
con committed
697 698 699 700 701 702 703 704 705 706 707 708 709 710
    args.append(subVersionFileList);
    const SubversionResponse response = runSvn(args, subversionLongTimeOut, true);
    return !response.error ;
}

void SubversionPlugin::filelogCurrentFile()
{
    const QString file = currentFileName();
    if (!file.isEmpty())
        filelog(file);
}

void SubversionPlugin::filelog(const QString &file)
{
711
    QTextCodec *codec = VCSBase::VCSBaseEditor::getCodec(file);
con's avatar
con committed
712 713 714 715 716 717 718 719 720 721 722
    // no need for temp file
    QStringList args(QLatin1String("log"));
    args.append(QDir::toNativeSeparators(file));

    const SubversionResponse response = runSvn(args, subversionShortTimeOut, false, codec);
    if (response.error)
        return;

    // Re-use an existing view if possible to support
    // the common usage pattern of continuously changing and diffing a file

hjk's avatar
hjk committed
723
    if (Core::IEditor *editor = locateEditor("logFileName", file)) {
con's avatar
con committed
724
        editor->createNew(response.stdOut);
725
        Core::EditorManager::instance()->activateEditor(editor);
con's avatar
con committed
726
    } else {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
727
        const QString title = QString::fromLatin1("svn log %1").arg(QFileInfo(file).fileName());
con's avatar
con committed
728 729 730 731 732 733 734 735 736 737 738 739
        Core::IEditor *newEditor = showOutputInEditor(title, response.stdOut, VCSBase::LogOutput, file, codec);
        newEditor->setProperty("logFileName", file);
    }
}

void SubversionPlugin::updateProject()
{
    const QStringList topLevels = currentProjectsTopLevels();
    if (topLevels.empty())
        return;

    QStringList args(QLatin1String("update"));
740
    args.push_back(QLatin1String(nonInteractiveOptionC));
con's avatar
con committed
741
    args.append(topLevels);
742
    const SubversionResponse response = runSvn(args, subversionLongTimeOut, true);
743
    if (!response.error) {
744
        foreach(const QString &repo, topLevels)
745 746
            subVersionControl()->emitRepositoryChanged(repo);
    }
con's avatar
con committed
747 748 749 750 751 752 753 754 755 756 757
}

void SubversionPlugin::annotateCurrentFile()
{
    const QString file = currentFileName();
    if (!file.isEmpty())
        annotate(file);
}

void SubversionPlugin::annotate(const QString &file)
{
758
    QTextCodec *codec = VCSBase::VCSBaseEditor::getCodec(file);
con's avatar
con committed
759 760 761 762 763 764 765 766 767 768 769

    QStringList args(QLatin1String("annotate"));
    args.push_back(QLatin1String("-v"));
    args.append(QDir::toNativeSeparators(file));

    const SubversionResponse response = runSvn(args, subversionShortTimeOut, false, codec);
    if (response.error)
        return;

    // Re-use an existing view if possible to support
    // the common usage pattern of continuously changing and diffing a file
770
    const int lineNumber = VCSBase::VCSBaseEditor::lineNumberOfCurrentEditor(file);
con's avatar
con committed
771

hjk's avatar
hjk committed
772
    if (Core::IEditor *editor = locateEditor("annotateFileName", file)) {
con's avatar
con committed
773
        editor->createNew(response.stdOut);
774 775
        VCSBase::VCSBaseEditor::gotoLineOfEditor(editor, lineNumber);
        Core::EditorManager::instance()->activateEditor(editor);        
con's avatar
con committed
776
    } else {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
777
        const QString title = QString::fromLatin1("svn annotate %1").arg(QFileInfo(file).fileName());
con's avatar
con committed
778 779
        Core::IEditor *newEditor = showOutputInEditor(title, response.stdOut, VCSBase::AnnotateOutput, file, codec);
        newEditor->setProperty("annotateFileName", file);
780
        VCSBase::VCSBaseEditor::gotoLineOfEditor(newEditor, lineNumber);
con's avatar
con committed
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
    }
}

void SubversionPlugin::projectStatus()
{
    if (!m_projectExplorer)
        return;

    QStringList args(QLatin1String("status"));
    args += currentProjectsTopLevels();

    if (args.size() == 1)
        return;

    runSvn(args, subversionShortTimeOut, true);
}

void SubversionPlugin::describe(const QString &source, const QString &changeNr)
{
    // To describe a complete change, find the top level and then do
    //svn diff -r 472958:472959 <top level>
    const QFileInfo fi(source);
    const QString topLevel = findTopLevelForDirectory(fi.isDir() ? source : fi.absolutePath());
    if (topLevel.isEmpty())
        return;
    if (Subversion::Constants::debug)
        qDebug() << Q_FUNC_INFO << source << topLevel << changeNr;
    // Number must be > 1
    bool ok;
    const int number = changeNr.toInt(&ok);
    if (!ok || number < 2)
        return;
813 814 815 816 817 818 819 820 821 822 823 824 825 826
    // Run log to obtain message (local utf8)
    QString description;
    QStringList args(QLatin1String("log"));
    args.push_back(QLatin1String("-r"));
    args.push_back(changeNr);
    args.push_back(topLevel);
    const SubversionResponse logResponse = runSvn(args, subversionShortTimeOut, false);
    if (logResponse.error)
        return;
    description = logResponse.stdOut;

    // Run diff (encoding via source codec)
    args.clear();
    args.push_back(QLatin1String("diff"));
con's avatar
con committed
827 828 829 830 831 832
    args.push_back(QLatin1String("-r"));
    QString diffArg;
    QTextStream(&diffArg) << (number - 1) << ':' << number;
    args.push_back(diffArg);
    args.push_back(topLevel);

833
    QTextCodec *codec = VCSBase::VCSBaseEditor::getCodec(source);
con's avatar
con committed
834 835 836
    const SubversionResponse response = runSvn(args, subversionShortTimeOut, false, codec);
    if (response.error)
        return;
837
    description += response.stdOut;
con's avatar
con committed
838 839 840 841

    // Re-use an existing view if possible to support
    // the common usage pattern of continuously changing and diffing a file
    const QString id = diffArg + source;
hjk's avatar
hjk committed
842
    if (Core::IEditor *editor = locateEditor("describeChange", id)) {
843
        editor->createNew(description);
hjk's avatar
hjk committed
844
        Core::EditorManager::instance()->activateEditor(editor);
con's avatar
con committed
845
    } else {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
846
        const QString title = QString::fromLatin1("svn describe %1#%2").arg(QFileInfo(source).fileName(), changeNr);
847
        Core::IEditor *newEditor = showOutputInEditor(title, description, VCSBase::DiffOutput, source, codec);
con's avatar
con committed
848 849 850 851
        newEditor->setProperty("describeChange", id);
    }
}

852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
void SubversionPlugin::slotDescribe()
{
    const QStringList topLevels = currentProjectsTopLevels();
    if (topLevels.size() != 1)
        return;

    QInputDialog inputDialog(Core::ICore::instance()->mainWindow());
    inputDialog.setWindowFlags(inputDialog.windowFlags() & ~Qt::WindowContextHelpButtonHint);
    inputDialog.setInputMode(QInputDialog::IntInput);
    inputDialog.setIntRange(2, INT_MAX);
    inputDialog.setWindowTitle(tr("Describe"));
    inputDialog.setLabelText(tr("Revision number:"));
    if (inputDialog.exec() != QDialog::Accepted)
        return;

    const int revision = inputDialog.intValue();
    describe(topLevels.front(), QString::number(revision));
}

con's avatar
con committed
871 872
void SubversionPlugin::submitCurrentLog()
{
873
    m_submitActionTriggered = true;
874 875
    Core::EditorManager::instance()->closeEditors(QList<Core::IEditor*>()
        << Core::EditorManager::instance()->currentEditor());
con's avatar
con committed
876 877 878 879
}

QString SubversionPlugin::currentFileName() const
{
hjk's avatar
hjk committed
880
    const QString fileName = Core::ICore::instance()->fileManager()->currentFile();
con's avatar
con committed
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
    if (!fileName.isEmpty()) {
        const QFileInfo fi(fileName);
        if (fi.exists())
            return fi.canonicalFilePath();
    }
    return QString();
}

static inline QString processStdErr(QProcess &proc)
{
    return QString::fromLocal8Bit(proc.readAllStandardError()).remove(QLatin1Char('\r'));
}

static inline QString processStdOut(QProcess &proc, QTextCodec *outputCodec = 0)
{
    const QByteArray stdOutData = proc.readAllStandardOutput();
    QString stdOut = outputCodec ? outputCodec->toUnicode(stdOutData) : QString::fromLocal8Bit(stdOutData);
    return stdOut.remove(QLatin1Char('\r'));
}

SubversionResponse SubversionPlugin::runSvn(const QStringList &arguments,
                                            int timeOut,
                                            bool showStdOutInOutputWindow,
                                            QTextCodec *outputCodec)
{
    const QString executable = m_settings.svnCommand;
    SubversionResponse response;
    if (executable.isEmpty()) {
        response.error = true;
        response.message =tr("No subversion executable specified!");
        return response;
    }
    const QStringList allArgs = m_settings.addOptions(arguments);

915
    VCSBase::VCSBaseOutputWindow *outputWindow = VCSBase::VCSBaseOutputWindow::instance();
con's avatar
con committed
916
    // Hide passwords, etc in the log window
917 918 919
    //: Executing: <executable> <arguments>
    const QString outputText = tr("Executing: %1 %2\n").arg(executable, SubversionSettings::formatArguments(allArgs));
    outputWindow->appendCommand(outputText);
con's avatar
con committed
920 921 922 923 924

    if (Subversion::Constants::debug)
        qDebug() << "runSvn" << timeOut << outputText;

    // Run, connect stderr to the output window
925
    Utils::SynchronousProcess process;
con's avatar
con committed
926 927 928 929
    process.setTimeout(timeOut);
    process.setStdOutCodec(outputCodec);

    process.setStdErrBufferedSignalsEnabled(true);
930
    connect(&process, SIGNAL(stdErrBuffered(QString,bool)), outputWindow, SLOT(append(QString)));
con's avatar
con committed
931 932 933 934

    // connect stdout to the output window if desired
    if (showStdOutInOutputWindow) {
        process.setStdOutBufferedSignalsEnabled(true);
935
        connect(&process, SIGNAL(stdOutBuffered(QString,bool)), outputWindow, SLOT(append(QString)));
con's avatar
con committed
936 937
    }

938
    const Utils::SynchronousProcessResponse sp_resp = process.run(executable, allArgs);
con's avatar
con committed
939 940 941 942
    response.error = true;
    response.stdErr = sp_resp.stdErr;
    response.stdOut = sp_resp.stdOut;
    switch (sp_resp.result) {
943
    case Utils::SynchronousProcessResponse::Finished:
con's avatar
con committed
944 945
        response.error = false;
        break;
946
    case Utils::SynchronousProcessResponse::FinishedError:
con's avatar
con committed
947 948
        response.message = tr("The process terminated with exit code %1.").arg(sp_resp.exitCode);
        break;
949
    case Utils::SynchronousProcessResponse::TerminatedAbnormally:
con's avatar
con committed
950 951
        response.message = tr("The process terminated abnormally.");
        break;
952
    case Utils::SynchronousProcessResponse::StartFailed:
con's avatar
con committed
953 954
        response.message = tr("Could not start subversion '%1'. Please check your settings in the preferences.").arg(executable);
        break;
955
    case Utils::SynchronousProcessResponse::Hang:
con's avatar
con committed
956 957 958 959
        response.message = tr("Subversion did not respond within timeout limit (%1 ms).").arg(timeOut);
        break;
    }
    if (response.error)
960
        outputWindow->appendError(response.message);
con's avatar
con committed
961 962 963 964 965 966 967 968 969

    return response;
}

Core::IEditor * SubversionPlugin::showOutputInEditor(const QString& title, const QString &output,
                                                     int editorType, const QString &source,
                                                     QTextCodec *codec)
{
    const VCSBase::VCSBaseEditorParameters *params = findType(editorType);
hjk's avatar
hjk committed
970
    QTC_ASSERT(params, return 0);
con's avatar
con committed
971 972 973 974
    const QString kind = QLatin1String(params->kind);
    if (Subversion::Constants::debug)
        qDebug() << "SubversionPlugin::showOutputInEditor" << title << kind <<  "Size= " << output.size() <<  " Type=" << editorType << debugCodec(codec);
    QString s = title;
con's avatar
con committed
975
    Core::IEditor *editor = Core::EditorManager::instance()->openEditorWithContents(kind, &s, output);
976
    SubversionEditor *e = qobject_cast<SubversionEditor*>(editor->widget());
con's avatar
con committed
977 978 979 980 981 982 983 984
    if (!e)
        return 0;
    s.replace(QLatin1Char(' '), QLatin1Char('_'));
    e->setSuggestedFileName(s);
    if (!source.isEmpty())
        e->setSource(source);
    if (codec)
        e->setCodec(codec);
985 986 987
    Core::IEditor *ie = e->editableInterface();
    Core::EditorManager::instance()->activateEditor(ie);
    return ie;
con's avatar
con committed
988 989 990 991 992 993 994 995 996 997 998
}

SubversionSettings SubversionPlugin::settings() const
{
    return m_settings;
}

void SubversionPlugin::setSettings(const SubversionSettings &s)
{
    if (s != m_settings) {
        m_settings = s;
hjk's avatar
hjk committed
999
        if (QSettings *settings = Core::ICore::instance()->settings())
con's avatar
con committed
1000 1001 1002 1003 1004 1005
            m_settings.toSettings(settings);
    }
}

SubversionPlugin *SubversionPlugin::subversionPluginInstance()
{
hjk's avatar
hjk committed
1006
    QTC_ASSERT(m_subversionPluginInstance, return m_subversionPluginInstance);
con's avatar
con committed
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 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
    return m_subversionPluginInstance;
}

bool SubversionPlugin::vcsAdd(const QString &rawFileName)
{
    const QString file = QDir::toNativeSeparators(rawFileName);
    QStringList args(QLatin1String("add"));
    args.push_back(file);

    const SubversionResponse response = runSvn(args, subversionShortTimeOut, true);
    return !response.error;
}

bool SubversionPlugin::vcsDelete(const QString &rawFileName)
{
    const QString file = QDir::toNativeSeparators(rawFileName);

    QStringList args(QLatin1String("delete"));
    args.push_back(file);

    const SubversionResponse response = runSvn(args, subversionShortTimeOut, true);
    return !response.error;
}

/* Subversion has ".svn" directory in each directory
 * it manages. The top level is the first directory
 * under the directory that does not have a  ".svn". */
bool SubversionPlugin::managesDirectory(const QString &directory) const
{
    const QDir dir(directory);
    const bool rc = dir.exists() && managesDirectory(dir);
    if (Subversion::Constants::debug)
        qDebug() << "SubversionPlugin::managesDirectory" << directory << rc;
    return rc;
}

bool SubversionPlugin::managesDirectory(const QDir &directory) const
{
1045 1046 1047 1048 1049 1050 1051
    const int dirCount = m_svnDirectories.size();
    for (int i = 0; i < dirCount; i++) {
        const QString svnDir = directory.absoluteFilePath(m_svnDirectories.at(i));
        if (QFileInfo(svnDir).isDir())
            return true;
    }
    return false;
con's avatar
con committed
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
}

QString SubversionPlugin::findTopLevelForDirectory(const QString &directory) const
{
    // Debug wrapper
    const QString rc = findTopLevelForDirectoryI(directory);
    if (Subversion::Constants::debug)
        qDebug() << "SubversionPlugin::findTopLevelForDirectory" << directory << rc;
    return rc;
}

QString SubversionPlugin::findTopLevelForDirectoryI(const QString &directory) const
{
    /* Recursing up, the top level is a child of the first directory that does
     * not have a  ".svn" directory. The starting directory must be a managed
     * one. Go up and try to find the first unmanaged parent dir. */
    QDir lastDirectory = QDir(directory);
    if (!lastDirectory.exists() || !managesDirectory(lastDirectory))
        return QString();
    for (QDir parentDir = lastDirectory; parentDir.cdUp() ; lastDirectory = parentDir) {
        if (!managesDirectory(parentDir))
            return QDir::toNativeSeparators(lastDirectory.absolutePath());
    }
    return QString();
}

1078 1079 1080 1081 1082
SubversionControl *SubversionPlugin::subVersionControl() const
{
    return static_cast<SubversionControl *>(versionControl());
}

con's avatar
con committed
1083
Q_EXPORT_PLUGIN(SubversionPlugin)