• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

devonfw / IDEasy / 43874276980

16 Nov 2026 01:16PM UTC coverage: 75.389% (-0.02%) from 75.411%
43874276980

Pull #2623

github

web-flow
Merge 007517097 into 2c3fd8a45
Pull Request #2623: #2561: Make python a pristine versioned tool with per-project venv is…

6483 of 9527 branches covered (68.05%)

Branch coverage included in aggregate %.

16565 of 21045 relevant lines covered (78.71%)

3.4 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

57.69
cli/src/main/java/com/devonfw/tools/ide/tool/python/Python.java
1
package com.devonfw.tools.ide.tool.python;
2

3
import java.nio.file.Files;
4
import java.nio.file.Path;
5
import java.nio.file.StandardCopyOption;
6
import java.util.List;
7
import java.util.Set;
8

9
import org.slf4j.Logger;
10
import org.slf4j.LoggerFactory;
11

12
import com.devonfw.tools.ide.cli.CliException;
13
import com.devonfw.tools.ide.common.Tag;
14
import com.devonfw.tools.ide.context.IdeContext;
15
import com.devonfw.tools.ide.io.FileAccess;
16
import com.devonfw.tools.ide.log.IdeLogLevel;
17
import com.devonfw.tools.ide.process.EnvironmentContext;
18
import com.devonfw.tools.ide.process.ProcessContext;
19
import com.devonfw.tools.ide.process.ProcessErrorHandling;
20
import com.devonfw.tools.ide.process.ProcessMode;
21
import com.devonfw.tools.ide.process.ProcessResult;
22
import com.devonfw.tools.ide.tool.AbstractLocalToolCommandlet;
23
import com.devonfw.tools.ide.tool.AbstractToolCommandlet;
24
import com.devonfw.tools.ide.tool.ToolInstallRequest;
25
import com.devonfw.tools.ide.tool.ToolInstallation;
26
import com.devonfw.tools.ide.tool.repository.ToolRepository;
27
import com.devonfw.tools.ide.tool.uv.Uv;
28
import com.devonfw.tools.ide.variable.IdeVariables;
29
import com.devonfw.tools.ide.version.VersionIdentifier;
30

31
/**
32
 * {@link AbstractToolCommandlet} for <a href="https://www.python.org/">python</a>.
33
 */
