subversionplugin.cpp 41.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 8
**
** Contact:  Qt Software Information (qt-info@nokia.com)
**
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 26
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
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 38 39 40 41 42 43 44 45 46 47 48 49 50
#include "subversionplugin.h"

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

#include "subversionoutputwindow.h"
#include "subversionsubmiteditor.h"
#include "subversionconstants.h"
#include "subversioncontrol.h"

#include <vcsbase/basevcseditorfactory.h>
#include <vcsbase/vcsbaseeditor.h>
#include <vcsbase/basevcssubmiteditorfactory.h>
#include <utils/synchronousprocess.h>

#include <coreplugin/icore.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/filemanager.h>
#include <coreplugin/messagemanager.h>
#include <coreplugin/mimedatabase.h>
#include <coreplugin/uniqueidmanager.h>
51
#include <coreplugin/actionmanager/actionmanager.h>
con's avatar
con committed
52
#include <coreplugin/editormanager/editormanager.h>
53
#include <projectexplorer/projectexplorer.h>
hjk's avatar
hjk committed
54
#include <utils/qtcassert.h>
con's avatar
con committed
55 56

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

#include <limits.h>
con's avatar
con committed
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

using namespace Subversion::Internal;

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

// #pragma mark -- SubversionPlugin

const char * const SubversionPlugin::SUBVERSION_MENU    = "Subversion.Menu";
const char * const SubversionPlugin::ADD                = "Subversion.Add";
const char * const SubversionPlugin::DELETE_FILE        = "Subversion.Delete";
const char * const SubversionPlugin::REVERT             = "Subversion.Revert";
const char * const SubversionPlugin::SEPARATOR0         = "Subversion.Separator0";
const char * const SubversionPlugin::DIFF_PROJECT       = "Subversion.DiffAll";
const char * const SubversionPlugin::DIFF_CURRENT       = "Subversion.DiffCurrent";
const char * const SubversionPlugin::SEPARATOR1         = "Subversion.Separator1";
const char * const SubversionPlugin::COMMIT_ALL         = "Subversion.CommitAll";
const char * const SubversionPlugin::COMMIT_CURRENT     = "Subversion.CommitCurrent";
const char * const SubversionPlugin::SEPARATOR2         = "Subversion.Separator2";
const char * const SubversionPlugin::FILELOG_CURRENT    = "Subversion.FilelogCurrent";
const char * const SubversionPlugin::ANNOTATE_CURRENT   = "Subversion.AnnotateCurrent";
const char * const SubversionPlugin::SEPARATOR3         = "Subversion.Separator3";
const char * const SubversionPlugin::STATUS             = "Subversion.Status";
const char * const SubversionPlugin::UPDATE             = "Subversion.Update";
96
const char * const SubversionPlugin::DESCRIBE           = "Subversion.Describe";
con's avatar
con committed
97

98 99
static const char *nonInteractiveOptionC = "--non-interactive";

con's avatar
con committed
100 101 102
static const VCSBase::VCSBaseEditorParameters editorParameters[] = {
{
    VCSBase::RegularCommandOutput,
103 104
    "Subversion Command Log Editor", // kind
    "Subversion Command Log Editor", // context
con's avatar
con committed
105 106 107
    "application/vnd.nokia.text.scs_svn_commandlog",
    "scslog"},
{   VCSBase::LogOutput,
108 109
    "Subversion File Log Editor",   // kind
    "Subversion File Log Editor",   // context
con's avatar
con committed
110 111 112
    "application/vnd.nokia.text.scs_svn_filelog",
    "scsfilelog"},
{    VCSBase::AnnotateOutput,
113 114
    "Subversion Annotation Editor",  // kind
    "Subversion Annotation Editor",  // context
con's avatar
con committed
115 116 117
    "application/vnd.nokia.text.scs_svn_annotation",
    "scsannotate"},
{   VCSBase::DiffOutput,
118 119
    "Subversion Diff Editor",  // kind
    "Subversion Diff Editor",  // context
con's avatar
con committed
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
    "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
135
Core::IEditor* locateEditor(const char *property, const QString &entry)
con's avatar
con committed
136
{
137
    foreach (Core::IEditor *ed, Core::EditorManager::instance()->openedEditors())
con's avatar
con committed
138 139 140 141 142
        if (ed->property(property).toString() == entry)
            return ed;
    return 0;
}

143 144 145 146 147 148 149 150 151 152 153 154 155 156
// 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')) {
157 158
                const QString fileName = line.mid(7); // Column 8 starting from svn 1.6
                changeSet.push_back(SubversionSubmitEditor::StatusFilePair(QString(state), fileName.trimmed()));
159 160 161 162 163 164 165
            }

        }
    }
    return changeSet;
}

con's avatar
con committed
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
// ------------- SubversionPlugin
SubversionPlugin *SubversionPlugin::m_subversionPluginInstance = 0;

SubversionPlugin::SubversionPlugin() :
    m_svnDotDirectory(QLatin1String(".svn")),
    m_versionControl(0),
    m_coreListener(0),
    m_settingsPage(0),
    m_changeTmpFile(0),
    m_submitEditorFactory(0),
    m_subversionOutputWindow(0),
    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),
189
    m_describeAction(0),
con's avatar
con committed
190 191 192
    m_submitCurrentLogAction(0),
    m_submitDiffAction(0),
    m_submitUndoAction(0),
193 194
    m_submitRedoAction(0),
    m_submitActionTriggered(false)
con's avatar
con committed
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
{
}

SubversionPlugin::~SubversionPlugin()
{
    if (m_versionControl) {
        removeObject(m_versionControl);
        delete m_versionControl;
        m_versionControl = 0;
    }

    if (m_settingsPage) {
        removeObject(m_settingsPage);
        delete m_settingsPage;
        m_settingsPage = 0;
    }
    if (m_subversionOutputWindow) {
        removeObject(m_subversionOutputWindow);
        delete m_subversionOutputWindow;
        m_subversionOutputWindow = 0;
    }
    if (m_submitEditorFactory) {
        removeObject(m_submitEditorFactory);
        delete m_submitEditorFactory;
        m_submitEditorFactory = 0;
    }

    if (!m_editorFactories.empty()) {
hjk's avatar
hjk committed
223
        foreach (Core::IEditorFactory* pf, m_editorFactories)
con's avatar
con committed
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
            removeObject(pf);
        qDeleteAll(m_editorFactories);
        m_editorFactories.clear();
    }

    if (m_coreListener) {
        removeObject(m_coreListener);
        delete m_coreListener;
        m_coreListener = 0;
    }
    cleanChangeTmpFile();
}

void SubversionPlugin::cleanChangeTmpFile()
{
    if (m_changeTmpFile) {
        if (m_changeTmpFile->isOpen())
            m_changeTmpFile->close();
        delete m_changeTmpFile;
        m_changeTmpFile = 0;
    }
}

static const VCSBase::VCSBaseSubmitEditorParameters submitParameters = {
    Subversion::Constants::SUBVERSION_SUBMIT_MIMETYPE,
    Subversion::Constants::SUBVERSIONCOMMITEDITOR_KIND,
250
    Subversion::Constants::SUBVERSIONCOMMITEDITOR
con's avatar
con committed
251 252
};

253 254 255 256 257 258 259 260 261 262
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);
}

