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

devonfw / IDEasy / 43001039558

11 Nov 2026 10:08AM UTC coverage: 75.196% (-0.03%) from 75.23%
43001039558

Pull #2623

github

web-flow
Merge aed091170 into 4ae8da268
Pull Request #2623: #2561: Make python a pristine versioned tool with per-project venv is…

6400 of 9437 branches covered (67.82%)

Branch coverage included in aggregate %.

16416 of 20905 relevant lines covered (78.53%)

3.39 hits per line

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

57.14
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 {@code uv} tool store (e.g. {@code ruff}). */
41
  static final String UV_TOOLS_FOLDER = ".uv-tools";
42

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

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

49
  private static final String FILE_PYVENV_CFG = "pyvenv.cfg";
50

51
  private static final String PYVENV_CFG_VERSION_INFO = "version_info";
52

53
  /**
54
   * The constructor.
55
   *
56
   * @param context the {@link IdeContext}.
57
   */
58
  public Python(IdeContext context) {
59

60
    super(context, "python", Set.of(Tag.PYTHON));
6 ✔
61
  }
1 ✔
62

63
  @Override
64
  protected void performToolInstallation(ToolInstallRequest request, Path installationPath) {
65

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

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

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

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

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

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

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

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

134
  @Override
135
  public void setEnvironment(EnvironmentContext environmentContext, ToolInstallation toolInstallation, boolean additionalInstallation) {
136

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

151
  @Override
152
  protected void postInstall(ToolInstallRequest request) {
153

154
    super.postInstall(request);
3 ✔
155
    setupProjectEnvironment(request);
3 ✔
156
  }
1 ✔
157

158
  /**
159
   * Creates the per-project virtual environment (backed by the pristine interpreter) and primes {@code ruff} into the per-project {@code uv} tool store. Only
160
   * done inside a project (a pristine interpreter is shared and must not be modified).
161
   *
162
   * @param request the {@link ToolInstallRequest}.
163
   */
164
  private void setupProjectEnvironment(ToolInstallRequest request) {
165

166
    Path ideHome = this.context.getIdeHome();
4 ✔
167
    if (ideHome == null) {
2 !
168
      return;
×
169
    }
170
    VersionIdentifier resolvedVersion = request.getRequested().getResolvedVersion();
4 ✔
171
    Uv uv = this.context.getCommandletManager().getCommandlet(Uv.class);
7 ✔
172
    Path uvToolDir = ideHome.resolve(UV_TOOLS_FOLDER);
4 ✔
173

174
    // create the per-project virtual environment backed by the pristine interpreter
175
    Path venvPath = ideHome.resolve(VENV_FOLDER);
4 ✔
176
    Path interpreterDir = getInstallationPath(getConfiguredEdition(), resolvedVersion);
6 ✔
177
    if (interpreterDir != null) {
2 !
178
      uv.createVirtualEnvironment(venvPath, interpreterDir, request.getProcessContext());
6 ✔
179
      // 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
180
      createWindowsSymlinkBinFolder(this.context.getFileAccess(), venvPath);
6 ✔
181
    }
182

183
    // prime ruff into the per-project uv tool store (best effort - a failure must not fail the python installation); only when the project explicitly
184
    // opted in, so we do not push a linter onto every project
185
    if (Boolean.TRUE.equals(IdeVariables.PYTHON_INSTALL_RUFF.get(this.context))) {
7 !
186
      ProcessContext processContext = request.getProcessContext().withEnvVar("UV_TOOL_DIR", uvToolDir.toString())
×
187
          .withEnvVar("UV_TOOL_BIN_DIR", uvToolDir.resolve("bin").toString());
×
188
      uv.installTool(RUFF_TOOL, processContext);
×
189
    }
190
  }
1 ✔
191

192
  @Override
193
  protected boolean isIgnoreMissingSoftwareVersionFile() {
194

195
    // https://github.com/devonfw/IDEasy/issues/2190
196
    return true;
×
197
  }
198

199
  @Override
200
  protected VersionIdentifier computeInstalledVersionFromLocalSoftwareFolder() {
201

202
    Path toolPath = getToolPath();
3 ✔
203
    VersionIdentifier version = readVersionFromPyvenvCfg(toolPath);
4 ✔
204
    if (version == null) {
2 !
205
      version = readVersionFromInterpreter(toolPath);
4 ✔
206
    }
207
    if (version != null) {
2 !
208
      LOG.debug("Determined version {} of python from the installation at {}.", version, toolPath);
×
209
    }
210
    return version;
2 ✔
211
  }
212

213
  /**
214
   * @param installationPath the {@link Path} to the Python installation.
215
   * @return the {@link VersionIdentifier} from the {@code version_info} entry of {@code pyvenv.cfg} or {@code null} if not available or not precise enough.
216
   */
217
  private VersionIdentifier readVersionFromPyvenvCfg(Path installationPath) {
218

219
    Path pyvenvCfg = installationPath.resolve(FILE_PYVENV_CFG);
4 ✔
220
    if (!Files.exists(pyvenvCfg)) {
5 !
221
      return null;
2 ✔
222
    }
223
    String content = this.context.getFileAccess().readFileContent(pyvenvCfg);
×
224
    for (String line : content.split("\\R")) {
×
225
      String[] keyAndValue = line.split("=", 2);
×
226
      if ((keyAndValue.length == 2) && keyAndValue[0].trim().equals(PYVENV_CFG_VERSION_INFO)) {
×
227
        String value = keyAndValue[1].trim();
×
228
        // uv only writes the minor version (e.g. "3.13") for its own interpreters what is too imprecise for us
229
        if (value.chars().filter(c -> c == '.').count() >= 2) {
×
230
          return VersionIdentifier.ofRequired(value);
×
231
        }
232
        LOG.debug("Ignoring imprecise version {} from {}.", value, pyvenvCfg);
×
233
      }
234
    }
235
    return null;
×
236
  }
237

238
  /**
239
   * @param installationPath the {@link Path} to the Python installation.
240
   * @return the {@link VersionIdentifier} reported by the installed python interpreter or {@code null} if it could not be determined.
241
   */
242
  private VersionIdentifier readVersionFromInterpreter(Path installationPath) {
243

244
    Path binPath = this.context.getFileAccess().getBinPath(installationPath);
6 ✔
245
    Path binaryPath = this.context.getPath().findBinary(binPath.resolve(getBinaryName()));
9 ✔
246
    if (!Files.exists(binaryPath)) {
5 !
247
      LOG.debug("Python binary does not exist in {}.", binPath);
4 ✔
248
      return null;
2 ✔
249
    }
250
    ProcessContext pc = this.context.newProcess().errorHandling(ProcessErrorHandling.NONE).withPathEntry(binPath);
×
251
    ProcessResult result = runTool(pc, ProcessMode.DEFAULT_CAPTURE, List.of("--version"));
×
252
    String output = result.getSingleOutput(IdeLogLevel.DEBUG);
×
253
    if (output == null) {
×
254
      return null;
×
255
    }
256
    String version = output.trim();
×
257
    int lastSpace = version.lastIndexOf(' ');
×
258
    if (lastSpace >= 0) {
×
259
      version = version.substring(lastSpace + 1);
×
260
    }
261
    if (!version.isEmpty() && Character.isDigit(version.charAt(0))) {
×
262
      return VersionIdentifier.ofRequired(version);
×
263
    }
264
    LOG.debug("Could not parse version from output '{}' of {}.", output, binPath);
×
265
    return null;
×
266
  }
267

268
  @Override
269
  public ToolRepository getToolRepository() {
270

271
    return this.context.getPythonRepository();
4 ✔
272
  }
273

274
  /**
275
   * On Windows systems {@code uv} lays out a virtual environment with its executables in a {@code Scripts} folder. This creates a symlink from that
276
   * {@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
277
   * platforms. Does nothing on non-Windows systems, where {@code uv} already uses a {@code bin} folder.
278
   *
279
   * @param fileAccess the {@link FileAccess} utility for file operations.
280
   * @param installationPath the root of the Python virtual environment.
281
   */
282
  private void createWindowsSymlinkBinFolder(FileAccess fileAccess, Path installationPath) {
283

284
    if (!this.context.getSystemInfo().isWindows()) {
5 ✔
285
      return;
1 ✔
286
    }
287
    Path scriptsPath = installationPath.resolve("Scripts");
4 ✔
288
    Path binPath = installationPath.resolve("bin");
4 ✔
289
    fileAccess.symlink(scriptsPath, binPath);
4 ✔
290
  }
1 ✔
291

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