34
public class Python extends AbstractLocalToolCommandlet {
35

36
  private static final Logger LOG = LoggerFactory.getLogger(Python.class);
3 ✔
37

38
  private static final VersionIdentifier PYTHON_MIN_VERSION = VersionIdentifier.ofRequired("3.8.2");
4 ✔
39

40
  /** The per-project folder (inside {@code IDE_HOME}) that holds the virtual environment for the project's python packages. */
41
  static final String VENV_FOLDER = ".venv";
42

43
  /** The tool primed into the per-project {@code uv} tool store on installation so that it is available immediately. */
44
  private static final String RUFF_TOOL = "ruff";
45

46
  private static final String FILE_PYVENV_CFG = "pyvenv.cfg";
47

48
  private static final String PYVENV_CFG_VERSION_INFO = "version_info";
49

50
  /**
51
   * The constructor.
52
   *
53
   * @param context the {@link IdeContext}.
54
   */
55
  public Python(IdeContext context) {
56

57
    super(context, "python", Set.of(Tag.PYTHON));
6 ✔
58
  }
1 ✔
59

60
  @Override
61
  protected void performToolInstallation(ToolInstallRequest request, Path installationPath) {
62

63
    VersionIdentifier resolvedVersion = request.getRequested().getResolvedVersion();
4 ✔
64
    if (resolvedVersion.compareVersion(PYTHON_MIN_VERSION).isLess()) {
5 !
65
      throw new CliException("Python version must be at least " + this.PYTHON_MIN_VERSION);
×
66
    }
67

68
    // Python is installed as a pristine, versioned interpreter into the shared software repository (see getInstallationPath). uv lays the interpreter out in a
69
    // nested "cpython-«version»-«platform»" folder plus management files, so we install into a scratch directory and move the interpreter folder into place.
70
    // Unlike a virtual environment, a pristine interpreter keeps its executable in the installation root (not in a "Scripts" folder on Windows), so no "bin"
71
    // symlink is created here (see createWindowsSymlinkBinFolder, which is only applied to the per-project virtual environment in setupProjectEnvironment).
72
    FileAccess fileAccess = this.context.getFileAccess();
4 ✔
73
    if (Files.exists(installationPath)) {
5 !
74
      fileAccess.backup(installationPath);
×
75
    }
76

77
    Path scratchDir = fileAccess.createTempDir("python-install");
4 ✔
78
    try {
79
      Uv uv = this.context.getCommandletManager().getCommandlet(Uv.class);
7 ✔
80
      uv.installInterpreter(scratchDir, resolvedVersion, request.getProcessContext());
6 ✔
81

82
      Path interpreterDir = findInterpreterDir(scratchDir, resolvedVersion);
5 ✔
83
      fileAccess.mkdirs(installationPath.getParent());
4 ✔
84
      fileAccess.move(interpreterDir, installationPath, StandardCopyOption.REPLACE_EXISTING);
10 ✔
85
      this.context.writeVersionFile(resolvedVersion, installationPath);
5 ✔
86
      LOG.debug("Installed pristine {} in version {} at {}", this.tool, resolvedVersion, installationPath);
18 ✔
87
    } finally {
88
      fileAccess.delete(scratchDir);
3 ✔
89
    }
90
  }
1 ✔
91

92
  /**
93
   * Locates the {@code cpython-«version»} interpreter folder created by {@code uv python install} inside the given scratch directory.
94
   *
95
   * @param scratchDir the directory passed to {@code uv python install --install-dir}
96
   * @param version the {@link VersionIdentifier} that was installed
97
   * @return the {@link Path} of the interpreter folder.
98
   */
99
  private Path findInterpreterDir(Path scratchDir, VersionIdentifier version) {
100

101
    Path result = this.context.getFileAccess().findFirst(scratchDir, p -> {
9 ✔
102
      String name = p.getFileName().toString();
4 ✔
103
      return name.startsWith("cpython-" + version + "-");
6 ✔
104
    }, false);
105
    if (result == null) {
2 !
106
      throw new CliException("Could not find the python interpreter installed by uv in " + scratchDir);
×
107
    }
108
    return result;
2 ✔
109
  }
110

111
  /**
112
   * Places the pristine interpreter in the shared software repository under the {@link ToolRepository#ID_DEFAULT default} namespace
113
   * ({@code $IDE_ROOT/software/default/python/python/«version»}) - the same layout the default repository produces for other pristine, versioned tools (e.g.
114
   * node). Version resolution itself still uses {@link PythonRepository} (see {@link #getToolRepository()}), which is only consulted to list available
115
   * versions via {@code uv}; it is not a download source, so the pristine interpreter must not be stored under its {@link PythonRepository#ID ID}.
116
   *
117
   * @param edition the {@link #getConfiguredEdition() tool edition}.
118
   * @param resolvedVersion the resolved {@link VersionIdentifier version}.
119
   * @return the {@link Path} where the pristine interpreter is (to be) installed.
120
   */
121
  @Override
122
  protected Path getInstallationPath(String edition, VersionIdentifier resolvedVersion) {
123

124
    Path softwareRepositoryPath = this.context.getSoftwareRepositoryPath();
4 ✔
125
    if (softwareRepositoryPath == null) {
2 !
126
      return null;
×
127
    }
128
    return softwareRepositoryPath.resolve(ToolRepository.ID_DEFAULT).resolve(this.tool).resolve(edition).resolve(resolvedVersion.toString());
12 ✔
129
  }
130

131
  @Override
132
  public void setEnvironment(EnvironmentContext environmentContext, ToolInstallation toolInstallation, boolean additionalInstallation) {
133

134
    super.setEnvironment(environmentContext, toolInstallation, additionalInstallation);
5 ✔
135
    Path ideHome = this.context.getIdeHome();
4 ✔
136
    if (ideHome == null) {
2 !
137
      // running in global mode (no project) - there is no per-project virtual environment to point to
138
      return;
×
139
    }
140
    // The python packages of the project (pip / ruff / ...) live in a per-project virtual environment so that two projects on the same python interpreter
141
    // don't collide (see #352). The pristine interpreter itself stays shared in the software repository.
142
    Path venvPath = ideHome.resolve(VENV_FOLDER);
4 ✔
143
    environmentContext.withEnvVar("VIRTUAL_ENV", venvPath.toString());
6 ✔
144
    environmentContext.withEnvVar("UV_PROJECT_ENVIRONMENT", venvPath.toString());
6 ✔
145
    environmentContext.withPathEntry(venvPath.resolve("bin"));
6 ✔
146
  }
1 ✔
147

148
  @Override
149
  protected void postInstall(ToolInstallRequest request) {
150

151
    super.postInstall(request);
3 ✔
152
    setupProjectEnvironment(request);
3 ✔
153
  }
1 ✔
154

155
  /**
156
   * Removes the per-project virtual environment (see {@link #setupProjectEnvironment}) in addition to the per-project tool link (deleted by the default
157
   * implementation, which points at the shared pristine interpreter and must not be followed). This leaves nothing behind inside the project on uninstall (see
158
   * <a href="https://github.com/devonfw/IDEasy/issues/2561">#2561</a>).
159
   *
160
   * @param toolPath the current {@link #getToolPath() tool path} ({@code software/python}, the per-project link to the shared pristine interpreter).
161
   */
162
  @Override
163
  protected void performUninstall(Path toolPath) {
164

165
    super.performUninstall(toolPath);
3 ✔
166
    Path venvPath = this.context.getIdeHome() == null ? null : this.context.getIdeHome().resolve(VENV_FOLDER);
10 !
167
    if (venvPath != null) {
2 !
168
      this.context.getFileAccess().delete(venvPath);
5 ✔
169
    }
170
  }
1 ✔
171

172
  /**
173
   * Creates the per-project virtual environment (backed by the pristine interpreter) and primes {@code ruff} into the per-project {@code uv} tool store. Only
174
   * done inside a project (a pristine interpreter is shared and must not be modified).
175
   *
176
   * @param request the {@link ToolInstallRequest}.
177
   */
178
  private void setupProjectEnvironment(ToolInstallRequest request) {
179

180
    Path ideHome = this.context.getIdeHome();
4 ✔
181
    if (ideHome == null) {
2 !
182
      return;
×
183
    }
184
    VersionIdentifier resolvedVersion = request.getRequested().getResolvedVersion();
4 ✔
185
    Uv uv = this.context.getCommandletManager().getCommandlet(Uv.class);
7 ✔
186

187
    // create the per-project virtual environment backed by the pristine interpreter
188
    Path venvPath = ideHome.resolve(VENV_FOLDER);
4 ✔
189
    Path interpreterDir = getInstallationPath(getConfiguredEdition(), resolvedVersion);
6 ✔
190
    if (interpreterDir != null) {
2 !
191
      uv.createVirtualEnvironment(venvPath, interpreterDir, request.getProcessContext());
6 ✔
192
      // uv lays the executables out in a "Scripts" folder on Windows - expose them as "bin" so the PATH entry set in setEnvironment resolves on all platforms
193
      createWindowsSymlinkBinFolder(this.context.getFileAccess(), venvPath);
6 ✔
194
    }
195

196
    // prime ruff into the per-project uv tool store (best effort - a failure must not fail the python installation); only when the project explicitly
197
    // opted in, so we do not push a linter onto every project
198
    if (Boolean.TRUE.equals(IdeVariables.PYTHON_INSTALL_RUFF.get(this.context))) {
7 !
199
      Path uvToolDir = Uv.getUvToolStorePath(this.context);
×
200
      ProcessContext processContext = request.getProcessContext().withEnvVar("UV_TOOL_DIR", uvToolDir.toString())
×
201
          .withEnvVar("UV_TOOL_BIN_DIR", uvToolDir.resolve("bin").toString());
×
202
      uv.installTool(RUFF_TOOL, processContext);
×
203
    }
204
  }
1 ✔
205

206
  @Override
207
  protected boolean isIgnoreMissingSoftwareVersionFile() {
208

209
    // https://github.com/devonfw/IDEasy/issues/2190
210
    return true;
×
211
  }
212

213
  @Override
214
  protected VersionIdentifier computeInstalledVersionFromLocalSoftwareFolder() {
215

216
    Path toolPath = getToolPath();
3 ✔
217
    VersionIdentifier version = readVersionFromPyvenvCfg(toolPath);
4 ✔
218
    if (version == null) {
2 !
219
      version = readVersionFromInterpreter(toolPath);
4 ✔
220
    }
221
    if (version != null) {
2 !
222
      LOG.debug("Determined version {} of python from the installation at {}.", version, toolPath);
×
223
    }
224
    return version;
2 ✔
225
  }
226

227
  /**
228
   * @param installationPath the {@link Path} to the Python installation.
229
   * @return the {@link VersionIdentifier} from the {@code version_info} entry of {@code pyvenv.cfg} or {@code null} if not available or not precise enough.
230
   */
231
  private VersionIdentifier readVersionFromPyvenvCfg(Path installationPath) {
232

233
    Path pyvenvCfg = installationPath.resolve(FILE_PYVENV_CFG);
4 ✔
234
    if (!Files.exists(pyvenvCfg)) {
5 !
235
      return null;
2 ✔
236
    }
237
    String content = this.context.getFileAccess().readFileContent(pyvenvCfg);
×
238
    for (String line : content.split("\\R")) {
×
239
      String[] keyAndValue = line.split("=", 2);
×
240
      if ((keyAndValue.length == 2) && keyAndValue[0].trim().equals(PYVENV_CFG_VERSION_INFO)) {
×
241
        String value = keyAndValue[1].trim();
×
242
        // uv only writes the minor version (e.g. "3.13") for its own interpreters what is too imprecise for us
243
        if (value.chars().filter(c -> c == '.').count() >= 2) {
×
244
          return VersionIdentifier.ofRequired(value);
×
245
        }
246
        LOG.debug("Ignoring imprecise version {} from {}.", value, pyvenvCfg);
×
247
      }
248
    }
249
    return null;
×
250
  }
251

252
  /**
253
   * @param installationPath the {@link Path} to the Python installation.
254
   * @return the {@link VersionIdentifier} reported by the installed python interpreter or {@code null} if it could not be determined.
255
   */
256
  private VersionIdentifier readVersionFromInterpreter(Path installationPath) {
257

258
    Path binPath = this.context.getFileAccess().getBinPath(installationPath);
6 ✔
259
    Path binaryPath = this.context.getPath().findBinary(binPath.resolve(getBinaryName()));
9 ✔
260
    if (!Files.exists(binaryPath)) {
5 !
261
      LOG.debug("Python binary does not exist in {}.", binPath);
4 ✔
262
      return null;
2 ✔
263
    }
264
    ProcessContext pc = this.context.newProcess().errorHandling(ProcessErrorHandling.NONE).withPathEntry(binPath);
×
265
    ProcessResult result = runTool(pc, ProcessMode.DEFAULT_CAPTURE, List.of("--version"));
×
266
    String output = result.getSingleOutput(IdeLogLevel.DEBUG);
×
267
    if (output == null) {
×
268
      return null;
×
269
    }
270
    String version = output.trim();
×
271
    int lastSpace = version.lastIndexOf(' ');
×
272
    if (lastSpace >= 0) {
×
273
      version = version.substring(lastSpace + 1);
×
274
    }
275
    if (!version.isEmpty() && Character.isDigit(version.charAt(0))) {
×
276
      return VersionIdentifier.ofRequired(version);
×
277
    }
278
    LOG.debug("Could not parse version from output '{}' of {}.", output, binPath);
×
279
    return null;
×
280
  }
281

282
  @Override
283
  public ToolRepository getToolRepository() {
284

285
    return this.context.getPythonRepository();
4 ✔
286
  }
287

288
  /**
289
   * On Windows systems {@code uv} lays out a virtual environment with its executables in a {@code Scripts} folder. This creates a symlink from that
290
   * {@code Scripts} folder to a {@code bin} folder so that the {@code bin} path used to resolve the executable (see {@link #setEnvironment}) exists on all
291
   * platforms. Does nothing on non-Windows systems, where {@code uv} already uses a {@code bin} folder.
292
   *
293
   * @param fileAccess the {@link FileAccess} utility for file operations.
294
   * @param installationPath the root of the Python virtual environment.
295
   */
296
  private void createWindowsSymlinkBinFolder(FileAccess fileAccess, Path installationPath) {
297

298
    if (!this.context.getSystemInfo().isWindows()) {
5 ✔
299
      return;
1 ✔
300
    }
301
    Path scriptsPath = installationPath.resolve("Scripts");
4 ✔
302
    Path binPath = installationPath.resolve("bin");
4 ✔
303
    fileAccess.symlink(scriptsPath, binPath);
4 ✔
304
  }
1 ✔
305

306
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc