clearcaseplugin.cpp 95.5 KB
Newer Older
Orgad Shaneh's avatar
Orgad Shaneh committed
1 2
/**************************************************************************
**
3
** Copyright (c) 2014 AudioCodes Ltd.
Orgad Shaneh's avatar
Orgad Shaneh committed
4
** Author: Orgad Shaneh <orgad.shaneh@audiocodes.com>
hjk's avatar
hjk committed
5
** Contact: http://www.qt-project.org/legal
Orgad Shaneh's avatar
Orgad Shaneh committed
6
**
hjk's avatar
hjk committed
7
** This file is part of Qt Creator.
Orgad Shaneh's avatar
Orgad Shaneh committed
8
**
hjk's avatar
hjk committed
9 10 11 12 13 14 15
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
Orgad Shaneh's avatar
Orgad Shaneh committed
16 17
**
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
18 19 20 21 22 23 24 25 26
** 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.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
Orgad Shaneh's avatar
Orgad Shaneh committed
27 28
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
29
****************************************************************************/
Orgad Shaneh's avatar
Orgad Shaneh committed
30

31
#include "clearcaseplugin.h"
Orgad Shaneh's avatar
Orgad Shaneh committed
32 33 34 35 36 37 38
#include "activityselector.h"
#include "checkoutdialog.h"
#include "clearcaseconstants.h"
#include "clearcasecontrol.h"
#include "clearcaseeditor.h"
#include "clearcasesubmiteditor.h"
#include "clearcasesubmiteditorwidget.h"
39
#include "clearcasesync.h"
Orgad Shaneh's avatar
Orgad Shaneh committed
40 41 42 43 44 45 46 47 48 49 50
#include "settingspage.h"
#include "versionselector.h"
#include "ui_undocheckout.h"

#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/command.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/documentmanager.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/icore.h>
51
#include <coreplugin/infobar.h>
Orgad Shaneh's avatar
Orgad Shaneh committed
52 53 54
#include <coreplugin/messagemanager.h>
#include <coreplugin/mimedatabase.h>
#include <coreplugin/progressmanager/progressmanager.h>
55
#include <coreplugin/locator/commandlocator.h>
Orgad Shaneh's avatar
Orgad Shaneh committed
56 57 58 59 60 61
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/project.h>
#include <projectexplorer/iprojectmanager.h>
#include <utils/synchronousprocess.h>
#include <utils/parameteraction.h>
#include <utils/fileutils.h>
62
#include <utils/hostosinfo.h>
Orgad Shaneh's avatar
Orgad Shaneh committed
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
#include <utils/qtcassert.h>
#include <utils/runextensions.h>
#include <vcsbase/basevcseditorfactory.h>
#include <vcsbase/basevcssubmiteditorfactory.h>
#include <vcsbase/vcsbaseeditor.h>
#include <vcsbase/vcsbaseeditorparameterwidget.h>
#include <vcsbase/vcsbaseoutputwindow.h>
#include <vcsbase/vcsbasesubmiteditor.h>


#include <QAction>
#include <QDebug>
#include <QDialog>
#include <QDialogButtonBox>
#include <QDir>
#include <QFileInfo>
#include <QFuture>
#include <QFutureInterface>
#include <QInputDialog>
#include <QList>
#include <QMainWindow>
#include <QMenu>
#include <QMessageBox>
Orgad Shaneh's avatar
Orgad Shaneh committed
86
#include <QMetaObject>
Orgad Shaneh's avatar
Orgad Shaneh committed
87 88
#include <QMutex>
#include <QProcess>
89
#include <QRegExp>
Orgad Shaneh's avatar
Orgad Shaneh committed
90
#include <QSharedPointer>
91 92 93 94
#include <QtConcurrentRun>
#include <QTemporaryFile>
#include <QTextCodec>
#include <QtPlugin>
Orgad Shaneh's avatar
Orgad Shaneh committed
95 96 97 98 99
#include <QUrl>
#include <QUuid>
#include <QVariant>
#include <QVBoxLayout>
#include <QXmlStreamReader>
100 101 102
#ifdef WITH_TESTS
#include <QTest>
#endif
Orgad Shaneh's avatar
Orgad Shaneh committed
103

104 105 106
using namespace Core;
using namespace ProjectExplorer;

