aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/git/gitgrep.cpp
blob: 5cbb52fbcaaced6accfe3f54feeeb4e7bad3cefa (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
// Copyright (C) 2016 Orgad Shaneh <orgads@gmail.com>.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "gitgrep.h"

#include "gitclient.h"
#include "gittr.h"

#include <coreplugin/vcsmanager.h>

#include <texteditor/findinfiles.h>

#include <vcsbase/vcsbaseconstants.h>

#include <utils/algorithm.h>
#include <utils/async.h>
#include <utils/environment.h>
#include <utils/fancylineedit.h>
#include <utils/filesearch.h>
#include <utils/qtcprocess.h>
#include <utils/qtcassert.h>

#include <QCheckBox>
#include <QHBoxLayout>
#include <QRegularExpressionValidator>

using namespace Core;
using namespace TextEditor;
using namespace Utils;
using namespace VcsBase;

namespace Git::Internal {

const char GitGrepRef[] = "GitGrepRef";

class GitGrepParameters
{
public:
    QString ref;
    bool recurseSubmodules = false;
};

static QStringView nextLine(QStringView *remainingInput)
{
    const int newLinePos = remainingInput->indexOf('\n');
    if (newLinePos < 0) {
        QStringView ret = *remainingInput;
        *remainingInput = QStringView();
        return ret;
    }
    QStringView ret = remainingInput->left(newLinePos);
    *remainingInput = remainingInput->mid(newLinePos + 1);
    return ret;
}

struct Match
{
    Match() = default;
    Match(int start, int length) :
        matchStart(start), matchLength(length) {}

    int matchStart = 0;
    int matchLength = 0;
    QStringList regexpCapturedTexts;
};

static void processLine(QStringView line, SearchResultItems *resultList,
                        const std::optional<QRegularExpression> &regExp, const QString &ref,
                        const FilePath &directory)
{
    if (line.isEmpty())
        return;
    static const QLatin1String boldRed("\x1b[1;31m");
    static const QLatin1String resetColor("\x1b[m");
    SearchResultItem result;
    const int lineSeparator = line.indexOf(QChar::Null);
    QStringView filePath = line.left(lineSeparator);
    if (!ref.isEmpty() && filePath.startsWith(ref))
        filePath = filePath.mid(ref.length());
    result.setFilePath(directory.pathAppended(filePath.toString()));
    const int textSeparator = line.indexOf(QChar::Null, lineSeparator + 1);
    const int lineNumber = line.mid(lineSeparator + 1, textSeparator - lineSeparator - 1).toInt();
    QString text = line.mid(textSeparator + 1).toString();
    QList<Match> matches;
    while (true) {
        const int matchStart = text.indexOf(boldRed);
        if (matchStart == -1)
            break;
        const int matchTextStart = matchStart + boldRed.size();
        const int matchEnd = text.indexOf(resetColor, matchTextStart);
        QTC_ASSERT(matchEnd != -1, break);
        const int matchLength = matchEnd - matchTextStart;
        Match match(matchStart, matchLength);
        const QString matchText = text.mid(matchTextStart, matchLength);
        if (regExp)
            match.regexpCapturedTexts = regExp->match(matchText).capturedTexts();
        matches.append(match);
        text = text.left(matchStart) + matchText + text.mid(matchEnd + resetColor.size());
    }
    result.setDisplayText(text);

    for (const auto &match : std::as_const(matches)) {
        result.setMainRange(lineNumber, match.matchStart, match.matchLength);
        result.setUserData(match.regexpCapturedTexts);
        result.setUseTextEditorFont(true);
        resultList->append(result);
    }
}

static SearchResultItems parse(const QFuture<void> &future, const QString &input,
                               const std::optional<QRegularExpression> &regExp, const QString &ref,
                               const FilePath &directory)
{
    SearchResultItems items;
    QStringView remainingInput(input);
    while (true) {
        if (future.isCanceled())
            return {};

        if (remainingInput.isEmpty())
            break;

        const QStringView line = nextLine(&remainingInput);
        if (line.isEmpty())
            continue;

        processLine(line, &items, regExp, ref, directory);
    }
    return items;
}

static void runGitGrep(QPromise<SearchResultItems> &promise, const FileFindParameters &parameters,
                       const GitGrepParameters &gitParameters)
{
    const auto setupProcess = [&parameters, gitParameters](Process &process) {
        const FilePath vcsBinary = gitClient().vcsBinary(parameters.searchDir);
        const Environment environment = gitClient().processEnvironment(vcsBinary);

        QStringList arguments = {
            "-c", "color.grep.match=bold red",
            "-c", "color.grep=always",
            "-c", "color.grep.filename=",
            "-c", "color.grep.lineNumber=",
            "grep", "-zn", "--no-full-name"
        };
        if (!(parameters.flags & FindCaseSensitively))
            arguments << "-i";
        if (parameters.flags & FindWholeWords)
            arguments << "-w";
        if (parameters.flags & FindRegularExpression)
            arguments << "-P";
        else
            arguments << "-F";
        arguments << "-e" << parameters.text;
        if (gitParameters.recurseSubmodules)
            arguments << "--recurse-submodules";
        if (!gitParameters.ref.isEmpty()) {
            arguments << gitParameters.ref;
        }
        const QStringList filterArgs =
            parameters.nameFilters.isEmpty() ? QStringList("*") // needed for exclusion filters
                                               : parameters.nameFilters;
        const QStringList exclusionArgs =
            Utils::transform(parameters.exclusionFilters, [](const QString &filter) {
                return QString(":!" + filter);
            });
        arguments << "--" << filterArgs << exclusionArgs;

        process.setEnvironment(environment);
        process.setCommand({vcsBinary, arguments});
        process.setWorkingDirectory(parameters.searchDir);
    };

    const QString ref = gitParameters.ref.isEmpty() ? QString() : gitParameters.ref + ':';
    const auto outputParser = [&ref, &parameters](const QFuture<void> &future, const QString &input,
                                                 const std::optional<QRegularExpression> &regExp) {
        return parse(future, input, regExp, ref, parameters.searchDir);
    };

    TextEditor::searchInProcessOutput(promise, parameters, setupProcess, outputParser);
}

static bool isGitDirectory(const FilePath &path)
{
    static IVersionControl *gitVc = VcsManager::versionControl(VcsBase::Constants::VCS_ID_GIT);
    QTC_ASSERT(gitVc, return false);
    return gitVc == VcsManager::findVersionControlForDirectory(path);
}

GitGrep::GitGrep()
{
    m_widget = new QWidget;
    auto layout = new QHBoxLayout(m_widget);
    layout->setContentsMargins(0, 0, 0, 0);
    m_treeLineEdit = new FancyLineEdit;
    m_treeLineEdit->setPlaceholderText(Tr::tr("Tree (optional)"));
    m_treeLineEdit->setToolTip(Tr::tr("Can be HEAD, tag, local or remote branch, or a commit hash.\n"
                                  "Leave empty to search through the file system."));
    const QRegularExpression refExpression("[\\S]*");
    m_treeLineEdit->setValidator(new QRegularExpressionValidator(refExpression, this));
    layout->addWidget(m_treeLineEdit);
    // asynchronously check git version, add "recurse submodules" option if available

    m_recurseSubmodules = new QCheckBox(Tr::tr("Recurse submodules"));
    layout->addWidget(m_recurseSubmodules);
    FindInFiles *findInFiles = FindInFiles::instance();
    QTC_ASSERT(findInFiles, return);
    connect(findInFiles, &FindInFiles::searchDirChanged, m_widget, [this](const FilePath &path) {
        setEnabled(isGitDirectory(path));
    });
    connect(this, &SearchEngine::enabledChanged, m_widget, &QWidget::setEnabled);
    findInFiles->addSearchEngine(this);
}

GitGrep::~GitGrep()
{
    delete m_widget;
}

QString GitGrep::title() const
{
    return Tr::tr("Git Grep");
}

QString GitGrep::toolTip() const
{
    const QString ref = m_treeLineEdit->text();
    if (!ref.isEmpty())
        return Tr::tr("Ref: %1\n%2").arg(ref);
    return QLatin1String("%1");
}

QWidget *GitGrep::widget() const
{
    return m_widget;
}

GitGrepParameters GitGrep::gitParameters() const
{
    return {m_treeLineEdit->text(), m_recurseSubmodules && m_recurseSubmodules->isChecked()};
}

void GitGrep::readSettings(const Store &s)
{
    m_treeLineEdit->setText(s.value(GitGrepRef).toString());
}

void GitGrep::writeSettings(Store &s) const
{
    if (!m_treeLineEdit->text().isEmpty())
        s.insert(GitGrepRef, m_treeLineEdit->text());
}

SearchExecutor GitGrep::searchExecutor() const
{
    return [gitParameters = gitParameters()](const FileFindParameters &parameters) {
        return Utils::asyncRun(runGitGrep, parameters, gitParameters);
    };
}

EditorOpener GitGrep::editorOpener() const
{
    return [params = gitParameters()](const SearchResultItem &item,
                                      const FileFindParameters &parameters) -> IEditor * {
        const QStringList &itemPath = item.path();
        if (params.ref.isEmpty() || itemPath.isEmpty())
            return nullptr;
        const FilePath path = FilePath::fromUserInput(itemPath.first());
        IEditor *editor = gitClient().openShowEditor(
            parameters.searchDir, params.ref, path, GitClient::ShowEditor::OnlyIfDifferent);
        if (editor)
            editor->gotoLine(item.mainRange().begin.line, item.mainRange().begin.column);
        return editor;
    };
}

} // Git::Internal