263
bool SubversionPlugin::initialize(const QStringList &arguments, QString *errorMessage)
con's avatar
con committed
264
{
265 266
    Q_UNUSED(arguments);

con's avatar
con committed
267 268 269 270 271 272 273 274
    typedef VCSBase::VCSSubmitEditorFactory<SubversionSubmitEditor> SubversionSubmitEditorFactory;
    typedef VCSBase::VCSEditorFactory<SubversionEditor> SubversionEditorFactory;
    using namespace Constants;

    using namespace Core::Constants;
    using namespace ExtensionSystem;

    m_subversionPluginInstance = this;
hjk's avatar
hjk committed
275
    Core::ICore *core = Core::ICore::instance();
con's avatar
con committed
276

hjk's avatar
hjk committed
277
    if (!core->mimeDatabase()->addMimeTypes(QLatin1String(":/trolltech.subversion/Subversion.mimetypes.xml"), errorMessage))
con's avatar
con committed
278 279 280 281 282
        return false;

    m_versionControl = new SubversionControl(this);
    addObject(m_versionControl);

hjk's avatar
hjk committed
283
    if (QSettings *settings = core->settings())
con's avatar
con committed
284 285 286 287 288 289 290 291 292 293 294 295 296 297
        m_settings.fromSettings(settings);

    m_coreListener = new CoreListener(this);
    addObject(m_coreListener);

    m_settingsPage = new SettingsPage;
    addObject(m_settingsPage);

    m_submitEditorFactory = new SubversionSubmitEditorFactory(&submitParameters);
    addObject(m_submitEditorFactory);

    static const char *describeSlot = SLOT(describe(QString,QString));
    const int editorCount = sizeof(editorParameters)/sizeof(VCSBase::VCSBaseEditorParameters);
    for (int i = 0; i < editorCount; i++) {
298 299
        m_editorFactories.push_back(
            new SubversionEditorFactory(editorParameters + i, this, describeSlot));
con's avatar
con committed
300 301 302 303 304 305 306
        addObject(m_editorFactories.back());
    }

    m_subversionOutputWindow = new SubversionOutputWindow(this);
    addObject(m_subversionOutputWindow);

    //register actions
hjk's avatar
hjk committed
307
    Core::ActionManager *ami = core->actionManager();
308
    Core::ActionContainer *toolsContainer = ami->actionContainer(M_TOOLS);
con's avatar
con committed
309

310
    Core::ActionContainer *subversionMenu =
con's avatar
con committed
311 312 313
        ami->createMenu(QLatin1String(SUBVERSION_MENU));
    subversionMenu->menu()->setTitle(tr("&Subversion"));
    toolsContainer->addMenu(subversionMenu);
314 315 316 317
    if (QAction *ma = subversionMenu->menu()->menuAction()) {
        ma->setEnabled(m_versionControl->isEnabled());
        connect(m_versionControl, SIGNAL(enabledChanged(bool)), ma, SLOT(setVisible(bool)));
    }
con's avatar
con committed
318 319

    QList<int> globalcontext;
hjk's avatar
hjk committed
320
    globalcontext << core->uniqueIDManager()->uniqueIdentifier(C_GLOBAL);
con's avatar
con committed
321

con's avatar
con committed
322
    Core::Command *command;
con's avatar
con committed
323 324 325
    m_addAction = new QAction(tr("Add"), this);
    command = ami->registerAction(m_addAction, SubversionPlugin::ADD,
        globalcontext);
con's avatar
con committed
326
    command->setAttribute(Core::Command::CA_UpdateText);
327
#ifndef Q_OS_MAC
con's avatar
con committed
328
    command->setDefaultKeySequence(QKeySequence(tr("Alt+S,Alt+A")));
329
#endif
con's avatar
con committed
330 331 332 333 334 335
    connect(m_addAction, SIGNAL(triggered()), this, SLOT(addCurrentFile()));
    subversionMenu->addAction(command);

    m_deleteAction = new QAction(tr("Delete"), this);
    command = ami->registerAction(m_deleteAction, SubversionPlugin::DELETE_FILE,
        globalcontext);
con's avatar
con committed
336
    command->setAttribute(Core::Command::CA_UpdateText);
con's avatar
con committed
337 338 339 340 341 342
    connect(m_deleteAction, SIGNAL(triggered()), this, SLOT(deleteCurrentFile()));
    subversionMenu->addAction(command);

    m_revertAction = new QAction(tr("Revert"), this);
    command = ami->registerAction(m_revertAction, SubversionPlugin::REVERT,
        globalcontext);
con's avatar
con committed
343
    command->setAttribute(Core::Command::CA_UpdateText);
con's avatar
con committed
344 345 346
    connect(m_revertAction, SIGNAL(triggered()), this, SLOT(revertCurrentFile()));
    subversionMenu->addAction(command);

347
    subversionMenu->addAction(createSeparator(this, ami, SubversionPlugin::SEPARATOR0, globalcontext));
con's avatar
con committed
348 349 350 351 352 353 354 355 356 357

    m_diffProjectAction = new QAction(tr("Diff Project"), this);
    command = ami->registerAction(m_diffProjectAction, SubversionPlugin::DIFF_PROJECT,
        globalcontext);
    connect(m_diffProjectAction, SIGNAL(triggered()), this, SLOT(diffProject()));
    subversionMenu->addAction(command);

    m_diffCurrentAction = new QAction(tr("Diff Current File"), this);
    command = ami->registerAction(m_diffCurrentAction,
        SubversionPlugin::DIFF_CURRENT, globalcontext);
con's avatar
con committed
358
    command->setAttribute(Core::Command::CA_UpdateText);
359
#ifndef Q_OS_MAC
con's avatar
con committed
360
    command->setDefaultKeySequence(QKeySequence(tr("Alt+S,Alt+D")));
361
#endif
con's avatar
con committed
362 363 364
    connect(m_diffCurrentAction, SIGNAL(triggered()), this, SLOT(diffCurrentFile()));
    subversionMenu->addAction(command);

365
    subversionMenu->addAction(createSeparator(this, ami, SubversionPlugin::SEPARATOR1, globalcontext));
con's avatar
con committed
366 367 368 369 370 371 372 373 374 375

    m_commitAllAction = new QAction(tr("Commit All Files"), this);
    command = ami->registerAction(m_commitAllAction, SubversionPlugin::COMMIT_ALL,
        globalcontext);
    connect(m_commitAllAction, SIGNAL(triggered()), this, SLOT(startCommitAll()));
    subversionMenu->addAction(command);

    m_commitCurrentAction = new QAction(tr("Commit Current File"), this);
    command = ami->registerAction(m_commitCurrentAction,
        SubversionPlugin::COMMIT_CURRENT, globalcontext);
con's avatar
con committed
376
    command->setAttribute(Core::Command::CA_UpdateText);
377
#ifndef Q_OS_MAC
con's avatar
con committed
378
    command->setDefaultKeySequence(QKeySequence(tr("Alt+S,Alt+C")));
379
#endif
con's avatar
con committed
380 381 382
    connect(m_commitCurrentAction, SIGNAL(triggered()), this, SLOT(startCommitCurrentFile()));
    subversionMenu->addAction(command);

383
    subversionMenu->addAction(createSeparator(this, ami, SubversionPlugin::SEPARATOR2, globalcontext));
con's avatar
con committed
384 385 386 387

    m_filelogCurrentAction = new QAction(tr("Filelog Current File"), this);
    command = ami->registerAction(m_filelogCurrentAction,
        SubversionPlugin::FILELOG_CURRENT, globalcontext);
con's avatar
con committed
388
    command->setAttribute(Core::Command::CA_UpdateText);
con's avatar
con committed
389 390 391 392 393 394 395
    connect(m_filelogCurrentAction, SIGNAL(triggered()), this,
        SLOT(filelogCurrentFile()));
    subversionMenu->addAction(command);

    m_annotateCurrentAction = new QAction(tr("Annotate Current File"), this);
    command = ami->registerAction(m_annotateCurrentAction,
        SubversionPlugin::ANNOTATE_CURRENT, globalcontext);
con's avatar
con committed
396
    command->setAttribute(Core::Command::CA_UpdateText);
con's avatar
con committed
397 398 399 400
    connect(m_annotateCurrentAction, SIGNAL(triggered()), this,
        SLOT(annotateCurrentFile()));
    subversionMenu->addAction(command);

401 402 403 404 405 406
    m_describeAction = new QAction(tr("Describe..."), this);
    command = ami->registerAction(m_describeAction, SubversionPlugin::DESCRIBE, globalcontext);
    connect(m_describeAction, SIGNAL(triggered()), this, SLOT(slotDescribe()));
    subversionMenu->addAction(command);

    subversionMenu->addAction(createSeparator(this, ami, SubversionPlugin::SEPARATOR3, globalcontext));
con's avatar
con committed
407 408 409 410 411 412 413 414 415 416 417 418 419 420

    m_statusAction = new QAction(tr("Project Status"), this);
    command = ami->registerAction(m_statusAction, SubversionPlugin::STATUS,
        globalcontext);
    connect(m_statusAction, SIGNAL(triggered()), this, SLOT(projectStatus()));
    subversionMenu->addAction(command);

    m_updateProjectAction = new QAction(tr("Update Project"), this);
    command = ami->registerAction(m_updateProjectAction, SubversionPlugin::UPDATE, globalcontext);
    connect(m_updateProjectAction, SIGNAL(triggered()), this, SLOT(updateProject()));
    subversionMenu->addAction(command);

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

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

427
    m_submitDiffAction = new QAction(VCSBase::VCSBaseSubmitEditor::diffIcon(), tr("Diff Selected Files"), this);
con's avatar
con committed
428 429 430 431 432 433 434 435
    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);