Orgad Shaneh's avatar
Orgad Shaneh committed
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
namespace ClearCase {
namespace Internal {

static const char CMD_ID_CLEARCASE_MENU[]     = "ClearCase.Menu";
static const char CMD_ID_CHECKOUT[]           = "ClearCase.CheckOut";
static const char CMD_ID_CHECKIN[]            = "ClearCase.CheckInCurrent";
static const char CMD_ID_UNDOCHECKOUT[]       = "ClearCase.UndoCheckOut";
static const char CMD_ID_UNDOHIJACK[]         = "ClearCase.UndoHijack";
static const char CMD_ID_DIFF_CURRENT[]       = "ClearCase.DiffCurrent";
static const char CMD_ID_HISTORY_CURRENT[]    = "ClearCase.HistoryCurrent";
static const char CMD_ID_ANNOTATE[]           = "ClearCase.Annotate";
static const char CMD_ID_ADD_FILE[]           = "ClearCase.AddFile";
static const char CMD_ID_DIFF_ACTIVITY[]      = "ClearCase.DiffActivity";
static const char CMD_ID_CHECKIN_ACTIVITY[]   = "ClearCase.CheckInActivity";
static const char CMD_ID_UPDATEINDEX[]        = "ClearCase.UpdateIndex";
static const char CMD_ID_UPDATE_VIEW[]        = "ClearCase.UpdateView";
static const char CMD_ID_CHECKIN_ALL[]        = "ClearCase.CheckInAll";
static const char CMD_ID_STATUS[]             = "ClearCase.Status";

static const VcsBase::VcsBaseEditorParameters editorParameters[] = {
{
Orgad Shaneh's avatar
Orgad Shaneh committed
128
    VcsBase::LogOutput,
Orgad Shaneh's avatar
Orgad Shaneh committed
129 130 131
    "ClearCase File Log Editor",   // id
    QT_TRANSLATE_NOOP("VCS", "ClearCase File Log Editor"),   // display_name
    "ClearCase File Log Editor",   // context
Orgad Shaneh's avatar
Orgad Shaneh committed
132
    "text/vnd.qtcreator.clearcase.log"},
Orgad Shaneh's avatar
Orgad Shaneh committed
133 134 135 136
{    VcsBase::AnnotateOutput,
    "ClearCase Annotation Editor",  // id
    QT_TRANSLATE_NOOP("VCS", "ClearCase Annotation Editor"),   // display_name
    "ClearCase Annotation Editor",  // context
Orgad Shaneh's avatar
Orgad Shaneh committed
137
    "text/vnd.qtcreator.clearcase.annotation"},
Orgad Shaneh's avatar
Orgad Shaneh committed
138 139 140 141
{   VcsBase::DiffOutput,
    "ClearCase Diff Editor",  // id
    QT_TRANSLATE_NOOP("VCS", "ClearCase Diff Editor"),   // display_name
    "ClearCase Diff Editor",  // context
142
    "text/x-patch"}
Orgad Shaneh's avatar
Orgad Shaneh committed
143 144 145 146 147 148 149 150 151 152 153
};

// 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::VcsBaseEditorWidget::findType(editorParameters, sizeof(editorParameters)/sizeof(VcsBase::VcsBaseEditorParameters), et);
}

static inline QString debugCodec(const QTextCodec *c)
{
154
    return c ? QString::fromLatin1(c->name()) : QString::fromLatin1("Null codec");
Orgad Shaneh's avatar
Orgad Shaneh committed
155 156 157 158 159
}

// ------------- ClearCasePlugin
ClearCasePlugin *ClearCasePlugin::m_clearcasePluginInstance = 0;

160 161 162 163 164 165
ViewData::ViewData() :
    isDynamic(false),
    isUcm(false)
{
}

Orgad Shaneh's avatar
Orgad Shaneh committed
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
ClearCasePlugin::ClearCasePlugin() :
    m_commandLocator(0),
    m_checkOutAction(0),
    m_checkInCurrentAction(0),
    m_undoCheckOutAction(0),
    m_undoHijackAction(0),
    m_diffCurrentAction(0),
    m_historyCurrentAction(0),
    m_annotateCurrentAction(0),
    m_addFileAction(0),
    m_diffActivityAction(0),
    m_updateIndexAction(0),
    m_updateViewAction(0),
    m_checkInActivityAction(0),
    m_checkInAllAction(0),
    m_statusAction(0),
    m_checkInSelectedAction(0),
    m_checkInDiffAction(0),
    m_submitUndoAction(0),
    m_submitRedoAction(0),
    m_menuAction(0),
187
    m_submitActionTriggered(false),
188 189
    m_activityMutex(new QMutex),
    m_statusMap(new StatusMap)
190 191 192
  #ifdef WITH_TESTS
   ,m_fakeClearTool(false)
  #endif
Orgad Shaneh's avatar
Orgad Shaneh committed
193
{
194
    qRegisterMetaType<ClearCase::Internal::FileStatus::Status>("ClearCase::Internal::FileStatus::Status");
Orgad Shaneh's avatar
Orgad Shaneh committed
195 196 197 198 199 200
}

ClearCasePlugin::~ClearCasePlugin()
{
    cleanCheckInMessageFile();
    // wait for sync thread to finish reading activities
201 202 203
    m_activityMutex->lock();
    m_activityMutex->unlock();
    delete m_activityMutex;
Orgad Shaneh's avatar
Orgad Shaneh committed
204 205 206 207 208 209 210
}

void ClearCasePlugin::cleanCheckInMessageFile()
{
    if (!m_checkInMessageFileName.isEmpty()) {
        QFile::remove(m_checkInMessageFileName);
        m_checkInMessageFileName.clear();
211
        m_checkInView.clear();
Orgad Shaneh's avatar
Orgad Shaneh committed
212 213 214 215 216 217 218 219
    }
}

bool ClearCasePlugin::isCheckInEditorOpen() const
{
    return !m_checkInMessageFileName.isEmpty();
}

220 221
/// Files in this directories are under ClearCase control
QStringList ClearCasePlugin::getVobList() const
222
{
223 224 225 226 227 228 229 230 231 232 233 234 235 236
    QStringList args(QLatin1String("lsvob"));
    args << QLatin1String("-s");
    const ClearCaseResponse response =
            runCleartool(currentState().topLevel(), args, m_settings.timeOutMS(), SilentRun);

    return response.stdOut.split(QLatin1Char('\n'), QString::SkipEmptyParts);
}

/// Get the drive letter of a path
/// Necessary since QDir(directory).rootPath() returns C:/ in all cases
QString ClearCasePlugin::getDriveLetterOfPath(const QString &directory)
{
    // cdUp until we get just the drive letter
    QDir dir(directory);
Orgad Shaneh's avatar
Orgad Shaneh committed
237
    while (!dir.isRoot() && dir.cdUp())
238 239 240 241 242
    { }

    return dir.path();
}

243 244 245 246 247
void ClearCasePlugin::updateStatusForFile(const QString &absFile)
{
    setStatus(absFile, getFileStatus(absFile), false);
}

248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
/// Give warning if a derived object is edited
void ClearCasePlugin::updateEditDerivedObjectWarning(const QString &fileName,
                                                     const FileStatus::Status status)
{
    if (!isDynamic())
        return;

    Core::IDocument *curDocument = Core::EditorManager::currentDocument();
    if (!curDocument)
        return;

    Core::InfoBar *infoBar = curDocument->infoBar();
    const Core::Id derivedObjectWarning("ClearCase.DerivedObjectWarning");

    if (status == FileStatus::Derived) {
        if (!infoBar->canInfoBeAdded(derivedObjectWarning))
            return;

        infoBar->addInfo(Core::InfoBarEntry(derivedObjectWarning,
                                            tr("Editing Derived Object: %1")
                                            .arg(fileName)));
    } else {
        infoBar->removeInfo(derivedObjectWarning);
    }
}

274 275 276 277 278 279 280 281 282 283 284 285
FileStatus::Status ClearCasePlugin::getFileStatus(const QString &fileName) const
{
    QTC_CHECK(!fileName.isEmpty());

    const QDir viewRootDir = QFileInfo(fileName).dir();
    const QString viewRoot = viewRootDir.path();

    QStringList args(QLatin1String("ls"));
    args << fileName;
    QString buffer = runCleartoolSync(viewRoot, args);

    const int atatpos = buffer.indexOf(QLatin1String("@@"));
286
    if (atatpos != -1) { // probably a managed file
287 288 289 290 291 292
        const QString absFile =
                viewRootDir.absoluteFilePath(
                    QDir::fromNativeSeparators(buffer.left(atatpos)));
        QTC_CHECK(QFile(absFile).exists());
        QTC_CHECK(!absFile.isEmpty());

293 294 295 296 297 298 299 300 301
        // "cleartool ls" of a derived object looks like this:
        // /path/to/file/export/MyFile.h@@--11-13T19:52.266580
        const QChar c = buffer.at(atatpos + 2);
        const bool isDerivedObject = c != QLatin1Char('/') && c != QLatin1Char('\\');
        if (isDerivedObject)
            return FileStatus::Derived;

        // find first whitespace. anything before that is not interesting
        const int wspos = buffer.indexOf(QRegExp(QLatin1String("\\s")));
302 303 304 305 306 307 308 309 310 311 312
        if (buffer.lastIndexOf(QLatin1String("CHECKEDOUT"), wspos) != -1)
            return FileStatus::CheckedOut;
        else
            return FileStatus::CheckedIn;
    } else {
        QTC_CHECK(QFile(fileName).exists());
        QTC_CHECK(!fileName.isEmpty());
        return FileStatus::NotManaged;
    }
}

313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
///
/// Check if the directory is managed by ClearCase.
///
/// There are 6 cases to consider for accessing ClearCase views:
///
/// 1) Windows: dynamic view under M:\<view_tag> (working dir view)
/// 2) Windows: dynamic view under Z:\ (similar to unix "set view" by using "subst" or "net use")
/// 3) Windows: snapshot view
/// 4) Unix: dynamic view under /view/<view_tag> (working dir view)
/// 5) Unix: dynamic view which are set view (transparent access in a shell process)
/// 6) Unix: snapshot view
///
/// Note: the drive letters M: and Z: can be chosen by the user. /view is the "view-root"
///       directory and is not configurable, while VOB names and mount points are configurable
///       by the ClearCase admin.
///
/// Note: All cases except #5 have a root directory, i.e., all files reside under a directory.
///       For #5 files are "mounted" and access is transparent (e.g., under /vobs).
///
/// For a view named "myview" and a VOB named "vobA" topLevels would be:
/// 1) M:/myview/vobA
/// 2) Z:/vobA
/// 3) c:/snapshots/myview/vobA
/// 4) /view/myview/vobs/vobA
/// 5) /vobs/vobA/
/// 6) /home/<username>/snapshots/myview/vobs/vobA
///
/// Note: The VOB directory is used as toplevel although the directory one up could have been
///       used on cases execpt 5. For case 5 it would have been /, which we don't want.
///
/// "cleartool pwv" returns the values for "set view" and "working directory view", also for
/// snapshot views.
///
/// \returns The ClearCase topLevel/VOB directory for this directory
QString ClearCasePlugin::ccManagesDirectory(const QString &directory) const
{
    QStringList args(QLatin1String("pwv"));
    const ClearCaseResponse response =
            runCleartool(directory, args, m_settings.timeOutMS(), SilentRun);

    if (response.error)
        return QString();

    const QStringList result = response.stdOut.split(QLatin1Char('\n'), QString::SkipEmptyParts);
    if (result.size() != 2)
        return QString();

    const QByteArray workingDirPattern("Working directory view: ");
    if (!result[0].startsWith(QLatin1String(workingDirPattern)))
        return QString();
    const QString workingDirectoryView = result[0].mid(workingDirPattern.size());

    const QByteArray setViewDirPattern("Set view: ");
    if (!result[1].startsWith(QLatin1String(setViewDirPattern)))
        return QString();
    const QString setView = result[1].mid(setViewDirPattern.size());

    const QString none(QLatin1String("** NONE **"));
    QString rootDir;
    if (setView != none || workingDirectoryView != none)
        rootDir = ccViewRoot(directory);
    else
        return QString();

    // Check if the directory is inside one of the known VOBs.
    static QStringList vobs;
    if (vobs.empty())
        vobs = getVobList();
381

382 383 384 385 386 387
    foreach (const QString &relativeVobDir, vobs) {
        const QString vobPath = QDir::cleanPath(rootDir + QDir::fromNativeSeparators(relativeVobDir));
        const bool isManaged = Utils::FileName::fromString(directory).isChildOf(Utils::FileName::fromString(vobPath));
        if (isManaged)
            return vobPath;
    }
388 389 390 391

    return QString();
}

392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
/// Find the root path of a clearcase view. Precondition: This is a clearcase managed dir
QString ClearCasePlugin::ccViewRoot(const QString &directory) const
{
    QStringList args(QLatin1String("pwv"));
    args << QLatin1String("-root");
    const ClearCaseResponse response =
            runCleartool(directory, args, m_settings.timeOutMS(), SilentRun);

    QString root = response.stdOut.trimmed();

    if (root.isEmpty()) {
        if (Utils::HostOsInfo::isWindowsHost())
            root = getDriveLetterOfPath(directory);
        else
            root = QLatin1String("/");
    }

    return QDir::fromNativeSeparators(root);
}

412 413
/*! Find top level for view that contains \a directory
 *
414
 * Handles both dynamic views and snapshot views.
415
 */
Orgad Shaneh's avatar
Orgad Shaneh committed
416 417
QString ClearCasePlugin::findTopLevel(const QString &directory) const
{
418 419
    // Do not check again if we've already tested that the dir is managed,
    // or if it is a child of a managed dir (top level).
420 421 422 423
    if ((directory == m_topLevel) ||
            Utils::FileName::fromString(directory).isChildOf(Utils::FileName::fromString(m_topLevel)))
        return m_topLevel;

424
    return ccManagesDirectory(directory);
Orgad Shaneh's avatar
Orgad Shaneh committed
425 426 427
}

static const VcsBase::VcsBaseSubmitEditorParameters submitParameters = {
428 429 430 431
    Constants::CLEARCASE_SUBMIT_MIMETYPE,
    Constants::CLEARCASECHECKINEDITOR_ID,
    Constants::CLEARCASECHECKINEDITOR_DISPLAY_NAME,
    Constants::CLEARCASECHECKINEDITOR,
432
    VcsBase::VcsBaseSubmitEditorParameters::DiffFiles
Orgad Shaneh's avatar
Orgad Shaneh committed
433 434 435 436 437 438 439 440 441 442 443 444 445 446
};

bool ClearCasePlugin::initialize(const QStringList & /*arguments */, QString *errorMessage)
{
    typedef VcsBase::VcsSubmitEditorFactory<ClearCaseSubmitEditor> ClearCaseSubmitEditorFactory;
    typedef VcsBase::VcsEditorFactory<ClearCaseEditor> ClearCaseEditorFactory;
    using namespace Constants;

    using namespace Core::Constants;
    using namespace ExtensionSystem;

    initializeVcs(new ClearCaseControl(this));

    m_clearcasePluginInstance = this;
447
    connect(ICore::instance(), SIGNAL(coreAboutToClose()), this, SLOT(closing()));
448 449
    connect(ProgressManager::instance(), SIGNAL(allTasksFinished(Core::Id)),
            this, SLOT(tasksFinished(Core::Id)));
Orgad Shaneh's avatar
Orgad Shaneh committed
450

hjk's avatar
hjk committed
451
    if (!MimeDatabase::addMimeTypes(QLatin1String(":/clearcase/ClearCase.mimetypes.xml"), errorMessage))
Orgad Shaneh's avatar
Orgad Shaneh committed
452 453
        return false;

454
    m_settings.fromSettings(ICore::settings());
Orgad Shaneh's avatar
Orgad Shaneh committed
455 456

    // update view name when changing active project
457
    if (ProjectExplorerPlugin *pe = ProjectExplorerPlugin::instance())
Orgad Shaneh's avatar
Orgad Shaneh committed
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
        connect(pe, SIGNAL(currentProjectChanged(ProjectExplorer::Project*)),
                this, SLOT(projectChanged(ProjectExplorer::Project*)));

    addAutoReleasedObject(new SettingsPage);

    addAutoReleasedObject(new ClearCaseSubmitEditorFactory(&submitParameters));

    // any editor responds to describe (when clicking a version)
    static const char *describeSlot = SLOT(describe(QString,QString));
    const int editorCount = sizeof(editorParameters)/sizeof(VcsBase::VcsBaseEditorParameters);
    for (int i = 0; i < editorCount; i++)
        addAutoReleasedObject(new ClearCaseEditorFactory(editorParameters + i, this, describeSlot));

    const QString description = QLatin1String("ClearCase");
    const QString prefix = QLatin1String("cc");
    // register cc prefix in Locator
474
    m_commandLocator = new Core::CommandLocator("cc", description, prefix);
Orgad Shaneh's avatar
Orgad Shaneh committed
475 476 477
    addAutoReleasedObject(m_commandLocator);

    //register actions
478
    ActionContainer *toolsContainer = ActionManager::actionContainer(M_TOOLS);
Orgad Shaneh's avatar
Orgad Shaneh committed
479

480
    ActionContainer *clearcaseMenu = ActionManager::createMenu(CMD_ID_CLEARCASE_MENU);
Orgad Shaneh's avatar
Orgad Shaneh committed
481 482 483
    clearcaseMenu->menu()->setTitle(tr("C&learCase"));
    toolsContainer->addMenu(clearcaseMenu);
    m_menuAction = clearcaseMenu->menu()->menuAction();
484 485
    Context globalcontext(C_GLOBAL);
    Command *command;
Orgad Shaneh's avatar
Orgad Shaneh committed
486 487

    m_checkOutAction = new Utils::ParameterAction(tr("Check Out..."), tr("Check &Out \"%1\"..."), Utils::ParameterAction::AlwaysEnabled, this);
488
    command = ActionManager::registerAction(m_checkOutAction, CMD_ID_CHECKOUT,
Orgad Shaneh's avatar
Orgad Shaneh committed
489
        globalcontext);
490 491
    command->setAttribute(Command::CA_UpdateText);
    command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+L,Meta+O") : tr("Alt+L,Alt+O")));
Orgad Shaneh's avatar
Orgad Shaneh committed
492 493 494 495 496
    connect(m_checkOutAction, SIGNAL(triggered()), this, SLOT(checkOutCurrentFile()));
    clearcaseMenu->addAction(command);
    m_commandLocator->appendCommand(command);

    m_checkInCurrentAction = new Utils::ParameterAction(tr("Check &In..."), tr("Check &In \"%1\"..."), Utils::ParameterAction::AlwaysEnabled, this);
497 498 499
    command = ActionManager::registerAction(m_checkInCurrentAction, CMD_ID_CHECKIN, globalcontext);
    command->setAttribute(Command::CA_UpdateText);
    command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+L,Meta+I") : tr("Alt+L,Alt+I")));
Orgad Shaneh's avatar
Orgad Shaneh committed
500 501 502 503 504
    connect(m_checkInCurrentAction, SIGNAL(triggered()), this, SLOT(startCheckInCurrentFile()));
    clearcaseMenu->addAction(command);
    m_commandLocator->appendCommand(command);

    m_undoCheckOutAction = new Utils::ParameterAction(tr("Undo Check Out"), tr("&Undo Check Out \"%1\""), Utils::ParameterAction::AlwaysEnabled, this);
505 506 507
    command = ActionManager::registerAction(m_undoCheckOutAction, CMD_ID_UNDOCHECKOUT, globalcontext);
    command->setAttribute(Command::CA_UpdateText);
    command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+L,Meta+U") : tr("Alt+L,Alt+U")));
Orgad Shaneh's avatar
Orgad Shaneh committed
508 509 510 511 512
    connect(m_undoCheckOutAction, SIGNAL(triggered()), this, SLOT(undoCheckOutCurrent()));
    clearcaseMenu->addAction(command);
    m_commandLocator->appendCommand(command);

    m_undoHijackAction = new Utils::ParameterAction(tr("Undo Hijack"), tr("Undo Hi&jack \"%1\""), Utils::ParameterAction::AlwaysEnabled, this);
513 514 515
    command = ActionManager::registerAction(m_undoHijackAction, CMD_ID_UNDOHIJACK, globalcontext);
    command->setAttribute(Command::CA_UpdateText);
    command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+L,Meta+R") : tr("Alt+L,Alt+R")));
Orgad Shaneh's avatar
Orgad Shaneh committed
516 517 518 519 520 521 522
    connect(m_undoHijackAction, SIGNAL(triggered()), this, SLOT(undoHijackCurrent()));
    clearcaseMenu->addAction(command);
    m_commandLocator->appendCommand(command);

    clearcaseMenu->addSeparator(globalcontext);

    m_diffCurrentAction = new Utils::ParameterAction(tr("Diff Current File"), tr("&Diff \"%1\""), Utils::ParameterAction::EnabledWithParameter, this);
523
    command = ActionManager::registerAction(m_diffCurrentAction,
Orgad Shaneh's avatar
Orgad Shaneh committed
524
        CMD_ID_DIFF_CURRENT, globalcontext);
525 526
    command->setAttribute(Command::CA_UpdateText);
    command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+L,Meta+D") : tr("Alt+L,Alt+D")));
Orgad Shaneh's avatar
Orgad Shaneh committed
527 528 529 530 531
    connect(m_diffCurrentAction, SIGNAL(triggered()), this, SLOT(diffCurrentFile()));
    clearcaseMenu->addAction(command);
    m_commandLocator->appendCommand(command);

    m_historyCurrentAction = new Utils::ParameterAction(tr("History Current File"), tr("&History \"%1\""), Utils::ParameterAction::EnabledWithParameter, this);
532
    command = ActionManager::registerAction(m_historyCurrentAction,
Orgad Shaneh's avatar
Orgad Shaneh committed
533
        CMD_ID_HISTORY_CURRENT, globalcontext);
534 535
    command->setAttribute(Command::CA_UpdateText);
    command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+L,Meta+H") : tr("Alt+L,Alt+H")));
Orgad Shaneh's avatar
Orgad Shaneh committed
536 537 538 539 540 541
    connect(m_historyCurrentAction, SIGNAL(triggered()), this,
        SLOT(historyCurrentFile()));
    clearcaseMenu->addAction(command);
    m_commandLocator->appendCommand(command);

    m_annotateCurrentAction = new Utils::ParameterAction(tr("Annotate Current File"), tr("&Annotate \"%1\""), Utils::ParameterAction::EnabledWithParameter, this);
542
    command = ActionManager::registerAction(m_annotateCurrentAction,
Orgad Shaneh's avatar
Orgad Shaneh committed
543
        CMD_ID_ANNOTATE, globalcontext);
544 545
    command->setAttribute(Command::CA_UpdateText);
    command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+L,Meta+A") : tr("Alt+L,Alt+A")));
Orgad Shaneh's avatar
Orgad Shaneh committed
546 547 548 549 550 551
    connect(m_annotateCurrentAction, SIGNAL(triggered()), this,
        SLOT(annotateCurrentFile()));
    clearcaseMenu->addAction(command);
    m_commandLocator->appendCommand(command);

    m_addFileAction = new Utils::ParameterAction(tr("Add File..."), tr("Add File \"%1\""), Utils::ParameterAction::EnabledWithParameter, this);
552 553
    command = ActionManager::registerAction(m_addFileAction, CMD_ID_ADD_FILE, globalcontext);
    command->setAttribute(Command::CA_UpdateText);
Orgad Shaneh's avatar
Orgad Shaneh committed
554 555 556 557 558 559
    connect(m_addFileAction, SIGNAL(triggered()), this, SLOT(addCurrentFile()));
    clearcaseMenu->addAction(command);

    clearcaseMenu->addSeparator(globalcontext);

    m_diffActivityAction = new QAction(tr("Diff A&ctivity..."), this);
560
    m_diffActivityAction->setEnabled(false);
561
    command = ActionManager::registerAction(m_diffActivityAction, CMD_ID_DIFF_ACTIVITY, globalcontext);
Orgad Shaneh's avatar
Orgad Shaneh committed
562 563 564 565 566
    connect(m_diffActivityAction, SIGNAL(triggered()), this, SLOT(diffActivity()));
    clearcaseMenu->addAction(command);
    m_commandLocator->appendCommand(command);

    m_checkInActivityAction = new Utils::ParameterAction(tr("Ch&eck In Activity"), tr("Chec&k In Activity \"%1\"..."), Utils::ParameterAction::EnabledWithParameter, this);
567
    m_checkInActivityAction->setEnabled(false);
568
    command = ActionManager::registerAction(m_checkInActivityAction, CMD_ID_CHECKIN_ACTIVITY, globalcontext);
Orgad Shaneh's avatar
Orgad Shaneh committed
569
    connect(m_checkInActivityAction, SIGNAL(triggered()), this, SLOT(startCheckInActivity()));
570
    command->setAttribute(Command::CA_UpdateText);
Orgad Shaneh's avatar
Orgad Shaneh committed
571 572 573 574 575 576
    clearcaseMenu->addAction(command);
    m_commandLocator->appendCommand(command);

    clearcaseMenu->addSeparator(globalcontext);

    m_updateIndexAction = new QAction(tr("Update Index"), this);
577
    command = ActionManager::registerAction(m_updateIndexAction, CMD_ID_UPDATEINDEX, globalcontext);
Orgad Shaneh's avatar
Orgad Shaneh committed
578 579 580 581
    connect(m_updateIndexAction, SIGNAL(triggered()), this, SLOT(updateIndex()));
    clearcaseMenu->addAction(command);

    m_updateViewAction = new Utils::ParameterAction(tr("Update View"), tr("U&pdate View \"%1\""), Utils::ParameterAction::EnabledWithParameter, this);
582
    command = ActionManager::registerAction(m_updateViewAction, CMD_ID_UPDATE_VIEW, globalcontext);
Orgad Shaneh's avatar
Orgad Shaneh committed
583
    connect(m_updateViewAction, SIGNAL(triggered()), this, SLOT(updateView()));
584
    command->setAttribute(Command::CA_UpdateText);
Orgad Shaneh's avatar
Orgad Shaneh committed
585 586 587 588 589
    clearcaseMenu->addAction(command);

    clearcaseMenu->addSeparator(globalcontext);

    m_checkInAllAction = new QAction(tr("Check In All &Files..."), this);
590 591
    command = ActionManager::registerAction(m_checkInAllAction, CMD_ID_CHECKIN_ALL, globalcontext);
    command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+L,Meta+F") : tr("Alt+L,Alt+F")));
Orgad Shaneh's avatar
Orgad Shaneh committed
592 593 594 595 596
    connect(m_checkInAllAction, SIGNAL(triggered()), this, SLOT(startCheckInAll()));
    clearcaseMenu->addAction(command);
    m_commandLocator->appendCommand(command);

    m_statusAction = new QAction(tr("View &Status"), this);
597 598
    command = ActionManager::registerAction(m_statusAction, CMD_ID_STATUS, globalcontext);
    command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+L,Meta+S") : tr("Alt+L,Alt+S")));
Orgad Shaneh's avatar
Orgad Shaneh committed
599 600 601 602 603
    connect(m_statusAction, SIGNAL(triggered()), this, SLOT(viewStatus()));
    clearcaseMenu->addAction(command);
    m_commandLocator->appendCommand(command);

    // Actions of the submit editor
604
    Context clearcasecheckincontext(Constants::CLEARCASECHECKINEDITOR);
Orgad Shaneh's avatar
Orgad Shaneh committed
605 606

    m_checkInSelectedAction = new QAction(VcsBase::VcsBaseSubmitEditor::submitIcon(), tr("Check In"), this);
607 608
    command = ActionManager::registerAction(m_checkInSelectedAction, Constants::CHECKIN_SELECTED, clearcasecheckincontext);
    command->setAttribute(Command::CA_UpdateText);
Orgad Shaneh's avatar
Orgad Shaneh committed
609 610 611
    connect(m_checkInSelectedAction, SIGNAL(triggered()), this, SLOT(checkInSelected()));

    m_checkInDiffAction = new QAction(VcsBase::VcsBaseSubmitEditor::diffIcon(), tr("Diff Selected Files"), this);
612
    command = ActionManager::registerAction(m_checkInDiffAction , Constants::DIFF_SELECTED, clearcasecheckincontext);
Orgad Shaneh's avatar
Orgad Shaneh committed
613 614

    m_submitUndoAction = new QAction(tr("&Undo"), this);
615
    command = ActionManager::registerAction(m_submitUndoAction, Core::Constants::UNDO, clearcasecheckincontext);
Orgad Shaneh's avatar
Orgad Shaneh committed
616 617

    m_submitRedoAction = new QAction(tr("&Redo"), this);
618
    command = ActionManager::registerAction(m_submitRedoAction, Core::Constants::REDO, clearcasecheckincontext);
Orgad Shaneh's avatar
Orgad Shaneh committed
619 620 621 622 623

    return true;
}

// called before closing the submit editor
624
bool ClearCasePlugin::submitEditorAboutToClose()
Orgad Shaneh's avatar
Orgad Shaneh committed
625 626 627 628
{
    if (!isCheckInEditorOpen())
        return true;

629 630
    ClearCaseSubmitEditor *editor = qobject_cast<ClearCaseSubmitEditor *>(submitEditor());
    QTC_ASSERT(editor, return true);
631
    IDocument *editorDocument = editor->document();
632
    QTC_ASSERT(editorDocument, return true);
Orgad Shaneh's avatar
Orgad Shaneh committed
633 634 635

    // Submit editor closing. Make it write out the check in message
    // and retrieve files
636
    const QFileInfo editorFile(editorDocument->filePath());
Orgad Shaneh's avatar
Orgad Shaneh committed
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
    const QFileInfo changeFile(m_checkInMessageFileName);
    if (editorFile.absoluteFilePath() != changeFile.absoluteFilePath())
        return true; // Oops?!

    // Prompt user. Force a prompt unless submit was actually invoked (that
    // is, the editor was closed or shutdown).
    bool prompt = m_settings.promptToCheckIn;
    const VcsBase::VcsBaseSubmitEditor::PromptSubmitResult answer =
            editor->promptSubmit(tr("Closing ClearCase Editor"),
                                 tr("Do you want to check in the files?"),
                                 tr("The comment check failed. Do you want to check in the files?"),
                                 &prompt, !m_submitActionTriggered);
    m_submitActionTriggered = false;
    switch (answer) {
    case VcsBase::VcsBaseSubmitEditor::SubmitCanceled:
        return false; // Keep editing and change file
    case VcsBase::VcsBaseSubmitEditor::SubmitDiscarded:
        cleanCheckInMessageFile();
        return true; // Cancel all
    default:
        break;
    }
    // If user changed
    if (prompt != m_settings.promptToCheckIn) {
        m_settings.promptToCheckIn = prompt;
662
        m_settings.toSettings(ICore::settings());
Orgad Shaneh's avatar
Orgad Shaneh committed
663 664 665 666 667 668
    }

    const QStringList fileList = editor->checkedFiles();
    bool closeEditor = true;
    if (!fileList.empty()) {
        // get message & check in
669
        closeEditor = DocumentManager::saveDocument(editorDocument);
Orgad Shaneh's avatar
Orgad Shaneh committed
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
        if (closeEditor) {
            ClearCaseSubmitEditorWidget *widget = editor->submitEditorWidget();
            closeEditor = vcsCheckIn(m_checkInMessageFileName, fileList, widget->activity(),
                                   widget->isIdentical(), widget->isPreserve(),
                                   widget->activityChanged());
        }
    }
    // vcsCheckIn might fail if some of the files failed to check-in (though it does check-in
    // those who didn't fail). Therefore, if more than one file was sent, consider it as success
    // anyway (sync will be called from vcsCheckIn for next attempt)
    closeEditor |= (fileList.count() > 1);
    if (closeEditor)
        cleanCheckInMessageFile();
    return closeEditor;
}

void ClearCasePlugin::diffCheckInFiles(const QStringList &files)
{
688
    ccDiffWithPred(m_checkInView, files);
Orgad Shaneh's avatar
Orgad Shaneh committed
689 690
}

691
static inline void setWorkingDirectory(IEditor *editor, const QString &wd)
Orgad Shaneh's avatar
Orgad Shaneh committed
692 693
{
    if (VcsBase::VcsBaseEditorWidget *ve = qobject_cast<VcsBase::VcsBaseEditorWidget*>(editor->widget()))
694
        ve->setWorkingDirectory(wd);
Orgad Shaneh's avatar
Orgad Shaneh committed
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
}

//! retrieve full location of predecessor of \a version
QString ClearCasePlugin::ccGetPredecessor(const QString &version) const
{
    QStringList args(QLatin1String("describe"));
    args << QLatin1String("-fmt") << QLatin1String("%En@@%PSn") << version;
    const ClearCaseResponse response =
            runCleartool(currentState().topLevel(), args, m_settings.timeOutMS(), SilentRun);
    if (response.error || response.stdOut.endsWith(QLatin1Char('@'))) // <name-unknown>@@
        return QString();
    else
        return response.stdOut;
}

710
//! Get a list of paths to active VOBs.
711
//! Paths are relative to viewRoot
Orgad Shaneh's avatar
Orgad Shaneh committed
712 713 714 715
QStringList ClearCasePlugin::ccGetActiveVobs() const
{
    QStringList res;
    QStringList args(QLatin1String("lsvob"));
716 717
    const QString theViewRoot = viewRoot();

Orgad Shaneh's avatar
Orgad Shaneh committed
718
    const ClearCaseResponse response =
719
            runCleartool(theViewRoot, args, m_settings.timeOutMS(), SilentRun);
Orgad Shaneh's avatar
Orgad Shaneh committed
720 721
    if (response.error)
        return res;
722 723 724 725 726

    // format of output unix:
    // * /path/to/vob   /path/to/vob/storage.vbs <and some text omitted here>
    // format of output windows:
    // * \vob     \\share\path\to\vob\storage.vbs <and some text omitted here>
727
    QString prefix = theViewRoot;
728 729 730
    if (!prefix.endsWith(QLatin1Char('/')))
        prefix += QLatin1Char('/');

731
    const QDir theViewRootDir(theViewRoot);
732 733 734 735 736 737 738
    foreach (const QString &line, response.stdOut.split(QLatin1Char('\n'), QString::SkipEmptyParts)) {
        const bool isActive = line.at(0) == QLatin1Char('*');
        if (!isActive)
            continue;

        const QString dir =
                QDir::fromNativeSeparators(line.mid(3, line.indexOf(QLatin1Char(' '), 3) - 3));
739
        const QString relativeDir = theViewRootDir.relativeFilePath(dir);
740 741 742 743 744 745

        // Snapshot views does not necessarily have all active VOBs loaded, so we'll have to
        // check if the dirs exists as well. Else the command will work, but the output will
        // complain about the element not being loaded.
        if (QFile::exists(prefix + relativeDir))
            res.append(relativeDir);
Orgad Shaneh's avatar
Orgad Shaneh committed
746 747 748 749
    }
    return res;
}

750 751 752 753 754 755 756 757 758 759
void ClearCasePlugin::checkAndReIndexUnknownFile(const QString &file)
{
    if (isDynamic()) {
        // reindex unknown files
        if (m_statusMap->value(file, FileStatus(FileStatus::Unknown)).status == FileStatus::Unknown)
            updateStatusForFile(file);
    }
}

// file must be absolute, and using '/' path separator
Orgad Shaneh's avatar
Orgad Shaneh committed
760 761
FileStatus ClearCasePlugin::vcsStatus(const QString &file) const
{
762
    return m_statusMap->value(file, FileStatus(FileStatus::Unknown));
Orgad Shaneh's avatar
Orgad Shaneh committed
763 764 765 766 767 768 769 770 771 772 773 774
}

QString ClearCasePlugin::ccGetFileActivity(const QString &workingDir, const QString &file)
{
    QStringList args(QLatin1String("lscheckout"));
    args << QLatin1String("-fmt") << QLatin1String("%[activity]p");
    args << file;
    const ClearCaseResponse response =
            runCleartool(workingDir, args, m_settings.timeOutMS(), SilentRun);
    return response.stdOut;
}

775
ClearCaseSubmitEditor *ClearCasePlugin::openClearCaseSubmitEditor(const QString &fileName, bool isUcm)
Orgad Shaneh's avatar
Orgad Shaneh committed
776
{
777 778
    IEditor *editor =
            EditorManager::openEditor(fileName, Constants::CLEARCASECHECKINEDITOR_ID);
Orgad Shaneh's avatar
Orgad Shaneh committed
779 780 781 782
    ClearCaseSubmitEditor *submitEditor = qobject_cast<ClearCaseSubmitEditor*>(editor);
    QTC_CHECK(submitEditor);
    submitEditor->registerActions(m_submitUndoAction, m_submitRedoAction, m_checkInSelectedAction, m_checkInDiffAction);
    connect(submitEditor, SIGNAL(diffSelectedFiles(QStringList)), this, SLOT(diffCheckInFiles(QStringList)));
783
    submitEditor->setCheckScriptWorkingDirectory(m_checkInView);
784
    submitEditor->setIsUcm(isUcm);
Orgad Shaneh's avatar
Orgad Shaneh committed
785 786 787
    return submitEditor;
}

788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
QString fileStatusToText(FileStatus fileStatus)
{
    switch (fileStatus.status)
    {
    case FileStatus::CheckedIn:
        return QLatin1String("CheckedIn");
    case FileStatus::CheckedOut:
        return QLatin1String("CheckedOut");
    case FileStatus::Hijacked:
        return QLatin1String("Hijacked");
    case FileStatus::Missing:
        return QLatin1String("Missing");
    case FileStatus::NotManaged:
        return QLatin1String("ViewPrivate");
    case FileStatus::Unknown:
        return QLatin1String("Unknown");
    default:
        return QLatin1String("default");
    }
}

Orgad Shaneh's avatar
Orgad Shaneh committed
809 810
void ClearCasePlugin::updateStatusActions()
{
811
    FileStatus fileStatus = FileStatus::Unknown;
Orgad Shaneh's avatar
Orgad Shaneh committed
812
    bool hasFile = currentState().hasFile();
813
    if (hasFile) {
814
        QString absoluteFileName = currentState().currentFile();
815 816
        checkAndReIndexUnknownFile(absoluteFileName);
        fileStatus = vcsStatus(absoluteFileName);
817

818 819
        updateEditDerivedObjectWarning(absoluteFileName, fileStatus.status);

820
        if (Constants::debug)
821 822
            qDebug() << Q_FUNC_INFO << absoluteFileName << ", status = "
                     << fileStatusToText(fileStatus.status) << "(" << fileStatus.status << ")";
823
    }
824

Orgad Shaneh's avatar
Orgad Shaneh committed
825 826
    m_checkOutAction->setEnabled(hasFile && (fileStatus.status & (FileStatus::CheckedIn | FileStatus::Hijacked)));
    m_undoCheckOutAction->setEnabled(hasFile && (fileStatus.status & FileStatus::CheckedOut));
827
    m_undoHijackAction->setEnabled(!m_viewData.isDynamic && hasFile && (fileStatus.status & FileStatus::Hijacked));
Orgad Shaneh's avatar
Orgad Shaneh committed
828 829
    m_checkInCurrentAction->setEnabled(hasFile && (fileStatus.status & FileStatus::CheckedOut));
    m_addFileAction->setEnabled(hasFile && (fileStatus.status & FileStatus::NotManaged));
830 831 832
    m_diffCurrentAction->setEnabled(hasFile && (fileStatus.status != FileStatus::NotManaged));
    m_historyCurrentAction->setEnabled(hasFile && (fileStatus.status != FileStatus::NotManaged));
    m_annotateCurrentAction->setEnabled(hasFile && (fileStatus.status != FileStatus::NotManaged));
833

834 835
    m_checkInActivityAction->setEnabled(m_viewData.isUcm);
    m_diffActivityAction->setEnabled(m_viewData.isUcm);
Orgad Shaneh's avatar
Orgad Shaneh committed
836 837 838 839 840 841 842 843 844 845 846 847 848 849
}

void ClearCasePlugin::updateActions(VcsBase::VcsBasePlugin::ActionState as)
{
    if (!enableMenuAction(as, m_menuAction)) {
        m_commandLocator->setEnabled(false);
        return;
    }
    const VcsBase::VcsBasePluginState state = currentState();
    const bool hasTopLevel = state.hasTopLevel();
    m_commandLocator->setEnabled(hasTopLevel);
    if (hasTopLevel)
        m_topLevel = state.topLevel();

850
    m_updateViewAction->setParameter(m_viewData.isDynamic ? QString() : m_viewData.name);
Orgad Shaneh's avatar
Orgad Shaneh committed
851 852 853 854 855 856 857 858 859 860 861

    const QString fileName = state.currentFileName();
    m_checkOutAction->setParameter(fileName);
    m_undoCheckOutAction->setParameter(fileName);
    m_undoHijackAction->setParameter(fileName);
    m_diffCurrentAction->setParameter(fileName);
    m_checkInCurrentAction->setParameter(fileName);
    m_historyCurrentAction->setParameter(fileName);
    m_annotateCurrentAction->setParameter(fileName);
    m_addFileAction->setParameter(fileName);
    m_updateIndexAction->setEnabled(!m_settings.disableIndexer);
862

Orgad Shaneh's avatar
Orgad Shaneh committed
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
    updateStatusActions();
}

void ClearCasePlugin::checkOutCurrentFile()
{
    const VcsBase::VcsBasePluginState state = currentState();
    QTC_ASSERT(state.hasFile(), return);
    vcsOpen(state.currentFileTopLevel(), state.relativeCurrentFile());
}

void ClearCasePlugin::addCurrentFile()
{
    const VcsBase::VcsBasePluginState state = currentState();
    QTC_ASSERT(state.hasFile(), return);
    vcsAdd(state.currentFileTopLevel(), state.relativeCurrentFile());
}

880
// Set the FileStatus of file given in absolute path
Orgad Shaneh's avatar
Orgad Shaneh committed
881
void ClearCasePlugin::setStatus(const QString &file, FileStatus::Status status, bool update)
Orgad Shaneh's avatar
Orgad Shaneh committed
882
{
883
    QTC_CHECK(!file.isEmpty());
884 885 886
    m_statusMap->insert(file, FileStatus(status, QFileInfo(file).permissions()));

    if (update && currentState().currentFile() == file)
Orgad Shaneh's avatar
Orgad Shaneh committed
887
        QMetaObject::invokeMethod(this, "updateStatusActions");
Orgad Shaneh's avatar
Orgad Shaneh committed
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919
}

void ClearCasePlugin::undoCheckOutCurrent()
{
    const VcsBase::VcsBasePluginState state = currentState();
    QTC_ASSERT(state.hasFile(), return);
    QString file = state.relativeCurrentFile();
    const QString fileName = QDir::toNativeSeparators(file);

    QStringList args(QLatin1String("diff"));
    args << QLatin1String("-diff_format") << QLatin1String("-predecessor");
    args << fileName;

    const ClearCaseResponse diffResponse =
            runCleartool(state.currentFileTopLevel(), args, m_settings.timeOutMS(), 0);

    bool different = diffResponse.error; // return value is 1 if there is any difference
    bool keep = false;
    if (different) {
        Ui::UndoCheckOut uncoUi;
        QDialog uncoDlg;
        uncoUi.setupUi(&uncoDlg);
        uncoUi.lblMessage->setText(tr("Do you want to undo the check out of '%1'?").arg(fileName));
        if (uncoDlg.exec() != QDialog::Accepted)
            return;
        keep = uncoUi.chkKeep->isChecked();
    }
    vcsUndoCheckOut(state.topLevel(), file, keep);
}

bool ClearCasePlugin::vcsUndoCheckOut(const QString &workingDir, const QString &fileName, bool keep)
{
920
    if (Constants::debug)
Orgad Shaneh's avatar
Orgad Shaneh committed
921 922
        qDebug() << Q_FUNC_INFO << workingDir << fileName << keep;

923
    FileChangeBlocker fcb(fileName);
Orgad Shaneh's avatar
Orgad Shaneh committed
924 925 926 927 928 929 930 931 932 933 934

    // revert
    QStringList args(QLatin1String("uncheckout"));
    args << QLatin1String(keep ? "-keep" : "-rm");
    args << QDir::toNativeSeparators(fileName);

    const ClearCaseResponse response =
            runCleartool(workingDir, args, m_settings.timeOutMS(),
                         ShowStdOutInLogWindow | FullySynchronously);

    if (!response.error) {
935 936
        const QString absPath = workingDir + QLatin1Char('/') + fileName;

Orgad Shaneh's avatar
Orgad Shaneh committed
937
        if (!m_settings.disableIndexer)
938 939
            setStatus(absPath, FileStatus::CheckedIn);
        clearCaseControl()->emitFilesChanged(QStringList(absPath));
Orgad Shaneh's avatar
Orgad Shaneh committed
940 941 942 943
    }
    return !response.error;
}

944 945 946 947 948 949

/*! Undo a hijacked file in a snapshot view
 *
 * Runs cleartool update -overwrite \a fileName in \a workingDir
 * if \a keep is true, renames hijacked files to <filename>.keep. Otherwise it is overwritten
 */
Orgad Shaneh's avatar
Orgad Shaneh committed
950 951
bool ClearCasePlugin::vcsUndoHijack(const QString &workingDir, const QString &fileName, bool keep)
{
952
    if (Constants::debug)
Orgad Shaneh's avatar
Orgad Shaneh committed
953 954 955 956
        qDebug() << Q_FUNC_INFO << workingDir << fileName << keep;
    QStringList args(QLatin1String("update"));
    args << QLatin1String(keep ? "-rename" : "-overwrite");
    args << QLatin1String("-log");
957 958 959
    if (Utils::HostOsInfo::isWindowsHost())
        args << QLatin1String("NUL");
    else
Orgad Shaneh's avatar
Orgad Shaneh committed
960 961 962 963 964 965
    args << QLatin1String("/dev/null");
    args << QDir::toNativeSeparators(fileName);

    const ClearCaseResponse response =
            runCleartool(workingDir, args, m_settings.timeOutMS(),
                   ShowStdOutInLogWindow | FullySynchronously);
966 967 968 969
    if (!response.error && !m_settings.disableIndexer) {
        const QString absPath = workingDir + QLatin1Char('/') + fileName;
        setStatus(absPath, FileStatus::CheckedIn);
    }
Orgad Shaneh's avatar
Orgad Shaneh committed
970 971 972 973 974 975 976 977 978 979
    return !response.error;
}

void ClearCasePlugin::undoHijackCurrent()
{
    const VcsBase::VcsBasePluginState state = currentState();
    QTC_ASSERT(state.hasFile(), return);
    const QString fileName = state.relativeCurrentFile();

    bool keep = false;
980 981 982 983 984 985 986
    bool askKeep = true;
    if (m_settings.extDiffAvailable) {
        QString diffres = diffExternal(ccGetFileVersion(state.topLevel(), fileName), fileName);
        if (diffres.at(0) == QLatin1Char('F')) // Files are identical
            askKeep = false;
    }
    if (askKeep) {
Orgad Shaneh's avatar
Orgad Shaneh committed
987 988 989
        Ui::UndoCheckOut unhijackUi;
        QDialog unhijackDlg;
        unhijackUi.setupUi(&unhijackDlg);
990
        unhijackDlg.setWindowTitle(tr("Undo Hijack File"));
Orgad Shaneh's avatar
Orgad Shaneh committed
991 992 993 994 995 996 997
        unhijackUi.lblMessage->setText(tr("Do you want to undo hijack of '%1'?")
                                       .arg(QDir::toNativeSeparators(fileName)));
        if (unhijackDlg.exec() != QDialog::Accepted)
            return;
        keep = unhijackUi.chkKeep->isChecked();
    }

998
    FileChangeBlocker fcb(state.currentFile());
Orgad Shaneh's avatar
Orgad Shaneh committed
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011

    // revert
    if (vcsUndoHijack(state.currentFileTopLevel(), fileName, keep))
        clearCaseControl()->emitFilesChanged(QStringList(state.currentFile()));
}

QString ClearCasePlugin::ccGetFileVersion(const QString &workingDir, const QString &file) const
{
    QStringList args(QLatin1String("ls"));
    args << QLatin1String("-short") << file;
    return runCleartoolSync(workingDir, args).trimmed();
}

1012
void ClearCasePlugin::ccDiffWithPred(const QString &workingDir, const QStringList &files)
Orgad Shaneh's avatar
Orgad Shaneh committed
1013
{
1014
    if (Constants::debug)
Orgad Shaneh's avatar
Orgad Shaneh committed
1015
        qDebug() << Q_FUNC_INFO << files;
1016
    const QString source = VcsBase::VcsBaseEditorWidget::getSource(workingDir, files);
Orgad Shaneh's avatar
Orgad Shaneh committed
1017 1018 1019
    QTextCodec *codec = source.isEmpty() ? static_cast<QTextCodec *>(0) : VcsBase::VcsBaseEditorWidget::getCodec(source);

    if ((m_settings.diffType == GraphicalDiff) && (files.count() == 1)) {
1020 1021
        const QString file = files.first();
        const QString absFilePath = workingDir + QLatin1Char('/') + file;
1022
        if (vcsStatus(absFilePath).status == FileStatus::Hijacked)
1023
            diffGraphical(ccGetFileVersion(workingDir, file), file);
Orgad Shaneh's avatar
Orgad Shaneh committed
1024 1025 1026 1027
        else
            diffGraphical(file);
        return; // done here, diff is opened in a new window
    }
1028 1029 1030 1031 1032
    if (!m_settings.extDiffAvailable) {
        VcsBase::VcsBaseOutputWindow::instance()->appendError(
                    tr("External diff is required to compare multiple files."));
        return;
    }
Orgad Shaneh's avatar
Orgad Shaneh committed
1033 1034
    QString result;
    foreach (const QString &file, files) {
1035
        const QString absFilePath = workingDir + QLatin1Char('/') + file;
1036
        if (vcsStatus(QDir::fromNativeSeparators(absFilePath)).status == FileStatus::Hijacked)
1037
            result += diffExternal(ccGetFileVersion(workingDir, file), file);
Orgad Shaneh's avatar
Orgad Shaneh committed
1038 1039 1040 1041 1042 1043 1044 1045
        else
            result += diffExternal(file);
    }

    QString diffname;

    // 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
1046
    const QString tag = VcsBase::VcsBaseEditorWidget::editorTag(VcsBase::DiffOutput, workingDir, files);
Orgad Shaneh's avatar
Orgad Shaneh committed
1047 1048
    if (files.count() == 1) {
        // Show in the same editor if diff has been executed before
1049
        if (IEditor *existingEditor = VcsBase::VcsBaseEditorWidget::locateEditorByTag(tag)) {
1050
            existingEditor->document()->setContents(result.toUtf8());
1051
            EditorManager::activateEditor(existingEditor);
1052
            setWorkingDirectory(existingEditor, workingDir);
Orgad Shaneh's avatar
Orgad Shaneh committed
1053 1054 1055 1056 1057
            return;
        }
        diffname = QDir::toNativeSeparators(files.first());
    }
    const QString title = QString::fromLatin1("cc diff %1").arg(diffname);
1058
    IEditor *editor = showOutputInEditor(title, result, VcsBase::DiffOutput, source, codec);
1059
    setWorkingDirectory(editor, workingDir);
Orgad Shaneh's avatar
Orgad Shaneh committed
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
    VcsBase::VcsBaseEditorWidget::tagEditor(editor, tag);
    ClearCaseEditor *diffEditorWidget = qobject_cast<ClearCaseEditor *>(editor->widget());
    QTC_ASSERT(diffEditorWidget, return);
    if (files.count() == 1)
        editor->setProperty("originalFileName", diffname);
}

QStringList ClearCasePlugin::ccGetActivityVersions(const QString &workingDir, const QString &activity)
{
    QStringList args(QLatin1String("lsactivity"));
    args << QLatin1String("-fmt") << QLatin1String("%[versions]Cp") << activity;
    const ClearCaseResponse response =
        runCleartool(workingDir, args, m_settings.timeOutMS(), SilentRun);
    if (response.error)
        return QStringList();
    QStringList versions = response.stdOut.split(QLatin1String(", "));
    versions.sort();
    return versions;
}

void ClearCasePlugin::rmdir(const QString &path)
{
    QDir dir(path);
    foreach (QFileInfo fi, dir.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot)) {
        if (fi.isDir()) {
            rmdir(fi.canonicalFilePath());
            dir.rmdir(fi.baseName());
        }
        else
            QFile::remove(fi.canonicalFilePath());
    }
}

