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

devonfw / IDEasy / 44093082167

17 Nov 2026 01:28PM UTC coverage: 75.4% (-0.03%) from 75.426%
44093082167

Pull #2623

github

web-flow
Merge 5e6e3899c into 8b7272947
Pull Request #2623: #2561: Make python a pristine versioned tool with per-project venv is…

6556 of 9643 branches covered (67.99%)

Branch coverage included in aggregate %.

16843 of 21390 relevant lines covered (78.74%)

3.4 hits per line

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

60.38
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
  private static final String FILE_PYVENV_CFG = "pyvenv.cfg";
44

45
  private static final String PYVENV_CFG_VERSION_INFO = "version_info";
46

47
  /**
48
   * The constructor.
49
   *
50
   * @param context the {@link IdeContext}.
51
   */
52
  public Python(IdeContext context) {
53

54
    super(context, "python", Set.of(Tag.PYTHON));
6 ✔
55
  }
1 ✔
56

57
  @Override
58
  protected void performToolInstallation(ToolInstallRequest request, Path installationPath) {
59

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

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

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

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

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

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

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

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

128
  /**
129
   * @return the {@link Path} to the per-project virtual environment (where the project's python packages live) or {@code null} if not inside a project.
130
   * A stable per-project location (inside {@code IDE_HOME} by default) so the virtual environment can be created, updated and removed by IDEasy. The user may
131
   * relocate it via {@link IdeVariables#PYTHON_VENV_DIR}.
132
   */
133
  Path getVenvPath() {
134

135
    Path ideHome = this.context.getIdeHome();
4 ✔
136
    if (ideHome == null) {
2 !
137
      return null;
×
138
    }
139
    String venvDir = IdeVariables.PYTHON_VENV_DIR.get(this.context);
6 ✔
140
    if (venvDir != null && !venvDir.isBlank()) {
5 !
141
      return Path.of(venvDir);
5 ✔
142
    }
143
    return ideHome.resolve(VENV_FOLDER);
4 ✔
144
  }
145

146
  @Override
147
  public void setEnvironment(EnvironmentContext environmentContext, ToolInstallation toolInstallation, boolean additionalInstallation) {
148

149
    super.setEnvironment(environmentContext, toolInstallation, additionalInstallation);
5 ✔
150
    // The python packages of the project (pip / ruff / ...) live in a per-project virtual environment so that two projects on the same python interpreter
151
    // don't collide (see #352). The pristine interpreter itself stays shared in the software repository.
152
    Path venvPath = getVenvPath();
3 ✔
153
    if (venvPath == null) {
2 !
154
      // running in global mode (no project) - there is no per-project virtual environment to point to
155
      return;
×
156
    }
157
    environmentContext.withEnvVar("VIRTUAL_ENV", venvPath.toString());
6 ✔
158
    environmentContext.withEnvVar("UV_PROJECT_ENVIRONMENT", venvPath.toString());
6 ✔
159
    environmentContext.withPathEntry(venvPath.resolve("bin"));
6 ✔
160
  }
1 ✔
161

162
  @Override
163
  protected void postInstall(ToolInstallRequest request) {
164

165
    super.postInstall(request);
3 ✔
166
    setupProjectEnvironment(request);
3 ✔
167
  }
1 ✔
168

169
  /**
170
   * Removes the per-project virtual environment (see {@link #setupProjectEnvironment}) in addition to the per-project tool link (deleted by the default
171
   * implementation, which points at the shared pristine interpreter and must not be followed). This leaves nothing behind inside the project on uninstall (see
172
   * <a href="https://github.com/devonfw/IDEasy/issues/2561">#2561</a>).
173
   *
174
   * @param toolPath the current {@link #getToolPath() tool path} ({@code software/python}, the per-project link to the shared pristine interpreter).
175
   */
176
  @Override
177
  protected void performUninstall(Path toolPath) {
178

179
    super.performUninstall(toolPath);
3 ✔
180
    Path venvPath = getVenvPath();
3 ✔
181
    if (venvPath != null) {
2 !
182
      this.context.getFileAccess().delete(venvPath);
5 ✔
183
    }
184
  }
1 ✔
185

186
  /**
187
   * Creates the per-project virtual environment (backed by the pristine interpreter). Only done inside a project (a pristine interpreter is shared and must not
188
   * be modified).
189
   *
190
   * @param request the {@link ToolInstallRequest}.
191
   */
192
  private void setupProjectEnvironment(ToolInstallRequest request) {
193

194
    Path ideHome = this.context.getIdeHome();
4 ✔
195
    if (ideHome == null) {
2 !
196
      return;
×
197
    }
198
    VersionIdentifier resolvedVersion = request.getRequested().getResolvedVersion();
4 ✔
199
    Uv uv = this.context.getCommandletManager().getCommandlet(Uv.class);
7 ✔
200

201
    // create the per-project virtual environment backed by the pristine interpreter (honoring a relocated location via PYTHON_VENV_DIR, see getVenvPath)
202
    Path venvPath = getVenvPath();
3 ✔
203
    Path interpreterDir = getInstallationPath(getConfiguredEdition(), resolvedVersion);
6 ✔
204
    if (interpreterDir != null) {
2 !
205
      uv.createVirtualEnvironment(venvPath, interpreterDir, request.getProcessContext());
6 ✔
206
      // 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
207
      createWindowsSymlinkBinFolder(this.context.getFileAccess(), venvPath);
6 ✔
208
    }
209
  }
1 ✔
210

211
  @Override
212
  protected boolean isIgnoreMissingSoftwareVersionFile() {
213

214
    // https://github.com/devonfw/IDEasy/issues/2190
215
    return true;
×
216
  }
217

218
  @Override
219
  protected VersionIdentifier computeInstalledVersionFromLocalSoftwareFolder() {
220

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

232
  /**
233
   * @param installationPath the {@link Path} to the Python installation.
234
   * @return the {@link VersionIdentifier} from the {@code version_info} entry of {@code pyvenv.cfg} or {@code null} if not available or not precise enough.
235
   */
236
  private VersionIdentifier readVersionFromPyvenvCfg(Path installationPath) {
237

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

257
  /**
258
   * @param installationPath the {@link Path} to the Python installation.
259
   * @return the {@link VersionIdentifier} reported by the installed python interpreter or {@code null} if it could not be determined.
260
   */
261
  private VersionIdentifier readVersionFromInterpreter(Path installationPath) {
262

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

287
  @Override
288
  public ToolRepository getToolRepository() {
289

290
    return this.context.getPythonRepository();
4 ✔
291
  }
292

293
  /**
294
   * On Windows systems {@code uv} lays out a virtual environment with its executables in a {@code Scripts} folder. This creates a symlink from that
295
   * {@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
296
   * platforms. Does nothing on non-Windows systems, where {@code uv} already uses a {@code bin} folder.
297
   *
298
   * @param fileAccess the {@link FileAccess} utility for file operations.
299
   * @param installationPath the root of the Python virtual environment.
300
   */
301
  private void createWindowsSymlinkBinFolder(FileAccess fileAccess, Path installationPath) {
302

303
    if (!this.context.getSystemInfo().isWindows()) {
5 ✔
304
      return;
1 ✔
305
    }
306
    Path scriptsPath = installationPath.resolve("Scripts");
4 ✔
307
    Path binPath = installationPath.resolve("bin");
4 ✔
308
    fileAccess.symlink(scriptsPath, binPath);
4 ✔
309
  }
1 ✔
310

311
}
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