hjk's avatar
hjk committed
436
    connect(Core::ICore::instance(), SIGNAL(contextChanged(Core::IContext *)), this, SLOT(updateActions()));
con's avatar
con committed
437 438 439 440 441 442

    return true;
}

void SubversionPlugin::extensionsInitialized()
{
443
    m_projectExplorer = ProjectExplorer::ProjectExplorerPlugin::instance();
con's avatar
con committed
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
    if (m_projectExplorer) {
        connect(m_projectExplorer,
            SIGNAL(currentProjectChanged(ProjectExplorer::Project*)),
            m_subversionPluginInstance, SLOT(updateActions()));
    }
    updateActions();
}

bool SubversionPlugin::editorAboutToClose(Core::IEditor *iEditor)
{
    if (!m_changeTmpFile || !iEditor || qstrcmp(Constants::SUBVERSIONCOMMITEDITOR, iEditor->kind()))
        return true;

    Core::IFile *fileIFace = iEditor->file();
    const SubversionSubmitEditor *editor = qobject_cast<SubversionSubmitEditor *>(iEditor);
    if (!fileIFace || !editor)
        return true;

    // Submit editor closing. Make it write out the commit message
    // and retrieve files
    const QFileInfo editorFile(fileIFace->fileName());
    const QFileInfo changeFile(m_changeTmpFile->fileName());
    if (editorFile.absoluteFilePath() != changeFile.absoluteFilePath())
        return true; // Oops?!

469 470
    // Prompt user. Force a prompt unless submit was actually invoked (that
    // is, the editor was closed or shutdown).
471 472 473
    const VCSBase::VCSBaseSubmitEditor::PromptSubmitResult answer =
            editor->promptSubmit(tr("Closing Subversion Editor"),
                                 tr("Do you want to commit the change?"),
474 475 476
                                 tr("The commit message check failed. Do you want to commit the change?"),
                                 !m_submitActionTriggered);
    m_submitActionTriggered = false;
con's avatar
con committed
477
    switch (answer) {
478
    case VCSBase::VCSBaseSubmitEditor::SubmitCanceled:
con's avatar
con committed
479
        return false; // Keep editing and change file
480
    case VCSBase::VCSBaseSubmitEditor::SubmitDiscarded:
con's avatar
con committed
481 482 483 484 485 486 487
        cleanChangeTmpFile();
        return true; // Cancel all
    default:
        break;
    }

    const QStringList fileList = editor->checkedFiles();
488
    bool closeEditor = true;
con's avatar
con committed
489 490
    if (!fileList.empty()) {
        // get message & commit
hjk's avatar
hjk committed
491
        Core::ICore::instance()->fileManager()->blockFileChange(fileIFace);
con's avatar
con committed
492
        fileIFace->save();
hjk's avatar
hjk committed
493
        Core::ICore::instance()->fileManager()->unblockFileChange(fileIFace);
494
        closeEditor= commit(m_changeTmpFile->fileName(), fileList);
con's avatar
con committed
495
    }
496 497 498
    if (closeEditor)
        cleanChangeTmpFile();
    return closeEditor;
con's avatar
con committed
499 500 501 502 503 504 505 506 507 508 509 510
}

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();
511
    QTextCodec *codec = source.isEmpty() ? static_cast<QTextCodec *>(0) : VCSBase::VCSBaseEditor::getCodec(source);