void ClearCasePlugin::diffActivity()
{
1095 1096
    typedef QMap<QString, QStringPair>::Iterator FileVerIt;

Orgad Shaneh's avatar
Orgad Shaneh committed
1097 1098
    const VcsBase::VcsBasePluginState state = currentState();
    QTC_ASSERT(state.hasTopLevel(), return);
1099
    if (Constants::debug)
Orgad Shaneh's avatar
Orgad Shaneh committed
1100
        qDebug() << Q_FUNC_INFO;
1101 1102 1103 1104 1105
    if (!m_settings.extDiffAvailable) {
        VcsBase::VcsBaseOutputWindow::instance()->appendError(
                    tr("External diff is required to compare multiple files."));
        return;
    }
Orgad Shaneh's avatar
Orgad Shaneh committed
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 1142 1143 1144
    QString topLevel = state.topLevel();
    QString activity = QInputDialog::getText(0, tr("Enter Activity"), tr("Activity Name"), QLineEdit::Normal, m_activity);
    if (activity.isEmpty())
        return;
    QStringList versions = ccGetActivityVersions(topLevel, activity);

    QString result;
    // map from fileName to (first, latest) pair
    QMap<QString, QStringPair> filever;
    int topLevelLen = topLevel.length();
    foreach (const QString &version, versions) {
        QString shortver = version.mid(topLevelLen + 1);
        int atatpos = shortver.indexOf(QLatin1String("@@"));
        if (atatpos != -1) {
            QString file = shortver.left(atatpos);
            // latest version - updated each line
            filever[file].second = shortver;

            // pre-first version. only for the first occurence
            if (filever[file].first.isEmpty()) {
                int verpos = shortver.lastIndexOf(QRegExp(QLatin1String("[^0-9]"))) + 1;
                int vernum = shortver.mid(verpos).toInt();
                if (vernum)
                    --vernum;
                shortver.replace(verpos, shortver.length() - verpos, QString::number(vernum));
                // first version
                filever[file].first = shortver;
            }
        }
    }

    if ((m_settings.diffType == GraphicalDiff) && (filever.count() == 1)) {
        QStringPair pair(filever.values().at(0));
        diffGraphical(pair.first, pair.second);
        return;
    }
    rmdir(QDir::tempPath() + QLatin1String("/ccdiff/") + activity);
    QDir(QDir::tempPath()).rmpath(QLatin1String("ccdiff/") + activity);
    m_diffPrefix = activity;
1145 1146 1147
    const FileVerIt fend = filever.end();
    for (FileVerIt it = filever.begin(); it != fend; ++it) {
        QStringPair &pair(it.value());
Orgad Shaneh's avatar
Orgad Shaneh committed
1148 1149 1150 1151 1152 1153
        if (pair.first.contains(QLatin1String("CHECKEDOUT")))
            pair.first = ccGetPredecessor(pair.first.left(pair.first.indexOf(QLatin1String("@@"))));
        result += diffExternal(pair.first, pair.second, true);
    }
    m_diffPrefix.clear();
    const QString title = QString::fromLatin1("%1.patch").arg(activity);
1154
    IEditor *editor = showOutputInEditor(title, result, VcsBase::DiffOutput, activity, 0);
1155
    setWorkingDirectory(editor, topLevel);
Orgad Shaneh's avatar
Orgad Shaneh committed
1156 1157 1158 1159 1160 1161
}

