aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/git/gerrit/gerritpushdialog.cpp
blob: bd5cd09b1dcfff2c08cde8449daa45afb813a307 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
/****************************************************************************
**
** Copyright (C) 2016 Petar Perisin.
** Contact: petar.perisin@gmail.com
**
** This file is part of Qt Creator.
**
** 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 The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/

#include "gerritpushdialog.h"
#include "ui_gerritpushdialog.h"
#include "branchcombobox.h"

#include "../gitclient.h"
#include "../gitconstants.h"

#include <utils/icon.h>
#include <utils/stringutils.h>
#include <utils/theme/theme.h>

#include <QApplication>
#include <QDateTime>
#include <QDir>
#include <QPushButton>
#include <QRegularExpressionValidator>
#include <QVersionNumber>

using namespace Git::Internal;

namespace Gerrit {
namespace Internal {

static const int ReasonableDistance = 100;

class PushItemDelegate : public IconItemDelegate
{
public:
    PushItemDelegate(LogChangeWidget *widget)
        : IconItemDelegate(widget, Utils::Icon(":/git/images/arrowup.png"))
    {
    }

protected:
    bool hasIcon(int row) const override
    {
        return row >= currentRow();
    }
};

QString GerritPushDialog::determineRemoteBranch(const QString &localBranch)
{
    const QString earliestCommit = m_ui->commitView->earliestCommit();

    QString output;
    QString error;

    if (!GitClient::instance()->synchronousBranchCmd(
                m_workingDir, {"-r", "--contains", earliestCommit + '^'}, &output, &error)) {
        return QString();
    }
    const QString head = "/HEAD";
    const QStringList refs = output.split('\n');

    QString remoteTrackingBranch;
    if (localBranch != "HEAD")
        remoteTrackingBranch = GitClient::instance()->synchronousTrackingBranch(m_workingDir, localBranch);

    QString remoteBranch;
    for (const QString &reference : refs) {
        const QString ref = reference.trimmed();
        if (ref.contains(head) || ref.isEmpty())
            continue;

        if (remoteBranch.isEmpty())
            remoteBranch = ref;

        // Prefer remote tracking branch if it exists and contains the latest remote commit
        if (ref == remoteTrackingBranch)
            return ref;
    }
    return remoteBranch;
}

void GerritPushDialog::initRemoteBranches()
{
    QString output;
    const QString head = "/HEAD";

    QString remotesPrefix("refs/remotes/");
    if (!GitClient::instance()->synchronousForEachRefCmd(
                m_workingDir, {"--format=%(refname)\t%(committerdate:raw)", remotesPrefix}, &output)) {
        return;
    }

    const QStringList refs = output.split("\n");
    for (const QString &reference : refs) {
        QStringList entries = reference.split('\t');
        if (entries.count() < 2 || entries.first().endsWith(head))
            continue;
        const QString ref = entries.at(0).mid(remotesPrefix.size());
        int refBranchIndex = ref.indexOf('/');
        qint64 timeT = entries.at(1).leftRef(entries.at(1).indexOf(' ')).toLongLong();
        BranchDate bd(ref.mid(refBranchIndex + 1), QDateTime::fromSecsSinceEpoch(timeT).date());
        m_remoteBranches.insertMulti(ref.left(refBranchIndex), bd);
    }
    m_ui->remoteComboBox->updateRemotes(false);
}

GerritPushDialog::GerritPushDialog(const QString &workingDir, const QString &reviewerList,
                                   QSharedPointer<GerritParameters> parameters, QWidget *parent) :
    QDialog(parent),
    m_workingDir(workingDir),
    m_ui(new Ui::GerritPushDialog)
{
    m_ui->setupUi(this);
    m_ui->repositoryLabel->setText(QDir::toNativeSeparators(workingDir));
    m_ui->remoteComboBox->setRepository(workingDir);
    m_ui->remoteComboBox->setParameters(parameters);
    m_ui->remoteComboBox->setAllowDups(true);

    auto delegate = new PushItemDelegate(m_ui->commitView);
    delegate->setParent(this);

    initRemoteBranches();

    if (m_ui->remoteComboBox->isEmpty()) {
        m_initErrorMessage = tr("Cannot find a Gerrit remote. Add one and try again.");
        return;
    }

    m_ui->localBranchComboBox->init(workingDir);
    connect(m_ui->localBranchComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &GerritPushDialog::updateCommits);

    connect(m_ui->targetBranchComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &GerritPushDialog::setChangeRange);

    connect(m_ui->targetBranchComboBox, &QComboBox::currentTextChanged,
            this, &GerritPushDialog::validate);

    updateCommits(m_ui->localBranchComboBox->currentIndex());
    onRemoteChanged(true);

    QRegularExpressionValidator *noSpaceValidator = new QRegularExpressionValidator(QRegularExpression("^\\S+$"), this);
    m_ui->reviewersLineEdit->setText(reviewerList);
    m_ui->reviewersLineEdit->setValidator(noSpaceValidator);
    m_ui->topicLineEdit->setValidator(noSpaceValidator);
    m_ui->wipCheckBox->setCheckState(Qt::PartiallyChecked);

    connect(m_ui->remoteComboBox, &GerritRemoteChooser::remoteChanged,
            this, [this] { onRemoteChanged(); });
}

GerritPushDialog::~GerritPushDialog()
{
    delete m_ui;
}

QString GerritPushDialog::selectedCommit() const
{
    return m_ui->commitView->commit();
}

QString GerritPushDialog::calculateChangeRange(const QString &branch)
{
    QString remote = selectedRemoteName();
    remote += '/';
    remote += selectedRemoteBranchName();

    QString number;
    QString error;

    GitClient::instance()->synchronousRevListCmd(
                m_workingDir, { remote + ".." + branch, "--count" }, &number, &error);

    number.chop(1);
    return number;
}

void GerritPushDialog::setChangeRange()
{
    if (m_ui->targetBranchComboBox->itemData(m_ui->targetBranchComboBox->currentIndex()) == 1) {
        setRemoteBranches(true);
        return;
    }
    const QString remoteBranchName = selectedRemoteBranchName();
    if (remoteBranchName.isEmpty())
        return;
    const QString branch = m_ui->localBranchComboBox->currentText();
    const QString range = calculateChangeRange(branch);
    if (range.isEmpty()) {
        m_ui->infoLabel->hide();
        return;
    }
    m_ui->infoLabel->show();
    const QString remote = selectedRemoteName() + '/' + remoteBranchName;
    QString labelText = tr("Number of commits between %1 and %2: %3").arg(branch, remote, range);
    const int currentRange = range.toInt();
    QPalette palette = QApplication::palette();
    if (currentRange > ReasonableDistance) {
        const QColor errorColor = Utils::creatorTheme()->color(Utils::Theme::TextColorError);
        palette.setColor(QPalette::WindowText, errorColor);
        palette.setColor(QPalette::ButtonText, errorColor);
        labelText.append("\n" + tr("Are you sure you selected the right target branch?"));
    }
    m_ui->infoLabel->setPalette(palette);
    m_ui->targetBranchComboBox->setPalette(palette);
    m_ui->infoLabel->setText(labelText);
}

static bool versionSupportsWip(const QString &version)
{
    return QVersionNumber::fromString(version) >= QVersionNumber(2, 15);
}

void GerritPushDialog::onRemoteChanged(bool force)
{
    setRemoteBranches();
    const QString version = m_ui->remoteComboBox->currentServer().version;
    const bool supportsWip = versionSupportsWip(version);
    if (!force && supportsWip == m_currentSupportsWip)
        return;
    m_currentSupportsWip = supportsWip;
    m_ui->wipCheckBox->setEnabled(supportsWip);
    if (supportsWip) {
        m_ui->wipCheckBox->setToolTip(tr("Checked - Mark change as WIP.\n"
                                         "Unchecked - Mark change as ready for review.\n"
                                         "Partially checked - Do not change current state."));
        m_ui->draftCheckBox->setTristate(true);
        if (m_ui->draftCheckBox->checkState() != Qt::Checked)
            m_ui->draftCheckBox->setCheckState(Qt::PartiallyChecked);
        m_ui->draftCheckBox->setToolTip(tr("Checked - Mark change as private.\n"
                                           "Unchecked - Remove mark.\n"
                                           "Partially checked - Do not change current state."));
    } else {
        m_ui->wipCheckBox->setToolTip(tr("Supported on Gerrit 2.15 and later."));
        m_ui->draftCheckBox->setTristate(false);
        if (m_ui->draftCheckBox->checkState() != Qt::Checked)
            m_ui->draftCheckBox->setCheckState(Qt::Unchecked);
        m_ui->draftCheckBox->setToolTip(tr("Checked - The change is a draft.\n"
                                           "Unchecked - The change is not a draft."));
    }
}

QString GerritPushDialog::initErrorMessage() const
{
    return m_initErrorMessage;
}

QString GerritPushDialog::pushTarget() const
{
    QStringList options;
    QString target = selectedCommit();
    if (target.isEmpty())
        target = "HEAD";
    target += ":refs/";
    if (versionSupportsWip(m_ui->remoteComboBox->currentServer().version)) {
        target += "for";
        const Qt::CheckState draftState = m_ui->draftCheckBox->checkState();
        const Qt::CheckState wipState = m_ui->wipCheckBox->checkState();
        if (draftState == Qt::Checked)
            options << "private";
        else if (draftState == Qt::Unchecked)
            options << "remove-private";

        if (wipState == Qt::Checked)
            options << "wip";
        else if (wipState == Qt::Unchecked)
            options << "ready";
    } else {
        target += QLatin1String(m_ui->draftCheckBox->isChecked() ? "drafts" : "for");
    }
    target += '/' + selectedRemoteBranchName();
    const QString topic = selectedTopic();
    if (!topic.isEmpty())
        target += '/' + topic;

    const QStringList reviewersInput = reviewers().split(',', Utils::SkipEmptyParts);
    for (const QString &reviewer : reviewersInput)
        options << "r=" + reviewer;

    if (!options.isEmpty())
        target += '%' + options.join(',');
    return target;
}

void GerritPushDialog::storeTopic()
{
    const QString branch = m_ui->localBranchComboBox->currentText();
    GitClient::instance()->setConfigValue(
                m_workingDir, QString("branch.%1.topic").arg(branch), selectedTopic());
}

void GerritPushDialog::setRemoteBranches(bool includeOld)
{
    {
        QSignalBlocker blocker(m_ui->targetBranchComboBox);
        m_ui->targetBranchComboBox->clear();

        const QString remoteName = selectedRemoteName();
        if (!m_remoteBranches.contains(remoteName)) {
            const QStringList remoteBranches =
                    GitClient::instance()->synchronousRepositoryBranches(remoteName, m_workingDir);
            for (const QString &branch : remoteBranches)
                m_remoteBranches.insertMulti(remoteName, qMakePair(branch, QDate()));
            if (remoteBranches.isEmpty()) {
                m_ui->targetBranchComboBox->setEditable(true);
                m_ui->targetBranchComboBox->setToolTip(
                            tr("No remote branches found. This is probably the initial commit."));
                if (QLineEdit *lineEdit = m_ui->targetBranchComboBox->lineEdit())
                    lineEdit->setPlaceholderText(tr("Branch name"));
            }
        }

        int i = 0;
        bool excluded = false;
        const QList<BranchDate> remoteBranches = m_remoteBranches.values(remoteName);
        for (const BranchDate &bd : remoteBranches) {
            const bool isSuggested = bd.first == m_suggestedRemoteBranch;
            if (includeOld || isSuggested || !bd.second.isValid()
                    || bd.second.daysTo(QDate::currentDate()) <= Git::Constants::OBSOLETE_COMMIT_AGE_IN_DAYS) {
                m_ui->targetBranchComboBox->addItem(bd.first);
                if (isSuggested)
                    m_ui->targetBranchComboBox->setCurrentIndex(i);
                ++i;
            } else {
                excluded = true;
            }
        }
        if (excluded)
            m_ui->targetBranchComboBox->addItem(tr("... Include older branches ..."), 1);
        setChangeRange();
    }
    validate();
}

void GerritPushDialog::updateCommits(int index)
{
    const QString branch = m_ui->localBranchComboBox->itemText(index);
    m_hasLocalCommits = m_ui->commitView->init(m_workingDir, branch, LogChangeWidget::Silent);
    QString topic = GitClient::instance()->readConfigValue(
                m_workingDir, QString("branch.%1.topic").arg(branch));
    if (!topic.isEmpty())
        m_ui->topicLineEdit->setText(topic);

    const QString remoteBranch = determineRemoteBranch(branch);
    if (!remoteBranch.isEmpty()) {
        const int slash = remoteBranch.indexOf('/');

        m_suggestedRemoteBranch = remoteBranch.mid(slash + 1);
        const QString remote = remoteBranch.left(slash);

        if (!m_ui->remoteComboBox->setCurrentRemote(remote))
            onRemoteChanged();
    }
    validate();
}

void GerritPushDialog::validate()
{
    const bool valid = m_hasLocalCommits && !selectedRemoteBranchName().isEmpty();
    m_ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(valid);
}

QString GerritPushDialog::selectedRemoteName() const
{
    return m_ui->remoteComboBox->currentRemoteName();
}

QString GerritPushDialog::selectedRemoteBranchName() const
{
    return m_ui->targetBranchComboBox->currentText();
}

QString GerritPushDialog::selectedTopic() const
{
    return m_ui->topicLineEdit->text().trimmed();
}

QString GerritPushDialog::reviewers() const
{
    return m_ui->reviewersLineEdit->text();
}

} // namespace Internal
} // namespace Gerrit