con's avatar
con committed
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526

    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
527
        if (Core::IEditor *editor = locateEditor("originalFileName", files.front())) {
con's avatar
con committed
528
            editor->createNew(response.stdOut);
529
            Core::EditorManager::instance()->activateEditor(editor);
con's avatar
con committed
530 531 532
            return;
        }
    }
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
533
    const QString title = QString::fromLatin1("svn diff %1").arg(diffname);
con's avatar
con committed
534 535 536 537 538 539 540
    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)
{
541
    Core::IEditor *editor = Core::EditorManager::instance()->openEditor(fileName, QLatin1String(Constants::SUBVERSIONCOMMITEDITOR_KIND));
con's avatar
con committed
542
    SubversionSubmitEditor *submitEditor = qobject_cast<SubversionSubmitEditor*>(editor);
hjk's avatar
hjk committed
543
    QTC_ASSERT(submitEditor, /**/);
544
    submitEditor->registerActions(m_submitUndoAction, m_submitRedoAction, m_submitCurrentLogAction, m_submitDiffAction);
con's avatar
con committed
545 546 547 548 549 550 551
    connect(submitEditor, SIGNAL(diffSelectedFiles(QStringList)), this, SLOT(diffFiles(QStringList)));

    return submitEditor;
}

void SubversionPlugin::updateActions()
{
552
    const QString fileName = currentFileName();
con's avatar
con committed
553 554 555 556 557 558 559 560 561 562 563 564
    const bool hasFile = !fileName.isEmpty();

    m_addAction->setEnabled(hasFile);
    m_deleteAction->setEnabled(hasFile);
    m_revertAction->setEnabled(hasFile);
    m_diffProjectAction->setEnabled(true);
    m_diffCurrentAction->setEnabled(hasFile);
    m_commitAllAction->setEnabled(true);
    m_commitCurrentAction->setEnabled(hasFile);
    m_filelogCurrentAction->setEnabled(hasFile);
    m_annotateCurrentAction->setEnabled(hasFile);
    m_statusAction->setEnabled(true);
565
    m_describeAction->setEnabled(true);
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

    QString baseName;
    if (hasFile)
        baseName = QFileInfo(fileName).fileName();

    m_addAction->setText(tr("Add %1").arg(baseName));
    m_deleteAction->setText(tr("Delete %1").arg(baseName));
    m_revertAction->setText(tr("Revert %1").arg(baseName));
    m_diffCurrentAction->setText(tr("Diff %1").arg(baseName));
    m_commitCurrentAction->setText(tr("Commit %1").arg(baseName));
    m_filelogCurrentAction->setText(tr("Filelog %1").arg(baseName));
    m_annotateCurrentAction->setText(tr("Annotate %1").arg(baseName));
}

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
609
    if (QMessageBox::warning(0, QLatin1String("svn revert"), tr("The file has been changed. Do you want to revert it?"),
con's avatar
con committed
610 611 612
                             QMessageBox::Yes, QMessageBox::No) == QMessageBox::No)
        return;