void ClearCasePlugin::diffCurrentFile()
{
    const VcsBase::VcsBasePluginState state = currentState();
    QTC_ASSERT(state.hasFile(), return);
1162
    ccDiffWithPred(state.topLevel(), QStringList(state.relativeCurrentFile()));
Orgad Shaneh's avatar
Orgad Shaneh committed
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
}

void ClearCasePlugin::startCheckInCurrentFile()
{
    const VcsBase::VcsBasePluginState state = currentState();
    QTC_ASSERT(state.hasFile(), return);
    QString nativeFile = QDir::toNativeSeparators(state.relativeCurrentFile());
    startCheckIn(state.currentFileTopLevel(), QStringList(nativeFile));
}

void ClearCasePlugin::startCheckInAll()
{
    const VcsBase::VcsBasePluginState state = currentState();
    QTC_ASSERT(state.hasTopLevel(), return);
    QString topLevel = state.topLevel();
    QStringList files;
1179 1180
    for (StatusMap::ConstIterator iterator = m_statusMap->constBegin();
         iterator != m_statusMap->constEnd();
Orgad Shaneh's avatar
Orgad Shaneh committed
1181 1182 1183 1184 1185
         ++iterator)
    {
        if (iterator.value().status == FileStatus::CheckedOut)
            files.append(QDir::toNativeSeparators(iterator.key()));
    }
1186
    files.sort();
Orgad Shaneh's avatar
Orgad Shaneh committed
1187 1188 1189 1190 1191
    startCheckIn(topLevel, files);
}

