aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/gitlab/gitlabclonedialog.cpp
blob: 3a061b9cc574e1cbe6406593280870d7be56895a (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
// Copyright (C) 2022 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "gitlabclonedialog.h"

#include "gitlabprojectsettings.h"
#include "gitlabtr.h"
#include "resultparser.h"

#include <coreplugin/documentmanager.h>
#include <coreplugin/vcsmanager.h>

#include <git/gitclient.h>

#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/projectmanager.h>

#include <utils/algorithm.h>
#include <utils/commandline.h>
#include <utils/environment.h>
#include <utils/fancylineedit.h>
#include <utils/filepath.h>
#include <utils/infolabel.h>
#include <utils/mimeutils.h>
#include <utils/pathchooser.h>
#include <utils/process.h>
#include <utils/qtcassert.h>

#include <vcsbase/vcsbaseplugin.h>
#include <vcsbase/vcscommand.h>

#include <QApplication>
#include <QCheckBox>
#include <QComboBox>
#include <QDialogButtonBox>
#include <QFormLayout>
#include <QHBoxLayout>
#include <QInputDialog>
#include <QMessageBox>
#include <QPlainTextEdit>
#include <QPushButton>
#include <QVBoxLayout>

using namespace Utils;
using namespace VcsBase;

namespace GitLab {

GitLabCloneDialog::GitLabCloneDialog(const Project &project, QWidget *parent)
    : QDialog(parent)
{
    setWindowTitle(Tr::tr("Clone Repository"));
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(new QLabel(Tr::tr("Specify repository URL, checkout path and directory.")));
    QHBoxLayout *centerLayout = new QHBoxLayout;
    QFormLayout *form = new QFormLayout;
    m_repositoryCB = new QComboBox(this);
    m_repositoryCB->addItems({project.sshUrl, project.httpUrl});
    form->addRow(Tr::tr("Repository"), m_repositoryCB);
    m_pathChooser = new PathChooser(this);
    m_pathChooser->setExpectedKind(PathChooser::ExistingDirectory);
    form->addRow(Tr::tr("Path"), m_pathChooser);
    m_directoryLE = new FancyLineEdit(this);
    m_directoryLE->setValidationFunction([this](FancyLineEdit *e, QString *msg) {
        const FilePath fullPath = m_pathChooser->filePath().pathAppended(e->text());
        bool alreadyExists = fullPath.exists();
        if (alreadyExists && msg)
            *msg = Tr::tr("Path \"%1\" already exists.").arg(fullPath.toUserOutput());
        return !alreadyExists;
    });
    form->addRow(Tr::tr("Directory"), m_directoryLE);
    m_submodulesCB = new QCheckBox(this);
    form->addRow(Tr::tr("Recursive"), m_submodulesCB);
    form->addItem(new QSpacerItem(10, 10));
    centerLayout->addLayout(form);
    m_cloneOutput = new QPlainTextEdit(this);
    m_cloneOutput->setReadOnly(true);
    centerLayout->addWidget(m_cloneOutput);
    layout->addLayout(centerLayout);
    m_infoLabel = new InfoLabel(this);
    layout->addWidget(m_infoLabel);
    auto buttons = new QDialogButtonBox(QDialogButtonBox::Cancel, this);
    m_cloneButton = new QPushButton(Tr::tr("Clone"), this);
    buttons->addButton(m_cloneButton, QDialogButtonBox::ActionRole);
    m_cancelButton = buttons->button(QDialogButtonBox::Cancel);
    layout->addWidget(buttons);
    setLayout(layout);

    m_pathChooser->setFilePath(Core::DocumentManager::projectsDirectory());
    auto [host, path, port]
            = GitLabProjectSettings::remotePartsFromRemote(m_repositoryCB->currentText());
    int slashIndex = path.indexOf('/');
    QTC_ASSERT(slashIndex > 0, return);
    m_directoryLE->setText(path.mid(slashIndex + 1));

    connect(m_pathChooser, &PathChooser::textChanged, this, [this] {
        m_directoryLE->validate();
        GitLabCloneDialog::updateUi();
    });
    connect(m_directoryLE, &FancyLineEdit::textChanged, this, &GitLabCloneDialog::updateUi);
    connect(m_cloneButton, &QPushButton::clicked, this, &GitLabCloneDialog::cloneProject);
    connect(m_cancelButton, &QPushButton::clicked,
            this, &GitLabCloneDialog::cancel);
    connect(this, &QDialog::rejected, this, [this]() {
        if (m_commandRunning) {
            cancel();
            QApplication::restoreOverrideCursor();
            return;
        }
    });

    updateUi();
    resize(575, 265);
}

void GitLabCloneDialog::updateUi()
{
    bool pathValid = m_pathChooser->isValid();
    bool directoryValid = m_directoryLE->isValid();
    m_cloneButton->setEnabled(pathValid && directoryValid);
    if (!pathValid) {
        m_infoLabel->setText(m_pathChooser->errorMessage());
        m_infoLabel->setType(InfoLabel::Error);
    } else if (!directoryValid) {
        m_infoLabel->setText(m_directoryLE->errorMessage());
        m_infoLabel->setType(InfoLabel::Error);
    }
    m_infoLabel->setVisible(!pathValid || !directoryValid);
}

void GitLabCloneDialog::cloneProject()
{
    VcsBasePluginPrivate *vc = static_cast<VcsBasePluginPrivate *>(
                Core::VcsManager::versionControl(Id::fromString("G.Git")));
    QTC_ASSERT(vc, return);
    const QStringList extraArgs = m_submodulesCB->isChecked() ? QStringList{ "--recursive" }
                                                              : QStringList{};
    m_command = vc->createInitialCheckoutCommand(m_repositoryCB->currentText(),
                                                 m_pathChooser->absoluteFilePath(),
                                                 m_directoryLE->text(), extraArgs);
    const FilePath workingDirectory = m_pathChooser->absoluteFilePath();
    m_command->addFlags(RunFlags::ProgressiveOutput);
    connect(m_command, &VcsCommand::stdOutText, this, [this](const QString &text) {
        m_cloneOutput->appendPlainText(text);
    });
    connect(m_command, &VcsCommand::stdErrText, this, [this](const QString &text) {
        m_cloneOutput->appendPlainText(text);
    });
    connect(m_command, &VcsCommand::done, this, [this] {
        cloneFinished(m_command->result() == ProcessResult::FinishedWithSuccess);
    });
    QApplication::setOverrideCursor(Qt::WaitCursor);

    m_cloneOutput->clear();
    m_cloneButton->setEnabled(false);
    m_pathChooser->setReadOnly(true);
    m_directoryLE->setReadOnly(true);
    m_commandRunning = true;
    m_command->start();
}

void GitLabCloneDialog::cancel()
{
    if (m_commandRunning) {
        m_cloneOutput->appendPlainText(Tr::tr("User canceled process."));
        m_cancelButton->setEnabled(false);
        m_command->cancel();    // FIXME does not cancel the git processes... QTCREATORBUG-27567
    } else {
        reject();
    }
}

static FilePaths scanDirectoryForFiles(const FilePath &directory)
{
    FilePaths result;
    const FilePaths entries = directory.dirEntries(QDir::AllEntries | QDir::NoDotAndDotDot);

    for (const FilePath &entry : entries) {
        if (entry.isDir())
            result.append(scanDirectoryForFiles(entry));
        else
            result.append(entry);
    }
    return result;
}

void GitLabCloneDialog::cloneFinished(bool success)
{
    m_commandRunning = false;
    delete m_command;
    m_command = nullptr;

    const QString emptyLine("\n\n");
    m_cloneOutput->appendPlainText(emptyLine);
    QApplication::restoreOverrideCursor();

    if (success) {
        m_cloneOutput->appendPlainText(Tr::tr("Cloning succeeded.") + emptyLine);
        m_cloneButton->setEnabled(false);

        const FilePath base = m_pathChooser->filePath().pathAppended(m_directoryLE->text());
        FilePaths filesWeMayOpen = filtered(scanDirectoryForFiles(base), [](const FilePath &f) {
            return ProjectExplorer::ProjectManager::canOpenProjectForMimeType(mimeTypeForFile(f));
        });

        // limit the files to the most top-level item(s)
        int minimum = std::numeric_limits<int>::max();
        for (const FilePath &f : filesWeMayOpen) {
            int parentCount = f.toString().count('/');
            if (parentCount < minimum)
                minimum = parentCount;
        }
        filesWeMayOpen = filtered(filesWeMayOpen, [minimum](const FilePath &f) {
            return f.toString().count('/') == minimum;
        });

        hide(); // avoid to many dialogs.. FIXME: maybe change to some wizard approach?
        if (filesWeMayOpen.isEmpty()) {
            QMessageBox::warning(this, Tr::tr("Warning"),
                                 Tr::tr("Cloned project does not have a project file that can be "
                                    "opened. Try importing the project as a generic project."));
            accept();
        } else {
            const QStringList pFiles = Utils::transform(filesWeMayOpen, [base](const FilePath &f) {
                return f.relativePathFrom(base).toUserOutput();
            });
            bool ok = false;
            const QString fileToOpen
                    = QInputDialog::getItem(this, Tr::tr("Open Project"),
                                            Tr::tr("Choose the project file to be opened."),
                                            pFiles, 0, false, &ok);
            accept();
            if (ok && !fileToOpen.isEmpty())
                ProjectExplorer::ProjectExplorerPlugin::openProject(base.pathAppended(fileToOpen));
        }
    } else {
        m_cloneOutput->appendPlainText(Tr::tr("Cloning failed.") + emptyLine);
        const FilePath fullPath = m_pathChooser->filePath().pathAppended(m_directoryLE->text());
        fullPath.removeRecursively();
        m_cloneButton->setEnabled(true);
        m_cancelButton->setEnabled(true);
        m_pathChooser->setReadOnly(false);
        m_directoryLE->setReadOnly(false);
        m_directoryLE->validate();
    }
}

} // namespace GitLab