hjk's avatar
hjk committed
613
    Core::FileManager *fm = Core::ICore::instance()->fileManager();
con's avatar
con committed
614
    QList<Core::IFile *> files = fm->managedFiles(file);
hjk's avatar
hjk committed
615
    foreach (Core::IFile *file, files)
con's avatar
con committed
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
        fm->blockFileChange(file);

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

    const SubversionResponse revertResponse = runSvn(args, subversionShortTimeOut, true);
    if (revertResponse.error) {
        foreach (Core::IFile *file, files)
            fm->unblockFileChange(file);
        return;
    }

    Core::IFile::ReloadBehavior tempBehavior = Core::IFile::ReloadAll;
    foreach (Core::IFile *file, files) {
        file->modified(&tempBehavior);
        fm->unblockFileChange(file);
    }
}

// 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: {
        const QString msg = tr("The commit list spans several respositories (%1). Please commit them one by one.").
            arg(files.join(QString(QLatin1Char(' '))));
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
701
        QMessageBox::warning(0, QLatin1String("svn commit"), msg, QMessageBox::Ok);
con's avatar
con committed
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
    }
        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;

    if (m_changeTmpFile) {
        showOutput(tr("Another commit is currently being executed."));
        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
729
    const StatusList statusOutput = parseStatusOutput(response.stdOut);
con's avatar
con committed
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
    if (statusOutput.empty()) {
        showOutput(tr("There are no modified files."), true);
        return;
    }

    // Create a new submit change file containing the submit template
    QTemporaryFile *changeTmpFile = new QTemporaryFile(this);
    changeTmpFile->setAutoRemove(true);
    if (!changeTmpFile->open()) {
        showOutput(tr("Cannot create temporary file: %1").arg(changeTmpFile->errorString()));
        delete changeTmpFile;
        return;
    }
    m_changeTmpFile = changeTmpFile;
    // TODO: Retrieve submit template from
    const QString submitTemplate;
    // Create a submit
    m_changeTmpFile->write(submitTemplate.toUtf8());
    m_changeTmpFile->flush();
    m_changeTmpFile->seek(0);
    // Create a submit editor and set file list
    SubversionSubmitEditor *editor = openSubversionSubmitEditor(m_changeTmpFile->fileName());
752
    editor->setStatusList(statusOutput);
con's avatar
con committed
753 754 755 756 757 758 759 760 761 762 763
}

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"));
764
    args << QLatin1String(nonInteractiveOptionC) << QLatin1String("--file") << messageFile;