void ClearCasePlugin::startCheckInActivity()
{
1192 1193
    QTC_ASSERT(isUcm(), return);

Orgad Shaneh's avatar
Orgad Shaneh committed
1194 1195
    const VcsBase::VcsBasePluginState state = currentState();
    QTC_ASSERT(state.hasProject(), return);
1196

Orgad Shaneh's avatar
Orgad Shaneh committed
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
    QDialog dlg;
    QVBoxLayout *layout = new QVBoxLayout(&dlg);
    ActivitySelector *actSelector = new ActivitySelector(&dlg);
    QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, &dlg);
    connect(buttonBox, SIGNAL(accepted()), &dlg, SLOT(accept()));
    connect(buttonBox, SIGNAL(rejected()), &dlg, SLOT(reject()));
    layout->addWidget(actSelector);
    layout->addWidget(buttonBox);
    dlg.setWindowTitle(tr("Check In Activity"));
    if (!dlg.exec())
        return;
1208

Orgad Shaneh's avatar
Orgad Shaneh committed
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
    QString topLevel = state.topLevel();
    int topLevelLen = topLevel.length();
    QStringList versions = ccGetActivityVersions(topLevel, actSelector->activity());
    QStringList files;
    QString last;
    foreach (const QString &version, versions) {
        int atatpos = version.indexOf(QLatin1String("@@"));
        if ((atatpos != -1) && (version.indexOf(QLatin1String("CHECKEDOUT"), atatpos) != -1)) {
            QString file = version.left(atatpos);
            if (file != last)
                files.append(file.mid(topLevelLen+1));
            last = file;
        }
    }
