aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/python/pythonutils.cpp
blob: 178f66108e182109df46d118ea5e83deed4dcde1 (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
// Copyright (C) 2019 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "pythonutils.h"

#include "pythonbuildconfiguration.h"
#include "pythonconstants.h"
#include "pythonkitaspect.h"
#include "pythonproject.h"
#include "pythonsettings.h"
#include "pythontr.h"

#include <coreplugin/messagemanager.h>
#include <coreplugin/progressmanager/processprogress.h>

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

#include <utils/algorithm.h>
#include <utils/datafromprocess.h>
#include <utils/mimeutils.h>
#include <utils/qtcprocess.h>
#include <utils/synchronizedvalue.h>

#include <QReadLocker>

using namespace ProjectExplorer;
using namespace Utils;

namespace Python::Internal {

static QHash<FilePath, FilePath> &userDefinedPythonsForDocument()
{
    static QHash<FilePath, FilePath> userDefines;
    return userDefines;
}

FilePath detectPython(const FilePath &documentPath)
{
    Project *project = documentPath.isEmpty() ? nullptr
                                              : ProjectManager::projectForFile(documentPath);
    if (!project)
        project = ProjectManager::startupProject();

    FilePaths dirs = Environment::systemEnvironment().path();

    if (project && (project->mimeType() == Constants::C_PY_PROJECT_MIME_TYPE
            || project->mimeType() == Constants::C_PY_PROJECT_MIME_TYPE_TOML)) {
        if (auto bc = qobject_cast<PythonBuildConfiguration *>(project->activeBuildConfiguration()))
            return bc->python();
        if (const std::optional<Interpreter> python = PythonKitAspect::python(project->activeKit()))
            return python->command;
    }

    const FilePath userDefined = userDefinedPythonsForDocument().value(documentPath);
    if (userDefined.exists())
        return userDefined;

    // check whether this file is inside a python virtual environment
    const QList<Interpreter> venvInterpreters = PythonSettings::detectPythonVenvs(documentPath);
    if (!venvInterpreters.isEmpty())
        return venvInterpreters.first().command;

    auto defaultInterpreter = PythonSettings::defaultInterpreter().command;
    if (defaultInterpreter.exists())
        return defaultInterpreter;

    auto pythonFromPath = [dirs](const FilePath &toCheck) {
        const FilePaths found = toCheck.searchAllInDirectories(dirs);
        for (const FilePath &python : found) {
            // Windows creates empty redirector files that may interfere
            if (python.exists() && python.osType() == OsTypeWindows && python.fileSize() != 0)
                return python;
        }
        return FilePath();
    };

    const FilePath fromPath3 = pythonFromPath("python3");
    if (fromPath3.exists())
        return fromPath3;

    const FilePath fromPath = pythonFromPath("python");
    if (fromPath.exists())
        return fromPath;

    return PythonSettings::interpreters().value(0).command;
}

void definePythonForDocument(const FilePath &documentPath, const FilePath &python)
{
    userDefinedPythonsForDocument()[documentPath] = python;
}

static QStringList replImportArgs(const FilePath &pythonFile, ReplType type)
{
    using MimeTypes = QList<MimeType>;
    const MimeTypes mimeTypes = pythonFile.isEmpty() || type == ReplType::Unmodified
                                    ? MimeTypes()
                                    : mimeTypesForFileName(pythonFile.toUrlishString());
    const bool isPython = Utils::anyOf(mimeTypes, [](const MimeType &mt) {
        return mt.inherits(Constants::C_PY_MIMETYPE) || mt.inherits(Constants::C_PY3_MIMETYPE);
    });
    if (type == ReplType::Unmodified || !isPython)
        return {};
    const auto import = type == ReplType::Import
                            ? QString("import %1").arg(pythonFile.completeBaseName())
                            : QString("from %1 import *").arg(pythonFile.completeBaseName());
    return {"-c", QString("%1; print('Running \"%1\"')").arg(import)};
}

void openPythonRepl(QObject *parent, const FilePath &file, ReplType type)
{
    Q_UNUSED(parent)

    static const auto workingDir = [](const FilePath &file) {
        if (file.isEmpty()) {
            if (Project *project = ProjectManager::startupProject())
                return project->projectDirectory();
            return FilePath::currentWorkingPath();
        }
        return file.absolutePath();
    };

    const FilePath pythonCommand = detectPython(file);
    Process process;
    process.setCommand({pythonCommand, {"-i", replImportArgs(file, type)}});
    process.setWorkingDirectory(workingDir(file));
    process.setTerminalMode(TerminalMode::Detached);
    process.start();

    if (process.error() != QProcess::UnknownError) {
        Core::MessageManager::writeDisrupting(
            Tr::tr((process.error() == QProcess::FailedToStart)
                       ? "Failed to run Python (%1): \"%2\"."
                       : "Error while running Python (%1): \"%2\".")
                .arg(process.commandLine().toUserOutput(), process.errorString()));
    }
}

PythonProject *pythonProjectForFile(const FilePath &file)
{
    for (Project *project : ProjectManager::projects()) {
        if (auto pythonProject = qobject_cast<PythonProject *>(project)) {
            if (pythonProject->isKnownFile(file))
                return pythonProject;
        }
    }
    return nullptr;
}

bool isVenvPython(const FilePath &python)
{
    return python.parentDir().parentDir().pathAppended("pyvenv.cfg").exists();
}

static bool isUsableHelper(
    SynchronizedValue<QHash<FilePath, bool>> *cache,
    const QString &commandArg,
    const FilePath &python)
{
    std::optional<bool> result;
    cache->read([&result, python](const QHash<FilePath, bool> &cache) {
        if (auto it = cache.find(python); it != cache.end())
            result = it.value();
    });
    if (result)
        return *result;

    Process process;
    process.setCommand({python, {"-m", commandArg, "-h"}});
    process.runBlocking();
    const bool usable = process.result() == ProcessResult::FinishedWithSuccess;
    cache->writeLocked()->insert(python, usable);
    return usable;
}

bool venvIsUsable(const FilePath &python)
{
    static SynchronizedValue<QHash<FilePath, bool>> cache;
    return isUsableHelper(&cache, "venv", python);
}

bool pipIsUsable(const FilePath &python)
{
    static SynchronizedValue<QHash<FilePath, bool>> cache;
    return isUsableHelper(&cache, "pip", python);
}

QString pythonVersion(const FilePath &python)
{
    DataFromProcess<QString>::Parameters
        params({python, {"--version"}}, [](const QString &stdOut, const QString &) {
            return stdOut.trimmed();
        });
    if (const std::optional<QString> version = DataFromProcess<QString>::getData(params))
        return *version;
    return {};
}

} // namespace Python::Internal