con's avatar
con committed
765 766 767 768 769 770 771 772 773 774 775 776 777 778
    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)
{
779
    QTextCodec *codec = VCSBase::VCSBaseEditor::getCodec(file);
con's avatar
con committed
780 781 782 783 784 785 786 787 788 789 790
    // 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
791
    if (Core::IEditor *editor = locateEditor("logFileName", file)) {
con's avatar
con committed
792
        editor->createNew(response.stdOut);
793
        Core::EditorManager::instance()->activateEditor(editor);
con's avatar
con committed
794
    } else {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
795
        const QString title = QString::fromLatin1("svn log %1").arg(QFileInfo(file).fileName());
con's avatar
con committed
796 797 798 799 800 801 802 803 804 805 806 807
        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"));
808
    args.push_back(QLatin1String(nonInteractiveOptionC));
con's avatar
con committed
809 810 811 812 813 814 815 816 817 818 819 820 821
    args.append(topLevels);
    runSvn(args, subversionLongTimeOut, false);
}

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

void SubversionPlugin::annotate(const QString &file)
{
822
    QTextCodec *codec = VCSBase::VCSBaseEditor::getCodec(file);
con's avatar
con committed
823 824 825 826 827 828 829 830 831 832 833 834

    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

hjk's avatar
hjk committed
835
    if (Core::IEditor *editor = locateEditor("annotateFileName", file)) {
con's avatar
con committed
836
        editor->createNew(response.stdOut);
837
        Core::EditorManager::instance()->activateEditor(editor);
con's avatar
con committed
838
    } else {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
839
        const QString title = QString::fromLatin1("svn annotate %1").arg(QFileInfo(file).fileName());
con's avatar
con committed
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
        Core::IEditor *newEditor = showOutputInEditor(title, response.stdOut, VCSBase::AnnotateOutput, file, codec);
        newEditor->setProperty("annotateFileName", file);
    }
}

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;
874 875 876 877 878 879 880 881 882 883 884 885 886 887
    // 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
888 889 890 891 892 893
    args.push_back(QLatin1String("-r"));
    QString diffArg;
    QTextStream(&diffArg) << (number - 1) << ':' << number;
    args.push_back(diffArg);
    args.push_back(topLevel);

894
    QTextCodec *codec = VCSBase::VCSBaseEditor::getCodec(source);
con's avatar
con committed
895 896 897
    const SubversionResponse response = runSvn(args, subversionShortTimeOut, false, codec);
    if (response.error)
        return;
898
    description += response.stdOut;
con's avatar
con committed
899 900 901 902

    // 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
903
    if (Core::IEditor *editor = locateEditor("describeChange", id)) {
904
        editor->createNew(description);
hjk's avatar
hjk committed
905
        Core::EditorManager::instance()->activateEditor(editor);
con's avatar
con committed
906
    } else {
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
907
        const QString title = QString::fromLatin1("svn describe %1#%2").arg(QFileInfo(source).fileName(), changeNr);
908
        Core::IEditor *newEditor = showOutputInEditor(title, description, VCSBase::DiffOutput, source, codec);
con's avatar
con committed
909 910 911 912
        newEditor->setProperty("describeChange", id);
    }
}

913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931
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
932 933
void SubversionPlugin::submitCurrentLog()
{
934
    m_submitActionTriggered = true;
935 936
    Core::EditorManager::instance()->closeEditors(QList<Core::IEditor*>()
        << Core::EditorManager::instance()->currentEditor());
con's avatar
con committed
937 938 939 940
}