1223
    files.sort();
1224
    startCheckIn(topLevel, files);
Orgad Shaneh's avatar
Orgad Shaneh committed
1225 1226 1227 1228 1229 1230 1231
}

/* Start check in of files of a single repository by displaying
 * template and files in a submit editor. On closing, the real
 * check in will start. */
void ClearCasePlugin::startCheckIn(const QString &workingDir, const QStringList &files)
{
1232
    if (raiseSubmitEditor())
Orgad Shaneh's avatar
Orgad Shaneh committed
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
        return;
    VcsBase::VcsBaseOutputWindow *outputwindow = VcsBase::VcsBaseOutputWindow::instance();

    if (isCheckInEditorOpen()) {
        outputwindow->appendWarning(tr("Another check in is currently being executed."));
        return;
    }

    // Get list of added/modified/deleted files
    if (files.empty()) {
        outputwindow->appendWarning(tr("There are no modified files."));
        return;
    }
    // Create a new submit change file containing the submit template
    Utils::TempFileSaver saver;
    saver.setAutoRemove(false);
    // TODO: Retrieve submit template from
    const QString submitTemplate;
    // Create a submit
    saver.write(submitTemplate.toUtf8());
    if (!saver.finalize()) {
        VcsBase::VcsBaseOutputWindow::instance()->appendError(saver.errorString());
        return;
    }
    m_checkInMessageFileName = saver.fileName();
1258
    m_checkInView = workingDir;
Orgad Shaneh's avatar
Orgad Shaneh committed
1259
    // Create a submit editor and set file list
1260
    ClearCaseSubmitEditor *editor = openClearCaseSubmitEditor(m_checkInMessageFileName, m_viewData.isUcm);
1261
    setSubmitEditor(editor);
Orgad Shaneh's avatar
Orgad Shaneh committed
1262
    editor->setStatusList(files);
1263

1264
    if (m_viewData.isUcm && (files.size() == 1)) {
Orgad Shaneh's avatar
Orgad Shaneh committed
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
        QString activity = ccGetFileActivity(workingDir, files.first());
        editor->submitEditorWidget()->setActivity(activity);
    }
}

