gerritmodel.cpp 31.4 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
2
**
3
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
7
**
hjk's avatar
hjk committed
8 9 10 11 12 13 14
** 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.
15 16
**
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17 18 19 20 21 22 23 24 25
** 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
26 27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
29 30 31

#include "gerritmodel.h"
#include "gerritparameters.h"
32 33
#include "../gitplugin.h"
#include "../gitclient.h"
34 35 36 37 38 39 40 41 42 43

#include <coreplugin/progressmanager/progressmanager.h>
#include <coreplugin/progressmanager/futureprogress.h>
#include <vcsbase/vcsbaseoutputwindow.h>
#include <utils/synchronousprocess.h>

#include <QStringList>
#include <QProcess>
#include <QVariant>
#include <QTextStream>
44 45
#include <QMessageBox>
#include <QPushButton>
46 47
#include <QDebug>
#include <QScopedPointer>
48 49
#include <QTimer>
#include <QApplication>
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
#if QT_VERSION >= 0x050000
#  include <QJsonDocument>
#  include <QJsonValue>
#  include <QJsonArray>
#  include <QJsonObject>
#else
#  include <utils/json.h>
#  include <utils/qtcassert.h>
#endif

enum { debug = 0 };

namespace Gerrit {
namespace Internal {

65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
QDebug operator<<(QDebug d, const GerritApproval &a)
{
    d.nospace() << a.reviewer << " :" << a.approval << " ("
                << a.type << ", " << a.description << ')';
    return d;
}

// Sort approvals by type and reviewer
bool gerritApprovalLessThan(const GerritApproval &a1, const GerritApproval &a2)
{
    return a1.type.compare(a2.type) < 0 || a1.reviewer.compare(a2.reviewer) < 0;
}

QDebug operator<<(QDebug d, const GerritPatchSet &p)
{
    d.nospace() << " Patch set: " << p.ref << ' ' << p.patchSetNumber
                << ' ' << p.approvals;
    return d;
}

QDebug operator<<(QDebug d, const GerritChange &c)
{
    d.nospace() << c.title << " by " << c.email
                << ' ' << c.lastUpdated << ' ' <<  c.currentPatchSet;
    return d;
}

92 93 94 95 96 97 98 99 100 101
// Format default Url for a change
static inline QString defaultUrl(const QSharedPointer<GerritParameters> &p, int gerritNumber)
{
    QString result = p->https ? QLatin1String("https://") : QLatin1String("http://");
    result += p->host;
    result += QLatin1Char('/');
    result += QString::number(gerritNumber);
    return result;
}

102 103 104
// Format (sorted) approvals as separate HTML table
// lines by type listing the revievers:
// "<tr><td>Code Review</td><td>John Doe: -1, ...</tr><tr>...Sanity Review: ...".
105
QString GerritPatchSet::approvalsToHtml() const
106
{
107 108 109
    if (approvals.isEmpty())
        return QString();

110
    QString result;
111 112 113 114 115 116 117 118 119 120 121 122
    QTextStream str(&result);
    QString lastType;
    foreach (const GerritApproval &a, approvals) {
        if (a.type != lastType) {
            if (!lastType.isEmpty())
                str << "</tr>\n";
            str << "<tr><td>"
                << (a.description.isEmpty() ? a.type : a.description)
                << "</td><td>";
            lastType = a.type;
        } else {
            str << ", ";
123
        }
124 125 126 127
        str << a.reviewer;
        if (!a.email.isEmpty())
            str << " <a href=\"mailto:" << a.email << "\">" << a.email << "</a>";
        str << ": " << forcesign << a.approval << noforcesign;
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
    }
    str << "</tr>\n";
    return result;
}

// Determine total approval level. Negative values take preference
// and stay.
static inline void applyApproval(int approval, int *total)
{
    if (approval < *total || (*total >= 0 && approval > *total))
        *total = approval;
}

// Format the approvals similar to the columns in the Web view
// by a type character followed by the approval level: "C: -2, S: 1"
QString GerritPatchSet::approvalsColumn() const
{
    typedef QMap<QChar, int> TypeReviewMap;
    typedef TypeReviewMap::iterator TypeReviewMapIterator;
    typedef TypeReviewMap::const_iterator TypeReviewMapConstIterator;

    QString result;
    if (approvals.isEmpty())
        return result;

    TypeReviewMap reviews; // Sort approvals into a map by type character
    foreach (const GerritApproval &a, approvals) {
        if (a.type != QLatin1String("STGN")) { // Qt-Project specific: Ignore "STGN" (Staged)
            const QChar typeChar = a.type.at(0);
            TypeReviewMapIterator it = reviews.find(typeChar);
            if (it == reviews.end())
                it = reviews.insert(typeChar, 0);
            applyApproval(a.approval, &it.value());
        }
    }

    QTextStream str(&result);
    const TypeReviewMapConstIterator cend = reviews.constEnd();
    for (TypeReviewMapConstIterator it = reviews.constBegin(); it != cend; ++it) {
        if (!result.isEmpty())
            str << ' ';
169
        str << it.key() << ": " << forcesign << it.value() << noforcesign;
170 171 172 173
    }
    return result;
}

174 175
bool GerritPatchSet::hasApproval(const QString &userName) const
{
176 177
    foreach (const GerritApproval &a, approvals)
        if (a.reviewer == userName)
178 179 180 181 182 183
            return true;
    return false;
}

int GerritPatchSet::approvalLevel() const
{
184 185 186 187
    int value = 0;
    foreach (const GerritApproval &a, approvals)
        applyApproval(a.approval, &value);
    return value;
188 189
}

190
QString GerritChange::toHtml() const
191
{
192
    // Keep in sync with list model headers.
193
    static const QString format = GerritModel::tr(
194 195
       "<html><head/><body><table>"
       "<tr><td>Subject</td><td>%1</td></tr>"
Friedemann Kleint's avatar
Friedemann Kleint committed
196
       "<tr><td>Number</td><td><a href=\"%11\">%2</a></td></tr>"
197
       "<tr><td>Owner</td><td>%3 <a href=\"mailto:%4\">%4</a></td></tr>"
198 199 200 201
       "<tr><td>Project</td><td>%5 (%6)</td></tr>"
       "<tr><td>Status</td><td>%7, %8</td></tr>"
       "<tr><td>Patch set</td><td>%9</td></tr>"
       "%10"
202
       "<tr><td>URL</td><td><a href=\"%11\">%11</a></td></tr>"
203 204 205
       "</table></body></html>");
    return format.arg(title).arg(number).arg(owner, email, project, branch)
           .arg(status, lastUpdated.toString(Qt::DefaultLocaleShortDate))
206
           .arg(currentPatchSet.patchSetNumber)
207
           .arg(currentPatchSet.approvalsToHtml(), url);
208 209 210 211 212 213 214 215
}

QString GerritChange::filterString() const
{
    const QChar blank = QLatin1Char(' ');
    QString result = QString::number(number) + blank + title + blank
            + owner + blank + project + blank
            + branch + blank + status;
216
    foreach (const GerritApproval &a, currentPatchSet.approvals) {
217
        result += blank;
218
        result += a.reviewer;
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
    }
    return result;
}

QStringList GerritChange::gitFetchArguments(const QSharedPointer<GerritParameters> &p) const
{
    QStringList arguments;
    const QString url = QLatin1String("ssh://") + p->sshHostArgument()
            + QLatin1Char(':') + QString::number(p->port) + QLatin1Char('/')
            + project;
    arguments << QLatin1String("fetch") << url << currentPatchSet.ref;
    return arguments;
}

// Helper class that runs ssh gerrit queries from a list of query argument
// string lists,
// see http://gerrit.googlecode.com/svn/documentation/2.1.5/cmd-query.html
// In theory, querying uses a continuation/limit protocol, but we assume
// we will never reach a limit with those queries.

class QueryContext : public QObject {
    Q_OBJECT
public:
Orgad Shaneh's avatar
Orgad Shaneh committed
242
    QueryContext(const QStringList &queries,
243 244 245 246 247
                 const QSharedPointer<GerritParameters> &p,
                 QObject *parent = 0);