QString SubversionPlugin::currentFileName() const
{
hjk's avatar
hjk committed
941
    const QString fileName = Core::ICore::instance()->fileManager()->currentFile();
con's avatar
con committed
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
    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);

    // Hide passwords, etc in the log window
    const QString timeStamp = QTime::currentTime().toString(QLatin1String("HH:mm"));
978
    //: <timestamp> Executing: <executable> <arguments>
con's avatar
con committed
979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
    const QString outputText = tr("%1 Executing: %2 %3\n").arg(timeStamp, executable, SubversionSettings::formatArguments(allArgs));
    showOutput(outputText, false);

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

    // Run, connect stderr to the output window
    Core::Utils::SynchronousProcess process;
    process.setTimeout(timeOut);
    process.setStdOutCodec(outputCodec);

    process.setStdErrBufferedSignalsEnabled(true);
    connect(&process, SIGNAL(stdErrBuffered(QString,bool)), m_subversionOutputWindow, SLOT(append(QString,bool)));

    // connect stdout to the output window if desired
    if (showStdOutInOutputWindow) {
        process.setStdOutBufferedSignalsEnabled(true);
        connect(&process, SIGNAL(stdOutBuffered(QString,bool)), m_subversionOutputWindow, SLOT(append(QString,bool)));
    }

    const Core::Utils::SynchronousProcessResponse sp_resp = process.run(executable, allArgs);
    response.error = true;
    response.stdErr = sp_resp.stdErr;
    response.stdOut = sp_resp.stdOut;
    switch (sp_resp.result) {
    case Core::Utils::SynchronousProcessResponse::Finished:
        response.error = false;
        break;
    case Core::Utils::SynchronousProcessResponse::FinishedError:
        response.message = tr("The process terminated with exit code %1.").arg(sp_resp.exitCode);
        break;
    case Core::Utils::SynchronousProcessResponse::TerminatedAbnormally:
        response.message = tr("The process terminated abnormally.");
        break;
    case Core::Utils::SynchronousProcessResponse::StartFailed:
        response.message = tr("Could not start subversion '%1'. Please check your settings in the preferences.").arg(executable);
        break;
    case Core::Utils::SynchronousProcessResponse::Hang:
        response.message = tr("Subversion did not respond within timeout limit (%1 ms).").arg(timeOut);
        break;
    }
    if (response.error)
        m_subversionOutputWindow->append(response.message, true);

    return response;
}

void SubversionPlugin::showOutput(const QString &output, bool bringToForeground)
{
    m_subversionOutputWindow->append(output);
    if (bringToForeground)
        m_subversionOutputWindow->popup();
}

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
1038
    QTC_ASSERT(params, return 0);
con's avatar
con committed
1039 1040 1041 1042
    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;
1043 1044
    Core::IEditor *editor = Core::EditorManager::instance()->newFile(kind, &s, output.toLocal8Bit());
    SubversionEditor *e = qobject_cast<SubversionEditor*>(editor->widget());
con's avatar
con committed
1045 1046 1047 1048 1049 1050 1051 1052
    if (!e)
        return 0;
    s.replace(QLatin1Char(' '), QLatin1Char('_'));
    e->setSuggestedFileName(s);
    if (!source.isEmpty())
        e->setSource(source);
    if (codec)
        e->setCodec(codec);
1053 1054 1055
    Core::IEditor *ie = e->editableInterface();
    Core::EditorManager::instance()->activateEditor(ie);
    return ie;
con's avatar
con committed
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
}

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
1067
        if (QSettings *settings = Core::ICore::instance()->settings())
con's avatar
con committed
1068 1069 1070 1071 1072 1073
            m_settings.toSettings(settings);
    }
}

SubversionPlugin *SubversionPlugin::subversionPluginInstance()
{
hjk's avatar
hjk committed
1074
    QTC_ASSERT(m_subversionPluginInstance, return m_subversionPluginInstance);
con's avatar
con committed
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
    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
{
    const QString svnDir = directory.absoluteFilePath(m_svnDotDirectory);
    return QFileInfo(svnDir).isDir();
}

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

Q_EXPORT_PLUGIN(SubversionPlugin)