void ClearCasePlugin::historyCurrentFile()
{
    const VcsBase::VcsBasePluginState state = currentState();
    QTC_ASSERT(state.hasFile(), return);
    history(state.currentFileTopLevel(), QStringList(state.relativeCurrentFile()), true);
}

void ClearCasePlugin::updateView()
{
    const VcsBase::VcsBasePluginState state = currentState();
    QTC_ASSERT(state.hasTopLevel(), return);
    ccUpdate(state.topLevel());
}

void ClearCasePlugin::history(const QString &workingDir,
                               const QStringList &files,
                               bool enableAnnotationContextMenu)
{
    QTextCodec *codec = VcsBase::VcsBaseEditorWidget::getCodec(workingDir, files);
    // no need for temp file
    QStringList args(QLatin1String("lshistory"));
    if (m_settings.historyCount > 0)
        args << QLatin1String("-last") << QString::number(m_settings.historyCount);
    if (!m_intStream.isEmpty())
        args << QLatin1String("-branch") << m_intStream;
    foreach (const QString &file, files)
        args.append(QDir::toNativeSeparators(file));

    const ClearCaseResponse response =
            runCleartool(workingDir, args, m_settings.timeOutMS(),
                   0, 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

    const QString id = VcsBase::VcsBaseEditorWidget::getTitleId(workingDir, files);
    const QString tag = VcsBase::VcsBaseEditorWidget::editorTag(VcsBase::LogOutput, workingDir, files);
1309
    if (IEditor *editor = VcsBase::VcsBaseEditorWidget::locateEditorByTag(tag)) {
1310
        editor->document()->setContents(response.stdOut.toUtf8());
1311
        EditorManager::activateEditor(editor);
Orgad Shaneh's avatar
Orgad Shaneh committed
1312 1313 1314
    } else {
        const QString title = QString::fromLatin1("cc history %1").arg(id);
        const QString source = VcsBase::VcsBaseEditorWidget::getSource(workingDir, files);
1315
        IEditor *newEditor = showOutputInEditor(title, response.stdOut, VcsBase::LogOutput, source, codec);
Orgad Shaneh's avatar
Orgad Shaneh committed
1316 1317 1318 1319 1320 1321 1322 1323
        VcsBase::VcsBaseEditorWidget::tagEditor(newEditor, tag);
        if (enableAnnotationContextMenu)
            VcsBase::VcsBaseEditorWidget::getVcsBaseEditor(newEditor)->setFileLogAnnotateEnabled(true);
    }
}

void ClearCasePlugin::viewStatus()
{
1324 1325 1326
    if (m_viewData.name.isEmpty())
        m_viewData = ccGetView(m_topLevel);
    QTC_ASSERT(!m_viewData.name.isEmpty() && !m_settings.disableIndexer, return);
Orgad Shaneh's avatar
Orgad Shaneh committed
1327
    VcsBase::VcsBaseOutputWindow *outputwindow = VcsBase::VcsBaseOutputWindow::instance();
1328 1329
    outputwindow->appendCommand(QLatin1String("Indexed files status (C=Checked Out, "
                                              "H=Hijacked, ?=Missing)"));
Orgad Shaneh's avatar
Orgad Shaneh committed
1330
    bool anymod = false;
1331 1332
    for (StatusMap::ConstIterator it = m_statusMap->constBegin();
         it != m_statusMap->constEnd();
Orgad Shaneh's avatar
Orgad Shaneh committed
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371
         ++it)
    {
        char cstat = 0;
        switch (it.value().status) {
            case FileStatus::CheckedOut: cstat = 'C'; break;
            case FileStatus::Hijacked:   cstat = 'H'; break;
            case FileStatus::Missing:    cstat = '?'; break;
            default: break;
        }
        if (cstat) {
            outputwindow->append(QString::fromLatin1("%1    %2\n")
                           .arg(cstat)
                           .arg(QDir::toNativeSeparators(it.key())));
            anymod = true;
        }
    }
    if (!anymod)
        outputwindow->appendWarning(QLatin1String("No modified files found!"));
}

void ClearCasePlugin::ccUpdate(const QString &workingDir, const QStringList &relativePaths)
{
    QStringList args(QLatin1String("update"));
    args << QLatin1String("-noverwrite");
    if (!relativePaths.isEmpty())
        args.append(relativePaths);
        const ClearCaseResponse response =
                runCleartool(workingDir, args, m_settings.longTimeOutMS(), ShowStdOutInLogWindow);
    if (!response.error)
        clearCaseControl()->emitRepositoryChanged(workingDir);
}

void ClearCasePlugin::annotateCurrentFile()
{
    const VcsBase::VcsBasePluginState state = currentState();
    QTC_ASSERT(state.hasFile(), return);
    vcsAnnotate(state.currentFileTopLevel(), state.relativeCurrentFile());
}

1372 1373 1374 1375
void ClearCasePlugin::annotateVersion(const QString &workingDirectory,
                                      const QString &file,
                                      const QString &revision,
                                      int lineNr)
Orgad Shaneh's avatar
Orgad Shaneh committed
1376
{
1377
    vcsAnnotate(workingDirectory, file, revision, lineNr);
Orgad Shaneh's avatar
Orgad Shaneh committed
1378 1379 1380 1381 1382 1383
}

void ClearCasePlugin::vcsAnnotate(const QString &workingDir, const QString &file,
                                const QString &revision /* = QString() */,
                                int lineNumber /* = -1 */) const
{
1384
    if (Constants::debug)
Orgad Shaneh's avatar
Orgad Shaneh committed
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
        qDebug() << Q_FUNC_INFO << file;

    QTextCodec *codec = VcsBase::VcsBaseEditorWidget::getCodec(file);

    // Determine id
    QString id = file;
    if (!revision.isEmpty())
        id += QLatin1String("@@") + revision;

    QStringList args(QLatin1String("annotate"));
    args << QLatin1String("-nco") << QLatin1String("-f");
    args << QLatin1String("-fmt") << QLatin1String("%-14.14Sd %-8.8u | ");
    args << QLatin1String("-out") << QLatin1String("-");
    args.append(QDir::toNativeSeparators(id));

    const ClearCaseResponse response =
            runCleartool(workingDir, args, m_settings.timeOutMS(), 0, 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
    const QString source = workingDir + QLatin1Char('/') + file;
    if (lineNumber <= 0)
        lineNumber = VcsBase::VcsBaseEditorWidget::lineNumberOfCurrentEditor(source);

    QString headerSep(QLatin1String("-------------------------------------------------"));
    int pos = qMax(0, response.stdOut.indexOf(headerSep));
    // there are 2 identical headerSep lines - skip them
    int dataStart = response.stdOut.indexOf(QLatin1Char('\n'), pos) + 1;
    dataStart = response.stdOut.indexOf(QLatin1Char('\n'), dataStart) + 1;
    QString res;
    QTextStream stream(&res, QIODevice::WriteOnly | QIODevice::Text);
    stream << response.stdOut.mid(dataStart) << headerSep << QLatin1Char('\n')
           << headerSep << QLatin1Char('\n') << response.stdOut.left(pos);
    const QStringList files = QStringList(file);
    const QString tag = VcsBase::VcsBaseEditorWidget::editorTag(VcsBase::AnnotateOutput, workingDir, files);
1422
    if (IEditor *editor = VcsBase::VcsBaseEditorWidget::locateEditorByTag(tag)) {
1423
        editor->document()->setContents(res.toUtf8());
Orgad Shaneh's avatar
Orgad Shaneh committed
1424
        VcsBase::<