    ~QueryContext();

248 249
    int currentQuery() const { return m_currentQuery; }

250 251 252 253 254 255 256 257 258 259 260 261
public slots:
    void start();

signals:
    void queryFinished(const QByteArray &);
    void finished();

private slots:
    void processError(QProcess::ProcessError);
    void processFinished(int exitCode, QProcess::ExitStatus);
    void readyReadStandardError();
    void readyReadStandardOutput();
262
    void timeout();
263 264

private:
Orgad Shaneh's avatar
Orgad Shaneh committed
265
    void startQuery(const QString &query);
266 267 268
    void errorTermination(const QString &msg);

    const QSharedPointer<GerritParameters> m_parameters;
Orgad Shaneh's avatar
Orgad Shaneh committed
269
    const QStringList m_queries;
270
    QProcess m_process;
271
    QTimer m_timer;
272 273 274 275 276 277 278
    QString m_binary;
    QByteArray m_output;
    int m_currentQuery;
    QFutureInterface<void> m_progress;
    QStringList m_baseArguments;
};

279 280
enum { timeOutMS = 30000 };

Orgad Shaneh's avatar
Orgad Shaneh committed
281
QueryContext::QueryContext(const QStringList &queries,
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
                           const QSharedPointer<GerritParameters> &p,
                           QObject *parent)
    : QObject(parent)
    , m_parameters(p)
    , m_queries(queries)
    , m_currentQuery(0)
    , m_baseArguments(p->baseCommandArguments())
{
    connect(&m_process, SIGNAL(readyReadStandardError()),
            this, SLOT(readyReadStandardError()));
    connect(&m_process, SIGNAL(readyReadStandardOutput()),
            this, SLOT(readyReadStandardOutput()));
    connect(&m_process, SIGNAL(finished(int,QProcess::ExitStatus)),
            this, SLOT(processFinished(int,QProcess::ExitStatus)));
    connect(&m_process, SIGNAL(error(QProcess::ProcessError)),
            this, SLOT(processError(QProcess::ProcessError)));
298 299
    m_process.setProcessEnvironment(Git::Internal::GitPlugin::instance()->
                                    gitClient()->processEnvironment());
300 301 302 303 304 305 306
    m_progress.setProgressRange(0, m_queries.size());

    // Determine binary and common command line arguments.
    m_baseArguments << QLatin1String("query") << QLatin1String("--current-patch-set")
                    << QLatin1String("--format=JSON");
    m_binary = m_baseArguments.front();
    m_baseArguments.pop_front();
307 308 309 310

    m_timer.setInterval(timeOutMS);
    m_timer.setSingleShot(true);
    connect(&m_timer, SIGNAL(timeout()), this, SLOT(timeout()));
311 312 313 314 315 316
}

QueryContext::~QueryContext()
{
    if (m_progress.isRunning())
        m_progress.reportFinished();
317 318
    if (m_timer.isActive())
        m_timer.stop();
319 320 321 322 323 324
    m_process.disconnect(this);
    Utils::SynchronousProcess::stopProcess(m_process);
}

void QueryContext::start()
{
325
    Core::FutureProgress *fp = Core::ProgressManager::addTask(m_progress.future(), tr("Gerrit"),
326
                                           "gerrit-query");
327 328 329 330 331
    fp->setKeepOnFinish(Core::FutureProgress::HideOnFinish);
    m_progress.reportStarted();
    startQuery(m_queries.front()); // Order: synchronous call to  error handling if something goes wrong.
}

Orgad Shaneh's avatar
Orgad Shaneh committed
332
void QueryContext::startQuery(const QString &query)
333
{
Orgad Shaneh's avatar
Orgad Shaneh committed
334 335
    QStringList arguments = m_baseArguments;
    arguments.push_back(query);
336 337
    VcsBase::VcsBaseOutputWindow::instance()
        ->appendCommand(m_process.workingDirectory(), m_binary, arguments);
338
    m_timer.start();
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
    m_process.start(m_binary, arguments);
    m_process.closeWriteChannel();
}

void QueryContext::errorTermination(const QString &msg)
{
    m_progress.reportCanceled();
    m_progress.reportFinished();
    VcsBase::VcsBaseOutputWindow::instance()->appendError(msg);
    emit finished();
}

void QueryContext::processError(QProcess::ProcessError e)
{
    const QString msg = tr("Error running %1: %2").arg(m_binary, m_process.errorString());
354
    if (e == QProcess::FailedToStart)
355
        errorTermination(msg);
356
    else
357 358 359 360 361
        VcsBase::VcsBaseOutputWindow::instance()->appendError(msg);
}

void QueryContext::processFinished(int exitCode, QProcess::ExitStatus es)
{
362 363
    if (m_timer.isActive())
        m_timer.stop();
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
    if (es != QProcess::NormalExit) {
        errorTermination(tr("%1 crashed.").arg(m_binary));
        return;
    } else if (exitCode) {
        errorTermination(tr("%1 returned %2.").arg(m_binary).arg(exitCode));
        return;
    }
    emit queryFinished(m_output);
    m_output.clear();

    if (++m_currentQuery >= m_queries.size()) {
        m_progress.reportFinished();
        emit finished();
    } else {
        m_progress.setProgressValue(m_currentQuery);
        startQuery(m_queries.at(m_currentQuery));
    }
}

void QueryContext::readyReadStandardError()
{
    VcsBase::VcsBaseOutputWindow::instance()->appendError(QString::fromLocal8Bit(m_process.readAllStandardError()));
}

void QueryContext::readyReadStandardOutput()
{
    m_output.append(m_process.readAllStandardOutput());
}

393 394 395 396 397 398 399 400 401 402
void QueryContext::timeout()
{
    if (m_process.state() != QProcess::Running)
        return;

    QWidget *parent = QApplication::activeModalWidget();
    if (!parent)
        parent = QApplication::activeWindow();
    QMessageBox box(QMessageBox::Question, tr("Timeout"),
                    tr("The gerrit process has not responded within %1s.\n"
403
                       "Most likely this is caused by problems with SSH authentication.\n"
404 405 406
                       "Would you like to terminate it?").
                    arg(timeOutMS / 1000), QMessageBox::NoButton, parent);
    QPushButton *terminateButton = box.addButton(tr("Terminate"), QMessageBox::YesRole);
407
    box.addButton(tr("Keep Running"), QMessageBox::NoRole);
408 409 410 411
    connect(&m_process, SIGNAL(finished(int)), &box, SLOT(reject()));
    box.exec();
    if (m_process.state() != QProcess::Running)
        return;
412
    if (box.clickedButton() == terminateButton)
413
        Utils::SynchronousProcess::stopProcess(m_process);
414
    else
415 416 417
        m_timer.start();
}

418 419 420 421 422
GerritModel::GerritModel(const QSharedPointer<GerritParameters> &p, QObject *parent)
    : QStandardItemModel(0, ColumnCount, parent)
    , m_parameters(p)
    , m_query(0)
{
423 424 425
    QStringList headers; // Keep in sync with GerritChange::toHtml()
    headers << QLatin1String("#") << tr("Subject") << tr("Owner")
            << tr("Updated") << tr("Project")
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
            << tr("Approvals") << tr("Status");
    setHorizontalHeaderLabels(headers);
}

GerritModel::~GerritModel()
{
}

GerritChangePtr GerritModel::change(int row) const
{
    if (row >= 0 && row < rowCount())
        return qvariant_cast<GerritChangePtr>(item(row, 0)->data(GerritChangeRole));
    return GerritChangePtr(new GerritChange);
}

int GerritModel::indexOf(int gerritNumber) const
{
    const int numRows = rowCount();
    for (int r = 0; r < numRows; ++r)
        if (change(r)->number == gerritNumber)
            return r;
    return -1;
}

Orgad Shaneh's avatar
Orgad Shaneh committed
450
void GerritModel::refresh(const QString &query)
451 452 453 454 455 456 457 458 459
{
    if (m_query) {
        qWarning("%s: Another query is still running", Q_FUNC_INFO);
        return;
    }
    clearData();

    // Assemble list of queries

Orgad Shaneh's avatar
Orgad Shaneh committed
460
    QStringList queries;
Orgad Shaneh's avatar
Orgad Shaneh committed
461 462 463 464 465 466 467 468 469 470 471 472 473
    if (!query.trimmed().isEmpty())
        queries.push_back(query);
    else
    {
        const QString statusOpenQuery = QLatin1String("status:open");
        if (m_parameters->user.isEmpty()) {
            queries.push_back(statusOpenQuery);
        } else {
            // Owned by:
            queries.push_back(statusOpenQuery + QLatin1String(" owner:") + m_parameters->user);
            // For Review by:
            queries.push_back(statusOpenQuery + QLatin1String(" reviewer:") + m_parameters->user);
        }
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
    }

    m_query = new QueryContext(queries, m_parameters, this);
    connect(m_query, SIGNAL(queryFinished(QByteArray)),
            this, SLOT(queryFinished(QByteArray)));
    connect(m_query, SIGNAL(finished()),
            this, SLOT(queriesFinished()));
    emit refreshStateChanged(true);
    m_query->start();
}

void GerritModel::clearData()
{
    if (const int rows = rowCount())
        removeRows(0, rows);
}

/* Parse gerrit query Json output.
 * See http://gerrit.googlecode.com/svn/documentation/2.1.5/cmd-query.html
 * Note: The url will be present only if  "canonicalWebUrl" is configured
 * in gerrit.config.
\code
{"project":"qt/qtbase","branch":"master","id":"I6601ca68c427b909680423ae81802f1ed5cd178a",
"number":"24143","subject":"bla","owner":{"name":"Hans Mustermann","email":"hm@acme.com"},
"url":"https://...","lastUpdated":1335127888,"sortKey":"001c8fc300005e4f",
"open":true,"status":"NEW","currentPatchSet":
  {"number":"1","revision":"0a1e40c78ef16f7652472f4b4bb4c0addeafbf82",
   "ref":"refs/changes/43/24143/1",
   "uploader":{"name":"Hans Mustermann","email":"hm@acme.com"},
   "approvals":[{"type":"SRVW","description":"Sanity Review","value":"1",
                 "grantedOn":1335127888,"by":{
                 "name":"Qt Sanity Bot","email":"qt_sanity_bot@ovi.com"}}]}}
\endcode
*/

#if QT_VERSION >= 0x050000
// Qt 5 using the QJsonDocument classes.
Orgad Shaneh's avatar
Orgad Shaneh committed
511 512 513
static bool parseOutput(const QSharedPointer<GerritParameters> &parameters,
                        const QByteArray &output,
                        QList<GerritChangePtr> &result)
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
{
    // The output consists of separate lines containing a document each
    const QString typeKey = QLatin1String("type");
    const QString idKey = QLatin1String("id");
    const QString branchKey = QLatin1String("branch");
    const QString numberKey = QLatin1String("number");
    const QString ownerKey = QLatin1String("owner");
    const QString ownerNameKey = QLatin1String("name");
    const QString ownerEmailKey = QLatin1String("email");
    const QString statusKey = QLatin1String("status");
    const QString projectKey = QLatin1String("project");
    const QString titleKey = QLatin1String("subject");
    const QString urlKey = QLatin1String("url");
    const QString patchSetKey = QLatin1String("currentPatchSet");
    const QString refKey = QLatin1String("ref");
    const QString approvalsKey = QLatin1String("approvals");
    const QString approvalsValueKey = QLatin1String("value");
    const QString approvalsByKey = QLatin1String("by");
    const QString lastUpdatedKey = QLatin1String("lastUpdated");
    const QList<QByteArray> lines = output.split('\n');
534 535 536
    const QString approvalsTypeKey = QLatin1String("type");
    const QString approvalsDescriptionKey = QLatin1String("description");

Orgad Shaneh's avatar
Orgad Shaneh committed
537 538
    bool res = true;
    result.clear();
539 540 541 542 543 544 545 546
    result.reserve(lines.size());

    foreach (const QByteArray &line, lines) {
        if (line.isEmpty())
            continue;
        QJsonParseError error;
        const QJsonDocument doc = QJsonDocument::fromJson(line, &error);
        if (doc.isNull()) {
Orgad Shaneh's avatar
Orgad Shaneh committed
547 548 549 550 551 552
            QString errorMessage = GerritModel::tr("Parse error: '%1' -> %2")
                    .arg(QString::fromLocal8Bit(line))
                    .arg(error.errorString());
            qWarning() << errorMessage;
            VcsBase::VcsBaseOutputWindow::instance()->appendError(errorMessage);
            res = false;
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
            continue;
        }
        GerritChangePtr change(new GerritChange);
        const QJsonObject object = doc.object();
        // Skip stats line: {"type":"stats","rowCount":9,"runTimeMilliseconds":13}
        if (!object.value(typeKey).toString().isEmpty())
            continue;
        // Read current patch set.
        const QJsonObject patchSet = object.value(patchSetKey).toObject();
        change->currentPatchSet.patchSetNumber = qMax(1, patchSet.value(numberKey).toString().toInt());
        change->currentPatchSet.ref = patchSet.value(refKey).toString();
        const QJsonArray approvalsJ = patchSet.value(approvalsKey).toArray();
        const int ac = approvalsJ.size();
        for (int a = 0; a < ac; ++a) {
            const QJsonObject ao = approvalsJ.at(a).toObject();
568
            GerritApproval approval;
569
            const QJsonObject approverO = ao.value(approvalsByKey).toObject();
570 571 572 573 574 575
            approval.reviewer = approverO.value(ownerNameKey).toString();
            approval.email = approverO.value(ownerEmailKey).toString();
            approval.approval = ao.value(approvalsValueKey).toString().toInt();
            approval.type = ao.value(approvalsTypeKey).toString();
            approval.description = ao.value(approvalsDescriptionKey).toString();
            change->currentPatchSet.approvals.push_back(approval);
576
        }
577 578 579
        qStableSort(change->currentPatchSet.approvals.begin(),
                    change->currentPatchSet.approvals.end(),
                    gerritApprovalLessThan);
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
        // Remaining
        change->number = object.value(numberKey).toString().toInt();
        change->url = object.value(urlKey).toString();
        if (change->url.isEmpty()) //  No "canonicalWebUrl" is in gerrit.config.
            change->url = defaultUrl(parameters, change->number);
        change->id = object.value(idKey).toString();
        change->title = object.value(titleKey).toString();
        const QJsonObject ownerJ = object.value(ownerKey).toObject();
        change->owner = ownerJ.value(ownerNameKey).toString();
        change->email = ownerJ.value(ownerEmailKey).toString();
        change->project = object.value(projectKey).toString();
        change->branch = object.value(branchKey).toString();
        change->status =  object.value(statusKey).toString();
        if (const int timeT = qRound(object.value(lastUpdatedKey).toDouble()))
            change->lastUpdated = QDateTime::fromTime_t(timeT);
        if (change->isValid()) {
            result.push_back(change);
        } else {
Orgad Shaneh's avatar
Orgad Shaneh committed
598 599 600 601 602
            qWarning("%s: Parse error: '%s'.", Q_FUNC_INFO, line.constData());
            VcsBase::VcsBaseOutputWindow::instance()
                    ->appendError(GerritModel::tr("Parse error: '%1'")
                                  .arg(QString::fromLocal8Bit(line)));
            res = false;
603 604
        }
    }
Orgad Shaneh's avatar
Orgad Shaneh committed
605
    return res;
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
}
#else // QT_VERSION >= 0x050000
// Qt 4.8 using the Json classes from utils.

static inline int jsonIntMember(Utils::JsonObjectValue *object,
                                const QString &key,
                                int defaultValue = 0)
{
    if (Utils::JsonValue *v = object->member(key)) {
        if (Utils::JsonIntValue *iv = v->toInt())
            return iv->value();
        if (Utils::JsonStringValue *sv = v->toString()) {
            bool ok;
            const int result = sv->value().toInt(&ok);
            if (ok)
                return result;
        }
    }
    return defaultValue;
}

static inline QString jsonStringMember(Utils::JsonObjectValue *object,
                                       const QString &key)
{
    if (Utils::JsonValue *v = object->member(key))
        if (Utils::JsonStringValue *sv = v->toString())
            return sv->value();
    return QString();
}

Orgad Shaneh's avatar
Orgad Shaneh committed
636 637 638
static bool parseOutput(const QSharedPointer<GerritParameters> &parameters,
                                          const QByteArray &output,
                                          QList<GerritChangePtr> &result)
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
{
   // The output consists of separate lines containing a document each
    const QList<QByteArray> lines = output.split('\n');
    const QString typeKey = QLatin1String("type");
    const QString idKey = QLatin1String("id");
    const QString branchKey = QLatin1String("branch");
    const QString numberKey = QLatin1String("number");
    const QString ownerKey = QLatin1String("owner");
    const QString ownerNameKey = QLatin1String("name");
    const QString ownerEmailKey = QLatin1String("email");
    const QString statusKey = QLatin1String("status");
    const QString projectKey = QLatin1String("project");
    const QString titleKey = QLatin1String("subject");
    const QString urlKey = QLatin1String("url");
    const QString patchSetKey = QLatin1String("currentPatchSet");
    const QString refKey = QLatin1String("ref");
    const QString approvalsKey = QLatin1String("approvals");
    const QString approvalsValueKey = QLatin1String("value");
    const QString approvalsByKey = QLatin1String("by");
658 659
    const QString approvalsTypeKey = QLatin1String("type");
    const QString approvalsDescriptionKey = QLatin1String("description");
660
    const QString lastUpdatedKey = QLatin1String("lastUpdated");
Orgad Shaneh's avatar
Orgad Shaneh committed
661 662
    bool res = true;
    result.clear();
663 664
    result.reserve(lines.size());

665 666
    Utils::JsonMemoryPool pool;

667 668 669
    foreach (const QByteArray &line, lines) {
        if (line.isEmpty())
            continue;
670 671
        Utils::JsonValue *objectValue = Utils::JsonValue::create(QString::fromUtf8(line), &pool);
        if (!objectValue) {
Orgad Shaneh's avatar
Orgad Shaneh committed
672 673 674 675 676
            QString errorMessage = GerritModel::tr("Parse error: '%1'")
                    .arg(QString::fromLocal8Bit(line));
            qWarning() << errorMessage;
            VcsBase::VcsBaseOutputWindow::instance()->appendError(errorMessage);
            res = false;
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
            continue;
        }
        Utils::JsonObjectValue *object = objectValue->toObject();
        QTC_ASSERT(object, continue );
        GerritChangePtr change(new GerritChange);
        // Skip stats line: {"type":"stats","rowCount":9,"runTimeMilliseconds":13}
        if (jsonStringMember(object, typeKey) == QLatin1String("stats"))
            continue;
        // Read current patch set.
        if (Utils::JsonValue *patchSetValue = object->member(patchSetKey)) {
            Utils::JsonObjectValue *patchSet = patchSetValue->toObject();
            QTC_ASSERT(patchSet, continue );
            const int n = jsonIntMember(patchSet, numberKey);
            change->currentPatchSet.patchSetNumber = qMax(1, n);
            change->currentPatchSet.ref = jsonStringMember(patchSet, refKey);
            if (Utils::JsonValue *approvalsV = patchSet->member(approvalsKey)) {
                Utils::JsonArrayValue *approvals = approvalsV->toArray();
                QTC_ASSERT(approvals, continue );
                foreach (Utils::JsonValue *c, approvals->elements()) {
                    Utils::JsonObjectValue *oc = c->toObject();
                    QTC_ASSERT(oc, break );
                    const int value = jsonIntMember(oc, approvalsValueKey);
                    QString by;
700
                    QString byMail;
701 702 703 704
                    if (Utils::JsonValue *byV = oc->member(approvalsByKey)) {
                        Utils::JsonObjectValue *byO = byV->toObject();
                        QTC_ASSERT(byO, break );
                        by = jsonStringMember(byO, ownerNameKey);
705
                        byMail = jsonStringMember(byO, ownerEmailKey);
706
                    }
707 708
                    GerritApproval a;
                    a.reviewer = by;
709
                    a.email = byMail;
710 711 712 713
                    a.approval = value;
                    a.type = jsonStringMember(oc, approvalsTypeKey);
                    a.description = jsonStringMember(oc, approvalsDescriptionKey);
                    change->currentPatchSet.approvals.push_back(a);
714
                }
715 716 717
                qStableSort(change->currentPatchSet.approvals.begin(),
                            change->currentPatchSet.approvals.end(),
                            gerritApprovalLessThan);
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
            }
        } // patch set
        // Remaining

        change->number = jsonIntMember(object, numberKey);
        change->url = jsonStringMember(object, urlKey);
        if (change->url.isEmpty()) //  No "canonicalWebUrl" is in gerrit.config.
            change->url = defaultUrl(parameters, change->number);
        change->id = jsonStringMember(object, idKey);
        change->title = jsonStringMember(object, titleKey);
        if (Utils::JsonValue *ownerV = object->member(ownerKey)) {
            Utils::JsonObjectValue *ownerO = ownerV->toObject();
            QTC_ASSERT(ownerO, continue );
            change->owner = jsonStringMember(ownerO, ownerNameKey);
            change->email = jsonStringMember(ownerO, ownerEmailKey);
        }
        change->project = jsonStringMember(object, projectKey);
        change->branch = jsonStringMember(object, branchKey);
        change->status = jsonStringMember(object, statusKey);

        if (const int timeT = jsonIntMember(object, lastUpdatedKey))
            change->lastUpdated = QDateTime::fromTime_t(timeT);
        if (change->isValid()) {
            result.push_back(change);
        } else {
Orgad Shaneh's avatar
Orgad Shaneh committed
743 744 745
            QString errorMessage = GerritModel::tr("Parse error in line '%1'")
                    .arg(QString::fromLocal8Bit(line));
            VcsBase::VcsBaseOutputWindow::instance()->appendError(errorMessage);
746
            qWarning("%s: Parse error in line '%s'.", Q_FUNC_INFO, line.constData());
Orgad Shaneh's avatar
Orgad Shaneh committed
747
            res = false;
748 749
        }
    }
750 751 752 753 754
    if (debug) {
        qDebug() << __FUNCTION__;
        foreach (const GerritChangePtr &p, result)
            qDebug() << *p;
    }
Orgad Shaneh's avatar
Orgad Shaneh committed
755
    return res;
756 757 758 759 760 761 762 763 764 765
}
#endif // QT_VERSION < 0x050000

bool changeDateLessThan(const GerritChangePtr &c1, const GerritChangePtr &c2)
{
    return c1->lastUpdated < c2->lastUpdated;
}

void GerritModel::queryFinished(const QByteArray &output)
{
766
    const QDate today = QDate::currentDate();
Orgad Shaneh's avatar
Orgad Shaneh committed
767 768 769
    QList<GerritChangePtr> changes;
    if (!parseOutput(m_parameters, output, changes))
        emit queryError();
770 771 772 773 774
    qStableSort(changes.begin(), changes.end(), changeDateLessThan);
    foreach (const GerritChangePtr &c, changes) {
        // Avoid duplicate entries for example in the (unlikely)
        // case people do self-reviews.
        if (indexOf(c->number) == -1) {
775 776 777 778
            // Determine the verbose user name from the owner of the first query.
            // It used for marking the changes pending for review in bold.
            if (m_userName.isEmpty() && !m_query->currentQuery())
                m_userName = c->owner;
779 780 781 782 783 784 785 786 787 788 789 790 791
            const QVariant filterV = QVariant(c->filterString());
            const QVariant changeV = qVariantFromValue(c);
            QList<QStandardItem *> row;
            for (int i = 0; i < GerritModel::ColumnCount; ++i) {
                QStandardItem *item = new QStandardItem;
                item->setData(changeV, GerritModel::GerritChangeRole);
                item->setData(filterV, GerritModel::FilterRole);
                item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
                row.append(item);
            }
            row[NumberColumn]->setText(QString::number(c->number));
            row[TitleColumn]->setText(c->title);
            row[OwnerColumn]->setText(c->owner);
792 793 794 795 796 797
            // Shorten columns: Display time if it is today, else date
            const QString dateString = c->lastUpdated.date() == today ?
                c->lastUpdated.time().toString(Qt::SystemLocaleShortDate) :
                c->lastUpdated.date().toString(Qt::SystemLocaleShortDate);
            row[DateColumn]->setText(dateString);

798 799 800 801 802
            QString project = c->project;
            if (c->branch != QLatin1String("master"))
                project += QLatin1String(" (") + c->branch  + QLatin1Char(')');
            row[ProjectColumn]->setText(project);
            row[StatusColumn]->setText(c->status);
803
            row[ApprovalsColumn]->setText(c->currentPatchSet.approvalsColumn());
804 805
            // Mark changes awaiting action using a bold font.
            bool bold = false;
Orgad Shaneh's avatar
Orgad Shaneh committed
806
            if (c->owner == m_userName) { // Owned changes: Review != 0,1. Submit or amend.
807 808
                const int level = c->currentPatchSet.approvalLevel();
                bold = level != 0 && level != 1;
Orgad Shaneh's avatar
Orgad Shaneh committed
809
            } else if (m_query->currentQuery() == 1) { // Changes pending for review: No review yet.
810 811 812 813 814 815 816 817
                bold = !m_userName.isEmpty() && !c->currentPatchSet.hasApproval(m_userName);
            }
            if (bold) {
                QFont font = row.first()->font();
                font.setBold(true);
                for (int i = 0; i < GerritModel::ColumnCount; ++i)
                    row[i]->setFont(font);
            }
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
            appendRow(row);
        }
    }
}

void GerritModel::queriesFinished()
{
    m_query->deleteLater();
    m_query = 0;
    emit refreshStateChanged(false);
}

} // namespace Internal
} // namespace Gerrit

#include "gerritmodel.moc"