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

devonfw / IDEasy / 19750767554

28 Nov 2025 12:35AM UTC coverage: 69.441% (+0.3%) from 69.136%
19750767554

Pull #1614

github

web-flow
Merge aa8109e1d into 6f933cdda
Pull Request #1614: #1613: fixed duplicated CVE check and refactored installation routine

3694 of 5847 branches covered (63.18%)

Branch coverage included in aggregate %.

9615 of 13319 relevant lines covered (72.19%)

3.14 hits per line

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

78.02
cli/src/main/java/com/devonfw/tools/ide/tool/ToolCommandlet.java
1
package com.devonfw.tools.ide.tool;
2

3
import java.io.IOException;
4
import java.nio.file.Files;
5
import java.nio.file.Path;
6
import java.util.ArrayList;
7
import java.util.Collection;
8
import java.util.List;
9
import java.util.Set;
10

11
import com.devonfw.tools.ide.commandlet.Commandlet;
12
import com.devonfw.tools.ide.common.Tag;
13
import com.devonfw.tools.ide.common.Tags;
14
import com.devonfw.tools.ide.context.IdeContext;
15
import com.devonfw.tools.ide.environment.EnvironmentVariables;
16
import com.devonfw.tools.ide.environment.EnvironmentVariablesFiles;
17
import com.devonfw.tools.ide.io.FileCopyMode;
18
import com.devonfw.tools.ide.log.IdeSubLogger;
19
import com.devonfw.tools.ide.nls.NlsBundle;
20
import com.devonfw.tools.ide.os.MacOsHelper;
21
import com.devonfw.tools.ide.process.EnvironmentContext;
22
import com.devonfw.tools.ide.process.ProcessContext;
23
import com.devonfw.tools.ide.process.ProcessErrorHandling;
24
import com.devonfw.tools.ide.process.ProcessMode;
25
import com.devonfw.tools.ide.process.ProcessResult;
26
import com.devonfw.tools.ide.property.StringProperty;
27
import com.devonfw.tools.ide.security.ToolVersionChoice;
28
import com.devonfw.tools.ide.step.Step;
29
import com.devonfw.tools.ide.tool.repository.ToolRepository;
30
import com.devonfw.tools.ide.url.model.file.json.Cve;
31
import com.devonfw.tools.ide.url.model.file.json.ToolDependency;
32
import com.devonfw.tools.ide.url.model.file.json.ToolSecurity;
33
import com.devonfw.tools.ide.variable.IdeVariables;
34
import com.devonfw.tools.ide.version.GenericVersionRange;
35
import com.devonfw.tools.ide.version.VersionIdentifier;
36

37
/**
38
 * {@link Commandlet} for a tool integrated into the IDE.
39
 */
40
public abstract class ToolCommandlet extends Commandlet implements Tags {
1✔
41

42
  /** @see #getName() */
43
  protected final String tool;
44

45
  private final Set<Tag> tags;
46

47
  /** The commandline arguments to pass to the tool. */
48
  public final StringProperty arguments;
49

50
  private Path executionDirectory;
51

52
  private MacOsHelper macOsHelper;
53

54
  /**
55
   * The constructor.
56
   *
57
   * @param context the {@link IdeContext}.
58
   * @param tool the {@link #getName() tool name}.
59
   * @param tags the {@link #getTags() tags} classifying the tool. Should be created via {@link Set#of(Object) Set.of} method.
60
   */
61
  public ToolCommandlet(IdeContext context, String tool, Set<Tag> tags) {
62

63
    super(context);
3✔
64
    this.tool = tool;
3✔
65
    this.tags = tags;
3✔
66
    addKeyword(tool);
3✔
67
    this.arguments = new StringProperty("", false, true, "args");
9✔
68
    initProperties();
2✔
69
  }
1✔
70

71
  /**
72
   * Add initial Properties to the tool
73
   */
74
  protected void initProperties() {
75

76
    add(this.arguments);
5✔
77
  }
1✔
78

79
  /**
80
   * @return the name of the tool (e.g. "java", "mvn", "npm", "node").
81
   */
82
  @Override
83
  public final String getName() {
84

85
    return this.tool;
3✔
86
  }
87

88
  /**
89
   * @return the name of the binary executable for this tool.
90
   */
91
  protected String getBinaryName() {
92

93
    return this.tool;
3✔
94
  }
95

96
  @Override
97
  public final Set<Tag> getTags() {
98

99
    return this.tags;
3✔
100
  }
101

102
  /**
103
   * @return the execution directory where the tool will be executed. Will be {@code null} by default leading to execution in the users current working
104
   *     directory where IDEasy was called.
105
   * @see #setExecutionDirectory(Path)
106
   */
107
  public Path getExecutionDirectory() {
108
    return this.executionDirectory;
×
109
  }
110

111
  /**
112
   * @param executionDirectory the new value of {@link #getExecutionDirectory()}.
113
   */
114
  public void setExecutionDirectory(Path executionDirectory) {
115
    this.executionDirectory = executionDirectory;
×
116
  }
×
117

118
  /**
119
   * @return the {@link EnvironmentVariables#getToolVersion(String) tool version}.
120
   */
121
  public VersionIdentifier getConfiguredVersion() {
122

123
    return this.context.getVariables().getToolVersion(getName());
7✔
124
  }
125

126
  /**
127
   * @return the {@link EnvironmentVariables#getToolEdition(String) tool edition}.
128
   */
129
  public String getConfiguredEdition() {
130

131
    return this.context.getVariables().getToolEdition(getName());
7✔
132
  }
133

134
  /**
135
   * @return the {@link ToolEdition} with {@link #getName() tool} with its {@link #getConfiguredEdition() edition}.
136
   */
137
  protected final ToolEdition getToolWithConfiguredEdition() {
138

139
    return new ToolEdition(this.tool, getConfiguredEdition());
8✔
140
  }
141

142
  @Override
143
  public void run() {
144

145
    runTool(this.arguments.asArray());
6✔
146
  }
1✔
147

148
  /**
149
   * @param args the command-line arguments to run the tool.
150
   * @return the {@link ProcessResult result}.
151
   * @see ToolCommandlet#runTool(ProcessMode, GenericVersionRange, String...)
152
   */
153
  public ProcessResult runTool(String... args) {
154

155
    return runTool(ProcessMode.DEFAULT, (GenericVersionRange) null, args);
7✔
156
  }
157

158
  /**
159
   * Ensures the tool is installed and then runs this tool with the given arguments.
160
   *
161
   * @param processMode the {@link ProcessMode}. Should typically be {@link ProcessMode#DEFAULT} or {@link ProcessMode#BACKGROUND}.
162
   * @param toolVersion the explicit {@link GenericVersionRange version} to run. Typically {@code null} to run the
163
   *     {@link #getConfiguredVersion() configured version}. Otherwise, the specified version will be used (from the software repository, if not compatible).
164
   * @param args the command-line arguments to run the tool.
165
   * @return the {@link ProcessResult result}.
166
   */
167
  public final ProcessResult runTool(ProcessMode processMode, GenericVersionRange toolVersion, String... args) {
168

169
    return runTool(processMode, toolVersion, ProcessErrorHandling.THROW_CLI, args);
7✔
170
  }
171

172
  /**
173
   * Ensures the tool is installed and then runs this tool with the given arguments.
174
   *
175
   * @param processMode the {@link ProcessMode}. Should typically be {@link ProcessMode#DEFAULT} or {@link ProcessMode#BACKGROUND}.
176
   * @param toolVersion the explicit {@link GenericVersionRange version} to run. Typically {@code null} to run the
177
   *     {@link #getConfiguredVersion() configured version}. Otherwise, the specified version will be used (from the software repository, if not compatible).
178
   * @param errorHandling the {@link ProcessErrorHandling}.
179
   * @param args the command-line arguments to run the tool.
180
   * @return the {@link ProcessResult result}.
181
   */
182
  public ProcessResult runTool(ProcessMode processMode, GenericVersionRange toolVersion, ProcessErrorHandling errorHandling, String... args) {
183

184
    ProcessContext pc = this.context.newProcess().errorHandling(errorHandling);
6✔
185
    ToolInstallRequest request = new ToolInstallRequest(true);
5✔
186
    if (toolVersion != null) {
2!
187
      request.setRequested(new ToolEditionAndVersion(toolVersion));
×
188
    }
189
    request.setProcessContext(pc);
3✔
190
    install(request);
4✔
191
    return runTool(pc, processMode, args);
6✔
192
  }
193

194
  /**
195
   * @param pc the {@link ProcessContext}.
196
   * @param processMode the {@link ProcessMode}. Should typically be {@link ProcessMode#DEFAULT} or {@link ProcessMode#BACKGROUND}.
197
   * @param args the command-line arguments to run the tool.
198
   * @return the {@link ProcessResult result}.
199
   */
200
  public ProcessResult runTool(ProcessContext pc, ProcessMode processMode, String... args) {
201

202
    if (this.executionDirectory != null) {
3!
203
      pc.directory(this.executionDirectory);
×
204
    }
205
    configureToolBinary(pc, processMode);
4✔
206
    configureToolArgs(pc, processMode, args);
5✔
207
    return pc.run(processMode);
4✔
208
  }
209

210
  /**
211
   * @param pc the {@link ProcessContext}.
212
   * @param processMode the {@link ProcessMode}.
213
   */
214
  protected void configureToolBinary(ProcessContext pc, ProcessMode processMode) {
215

216
    pc.executable(Path.of(getBinaryName()));
8✔
217
  }
1✔
218

219
  /**
220
   * @param pc the {@link ProcessContext}.
221
   * @param processMode the {@link ProcessMode}.
222
   * @param args the command-line arguments to {@link ProcessContext#addArgs(Object...) add}.
223
   */
224
  protected void configureToolArgs(ProcessContext pc, ProcessMode processMode, String... args) {
225

226
    pc.addArgs(args);
4✔
227
  }
1✔
228

229
  /**
230
   * Installs or updates the managed {@link #getName() tool}.
231
   *
232
   * @return the {@link ToolInstallation}.
233
   */
234
  public ToolInstallation install() {
235

236
    return install(true);
4✔
237
  }
238

239
  /**
240
   * Performs the installation of the {@link #getName() tool} managed by this {@link com.devonfw.tools.ide.commandlet.Commandlet}.
241
   *
242
   * @param silent - {@code true} if called recursively to suppress verbose logging, {@code false} otherwise.
243
   * @return the {@link ToolInstallation}.
244
   */
245
  public ToolInstallation install(boolean silent) {
246
    return install(new ToolInstallRequest(silent));
7✔
247
  }
248

249
  /**
250
   * Performs the installation (install, update, downgrade) of the {@link #getName() tool} managed by this {@link ToolCommandlet}.
251
   *
252
   * @param request the {@link ToolInstallRequest}.
253
   * @return the {@link ToolInstallation}.
254
   */
255
  public ToolInstallation install(ToolInstallRequest request) {
256

257
    completeRequest(request);
3✔
258
    return doInstall(request);
4✔
259
  }
260

261
  /**
262
   * Performs the installation (install, update, downgrade) of the {@link #getName() tool} managed by this {@link ToolCommandlet}.
263
   *
264
   * @param request the {@link ToolInstallRequest}.
265
   * @return the {@link ToolInstallation}.
266
   */
267
  protected abstract ToolInstallation doInstall(ToolInstallRequest request);
268

269
  /**
270
   * @param request the {@link ToolInstallRequest} to complete (fill values that are currently {@code null}).
271
   */
272
  protected void completeRequest(ToolInstallRequest request) {
273

274
    completeRequestInstalled(request);
3✔
275
    completeRequestRequested(request); // depends on completeRequestInstalled
3✔
276
    completeRequestProcessContext(request);
3✔
277
  }
1✔
278

279
  private void completeRequestProcessContext(ToolInstallRequest request) {
280
    if (request.getProcessContext() == null) {
3✔
281
      ProcessContext pc = this.context.newProcess().errorHandling(ProcessErrorHandling.THROW_CLI);
6✔
282
      request.setProcessContext(pc);
3✔
283
    }
284
  }
1✔
285

286
  private void completeRequestInstalled(ToolInstallRequest request) {
287

288
    ToolEditionAndVersion installedToolVersion = request.getInstalled();
3✔
289
    if (installedToolVersion == null) {
2✔
290
      installedToolVersion = new ToolEditionAndVersion((GenericVersionRange) null);
6✔
291
      request.setInstalled(installedToolVersion);
3✔
292
    }
293
    if (installedToolVersion.getVersion() == null) {
3✔
294
      VersionIdentifier installedVersion = getInstalledVersion();
3✔
295
      if (installedVersion == null) {
2✔
296
        return;
1✔
297
      }
298
      installedToolVersion.setVersion(installedVersion);
3✔
299
    }
300
    if (installedToolVersion.getEdition() == null) {
3✔
301
      installedToolVersion.setEdition(new ToolEdition(this.tool, getInstalledEdition()));
9✔
302
    }
303
    assert installedToolVersion.getResolvedVersion() != null;
4!
304
  }
1✔
305

306
  private void completeRequestRequested(ToolInstallRequest request) {
307

308
    ToolEdition edition;
309
    ToolEditionAndVersion requested = request.getRequested();
3✔
310
    if (requested == null) {
2✔
311
      edition = new ToolEdition(this.tool, getConfiguredEdition());
8✔
312
      requested = new ToolEditionAndVersion(edition);
5✔
313
      request.setRequested(requested);
4✔
314
    } else {
315
      edition = requested.getEdition();
3✔
316
      if (edition == null) {
2✔
317
        edition = new ToolEdition(this.tool, getConfiguredEdition());
8✔
318
        requested.setEdition(edition);
3✔
319
      }
320
    }
321
    GenericVersionRange version = requested.getVersion();
3✔
322
    if (version == null) {
2✔
323
      version = getConfiguredVersion();
3✔
324
      requested.setVersion(version);
3✔
325
    }
326
    VersionIdentifier resolvedVersion = requested.getResolvedVersion();
3✔
327
    if (resolvedVersion == null) {
2✔
328
      if (this.context.isSkipUpdatesMode()) {
4✔
329
        ToolEditionAndVersion installed = request.getInstalled();
3✔
330
        if (installed != null) {
2!
331
          VersionIdentifier installedVersion = installed.getResolvedVersion();
3✔
332
          if (version.contains(installedVersion)) {
4✔
333
            resolvedVersion = installedVersion;
2✔
334
          }
335
        }
336
      }
337
      if (resolvedVersion == null) {
2✔
338
        resolvedVersion = getToolRepository().resolveVersion(this.tool, edition.edition(), version, this);
10✔
339
      }
340
      requested.setResolvedVersion(resolvedVersion);
3✔
341
    }
342
  }
1✔
343

344
  /**
345
   * This method is called after a tool was requested to be installed or updated.
346
   *
347
   * @param newlyInstalled {@code true} if the tool was installed or updated (at least link to software folder was created/updated), {@code false} otherwise
348
   *     (configured version was already installed and nothing changed).
349
   * @param pc the {@link ProcessContext} to use.
350
   */
351
  protected void postInstall(boolean newlyInstalled, ProcessContext pc) {
352

353
    if (newlyInstalled) {
2✔
354
      postInstall();
2✔
355
    }
356
  }
1✔
357

358
  /**
359
   * This method is called after the tool has been newly installed or updated to a new version.
360
   */
361
  protected void postInstall() {
362

363
    // nothing to do by default
364
  }
1✔
365

366
  /**
367
   * @param edition the {@link #getInstalledEdition() edition}.
368
   * @param version the {@link #getInstalledVersion() version}.
369
   * @return the {@link Path} where this tool is installed (physically) or {@code null} if not available.
370
   */
371
  protected abstract Path getInstallationPath(String edition, VersionIdentifier version);
372

373
  /**
374
   * @param request the {@link ToolInstallRequest}.
375
   * @return the existing {@link ToolInstallation}.
376
   */
377
  protected ToolInstallation createExistingToolInstallation(ToolInstallRequest request) {
378

379
    ToolEditionAndVersion installed = request.getInstalled();
3✔
380
    return createExistingToolInstallation(installed.getEdition().edition(), installed.getResolvedVersion(), request.getProcessContext(),
11✔
381
        request.isAdditionalInstallation());
1✔
382
  }
383

384
  /**
385
   * @param edition the {@link #getConfiguredEdition() edition}.
386
   * @param installedVersion the {@link #getConfiguredVersion() version}.
387
   * @param environmentContext the {@link EnvironmentContext}.
388
   * @param extraInstallation {@code true} if the {@link ToolInstallation} is an additional installation to the
389
   *     {@link #getConfiguredVersion() configured version} due to a conflicting version of a {@link ToolDependency}, {@code false} otherwise.
390
   * @return the {@link ToolInstallation}.
391
   */
392
  protected ToolInstallation createExistingToolInstallation(String edition, VersionIdentifier installedVersion, EnvironmentContext environmentContext,
393
      boolean extraInstallation) {
394

395
    Path installationPath = getInstallationPath(edition, installedVersion);
5✔
396
    return createToolInstallation(installationPath, installedVersion, false, environmentContext, extraInstallation);
8✔
397
  }
398

399
  /**
400
   * @param rootDir the {@link ToolInstallation#rootDir() top-level installation directory}.
401
   * @param version the installed {@link VersionIdentifier}.
402
   * @param newInstallation {@link ToolInstallation#newInstallation() new installation} flag.
403
   * @param environmentContext the {@link EnvironmentContext}.
404
   * @param additionalInstallation {@code true} if the {@link ToolInstallation} is an additional installation to the
405
   *     {@link #getConfiguredVersion() configured version} due to a conflicting version of a {@link ToolDependency}, {@code false} otherwise.
406
   * @return the {@link ToolInstallation}.
407
   */
408
  protected ToolInstallation createToolInstallation(Path rootDir, VersionIdentifier version, boolean newInstallation,
409
      EnvironmentContext environmentContext, boolean additionalInstallation) {
410

411
    Path linkDir = rootDir;
2✔
412
    Path binDir = rootDir;
2✔
413
    if (rootDir != null) {
2✔
414
      // on MacOS applications have a very strange structure - see JavaDoc of findLinkDir and ToolInstallation.linkDir for details.
415
      linkDir = getMacOsHelper().findLinkDir(rootDir, getBinaryName());
7✔
416
      binDir = this.context.getFileAccess().getBinPath(linkDir);
6✔
417
    }
418
    return createToolInstallation(rootDir, linkDir, binDir, version, newInstallation, environmentContext, additionalInstallation);
10✔
419
  }
420

421
  /**
422
   * @param rootDir the {@link ToolInstallation#rootDir() top-level installation directory}.
423
   * @param linkDir the {@link ToolInstallation#linkDir() link directory}.
424
   * @param binDir the {@link ToolInstallation#binDir() bin directory}.
425
   * @param version the installed {@link VersionIdentifier}.
426
   * @param newInstallation {@link ToolInstallation#newInstallation() new installation} flag.
427
   * @param environmentContext the {@link EnvironmentContext}.
428
   * @param additionalInstallation {@code true} if the {@link ToolInstallation} is an additional installation to the
429
   *     {@link #getConfiguredVersion() configured version} due to a conflicting version of a {@link ToolDependency}, {@code false} otherwise.
430
   * @return the {@link ToolInstallation}.
431
   */
432
  protected ToolInstallation createToolInstallation(Path rootDir, Path linkDir, Path binDir, VersionIdentifier version, boolean newInstallation,
433
      EnvironmentContext environmentContext, boolean additionalInstallation) {
434

435
    if (linkDir != rootDir) {
3✔
436
      assert (!linkDir.equals(rootDir));
5!
437
      Path toolVersionFile = rootDir.resolve(IdeContext.FILE_SOFTWARE_VERSION);
4✔
438
      if (Files.exists(toolVersionFile)) {
5!
439
        this.context.getFileAccess().copy(toolVersionFile, linkDir, FileCopyMode.COPY_FILE_OVERRIDE);
7✔
440
      }
441
    }
442
    ToolInstallation toolInstallation = new ToolInstallation(rootDir, linkDir, binDir, version, newInstallation);
9✔
443
    setEnvironment(environmentContext, toolInstallation, additionalInstallation);
5✔
444
    return toolInstallation;
2✔
445
  }
446

447
  /**
448
   * Called if the tool {@link ToolInstallRequest#isAlreadyInstalled(boolean) is already installed in the correct edition and version} so we can skip the
449
   * installation.
450
   *
451
   * @param request the {@link ToolInstallRequest}.
452
   * @return the {@link ToolInstallation}.
453
   */
454
  protected ToolInstallation toolAlreadyInstalled(ToolInstallRequest request) {
455

456
    logToolAlreadyInstalled(request);
3✔
457
    cveCheck(request, true);
5✔
458
    postInstall(false, request.getProcessContext());
5✔
459
    return createExistingToolInstallation(request);
4✔
460
  }
461

462
  /**
463
   * Log that the tool is already installed.
464
   *
465
   * @param request the {@link ToolInstallRequest}.
466
   */
467
  protected void logToolAlreadyInstalled(ToolInstallRequest request) {
468
    IdeSubLogger logger;
469
    if (request.isSilent()) {
3✔
470
      logger = this.context.debug();
5✔
471
    } else {
472
      logger = this.context.info();
4✔
473
    }
474
    ToolEditionAndVersion installed = request.getInstalled();
3✔
475
    logger.log("Version {} of tool {} is already installed", installed.getVersion(), installed.getEdition());
16✔
476
  }
1✔
477

478
  /**
479
   * Method to get the home path of the given {@link ToolInstallation}.
480
   *
481
   * @param toolInstallation the {@link ToolInstallation}.
482
   * @return the Path to the home of the tool
483
   */
484
  protected Path getToolHomePath(ToolInstallation toolInstallation) {
485
    return toolInstallation.linkDir();
3✔
486
  }
487

488
  /**
489
   * Method to set environment variables for the process context.
490
   *
491
   * @param environmentContext the {@link EnvironmentContext} where to {@link EnvironmentContext#withEnvVar(String, String) set environment variables} for
492
   *     this tool.
493
   * @param toolInstallation the {@link ToolInstallation}.
494
   * @param extraInstallation {@code true} if the {@link ToolInstallation} is an additional installation to the
495
   *     {@link #getConfiguredVersion() configured version} due to a conflicting version of a {@link ToolDependency}, {@code false} otherwise.
496
   */
497
  public void setEnvironment(EnvironmentContext environmentContext, ToolInstallation toolInstallation, boolean extraInstallation) {
498

499
    String pathVariable = EnvironmentVariables.getToolVariablePrefix(this.tool) + "_HOME";
5✔
500
    Path toolHomePath = getToolHomePath(toolInstallation);
4✔
501
    if (toolHomePath != null) {
2✔
502
      environmentContext.withEnvVar(pathVariable, toolHomePath.toString());
6✔
503
    }
504
    if (extraInstallation) {
2✔
505
      environmentContext.withPathEntry(toolInstallation.binDir());
5✔
506
    }
507
  }
1✔
508

509
  /**
510
   * @return {@code true} to extract (unpack) the downloaded binary file, {@code false} otherwise.
511
   */
512
  protected boolean isExtract() {
513

514
    return true;
2✔
515
  }
516

517
  /**
518
   * Checks a version to be installed for {@link Cve}s. If at least one {@link Cve} is found, we try to find better/safer versions as alternative. If we find
519
   * something better, we will suggest this to the user and ask him to make his choice.
520
   *
521
   * @param request the {@link ToolInstallRequest}.
522
   * @param skipSuggestions {@code true} to skip suggestions, {@code false} otherwise (try to find alternative suggestions and ask the user).
523
   * @return the {@link VersionIdentifier} to install. The will may be asked (unless {@code skipSuggestions} is {@code true}) and might choose a different
524
   *     version than the originally requested one.
525
   */
526
  protected VersionIdentifier cveCheck(ToolInstallRequest request, boolean skipSuggestions) {
527

528
    ToolEditionAndVersion requested = request.getRequested();
3✔
529
    ToolEdition toolEdition = requested.getEdition();
3✔
530
    VersionIdentifier resolvedVersion = requested.getResolvedVersion();
3✔
531
    GenericVersionRange allowedVersions = requested.getVersion();
3✔
532
    ToolSecurity toolSecurity = this.context.getDefaultToolRepository().findSecurity(this.tool, toolEdition.edition());
9✔
533
    double minSeverity = IdeVariables.CVE_MIN_SEVERITY.get(context);
7✔
534
    Collection<Cve> issues = toolSecurity.findCves(resolvedVersion, this.context, minSeverity);
7✔
535
    ToolVersionChoice currentChoice = ToolVersionChoice.ofCurrent(resolvedVersion, issues);
4✔
536
    if (logCvesAndReturnTrueForNone(toolEdition, resolvedVersion, currentChoice.option(), issues)) {
8✔
537
      return resolvedVersion;
2✔
538
    }
539
    if (skipSuggestions) {
2!
540
      // currently for a transitive dependency it does not make sense to suggest alternative versions, since the choice is not stored anywhere,
541
      // and we then would ask the user again every time the tool having this dependency is started. So we only log the problem and the user needs to react
542
      // (e.g. upgrade the tool with the dependency that is causing this).
543
      this.context.interaction("Please run 'ide -f install {}' to check for update suggestions!", this.tool);
×
544
      return resolvedVersion;
×
545
    }
546
    double currentSeveritySum = Cve.severitySum(issues);
3✔
547
    ToolVersionChoice latest = null;
2✔
548
    ToolVersionChoice nearest = null;
2✔
549
    List<VersionIdentifier> toolVersions = getVersions();
3✔
550
    double latestSeveritySum = currentSeveritySum;
2✔
551
    double nearestSeveritySum = currentSeveritySum;
2✔
552
    for (VersionIdentifier version : toolVersions) {
10✔
553
      if (!allowedVersions.isPattern() || allowedVersions.contains(version)) {
3!
554
        issues = toolSecurity.findCves(version, this.context, minSeverity);
7✔
555
        double newSeveritySum = Cve.severitySum(issues);
3✔
556
        if (newSeveritySum < latestSeveritySum) {
4✔
557
          // we found a better/safer version
558
          if (version.isGreater(resolvedVersion)) {
4!
559
            latest = ToolVersionChoice.ofLatest(version, issues);
4✔
560
            nearest = null;
2✔
561
            latestSeveritySum = newSeveritySum;
3✔
562
          } else {
563
            // latest = null;
564
            nearest = ToolVersionChoice.ofNearest(version, issues);
×
565
            nearestSeveritySum = newSeveritySum;
×
566
          }
567
        } else if (newSeveritySum < nearestSeveritySum) {
4✔
568
          if (version.isGreater(resolvedVersion)) {
4!
569
            nearest = ToolVersionChoice.ofNearest(version, issues);
×
570
          } else if (nearest == null) {
2!
571
            nearest = ToolVersionChoice.ofNearest(version, issues);
4✔
572
          }
573
          nearestSeveritySum = newSeveritySum;
2✔
574
        }
575
      }
576
    }
1✔
577
    if ((latest == null) && (nearest == null)) {
2!
578
      this.context.warning(
×
579
          "Could not find any other version resolving your CVEs.\nPlease keep attention to this tool and consider updating as soon as security fixes are available.");
580
    }
581
    List<ToolVersionChoice> choices = new ArrayList<>();
4✔
582
    choices.add(currentChoice);
4✔
583
    boolean addSuggestions;
584
    if (this.context.isForceMode() && request.isDirect()) {
4!
585
      addSuggestions = true;
×
586
    } else {
587
      List<String> skipCveFixTools = IdeVariables.SKIP_CVE_FIX.get(this.context);
6✔
588
      addSuggestions = !skipCveFixTools.contains(this.tool);
8!
589
    }
590
    if (nearest != null) {
2!
591
      if (addSuggestions) {
2!
592
        choices.add(nearest);
4✔
593
      }
594
      logCvesAndReturnTrueForNone(toolEdition, nearest.version(), nearest.option(), nearest.issues());
10✔
595
    }
596
    if (latest != null) {
2!
597
      if (addSuggestions) {
2!
598
        choices.add(latest);
4✔
599
      }
600
      logCvesAndReturnTrueForNone(toolEdition, latest.version(), latest.option(), latest.issues());
10✔
601
    }
602
    ToolVersionChoice[] choicesArray = choices.toArray(ToolVersionChoice[]::new);
8✔
603
    this.context.warning(
4✔
604
        "Please note that by selecting an unsafe version to install, you accept the risk to be attacked.");
605
    ToolVersionChoice answer = this.context.question(choicesArray, "Which version do you want to install?");
9✔
606
    VersionIdentifier version = answer.version();
3✔
607
    requested.setResolvedVersion(version);
3✔
608
    return version;
2✔
609
  }
610

611
  private boolean logCvesAndReturnTrueForNone(ToolEdition toolEdition, VersionIdentifier version, String option, Collection<Cve> issues) {
612
    if (issues.isEmpty()) {
3✔
613
      this.context.info("No CVEs found for {} version {} of tool {}.", option, version, toolEdition);
18✔
614
      return true;
2✔
615
    }
616
    this.context.warning("For {} version {} of tool {} we found {} CVE(s):", option, version, toolEdition, issues.size());
24✔
617
    for (Cve cve : issues) {
10✔
618
      logCve(cve);
3✔
619
    }
1✔
620
    return false;
2✔
621
  }
622

623
  private void logCve(Cve cve) {
624

625
    this.context.warning("{} with severity {} and affected versions: {} ", cve.id(), cve.severity(), cve.versions());
22✔
626
    this.context.warning("https://nvd.nist.gov/vuln/detail/" + cve.id());
6✔
627
    this.context.info("");
4✔
628
  }
1✔
629

630
  /**
631
   * @return the {@link MacOsHelper} instance.
632
   */
633
  protected MacOsHelper getMacOsHelper() {
634

635
    if (this.macOsHelper == null) {
3✔
636
      this.macOsHelper = new MacOsHelper(this.context);
7✔
637
    }
638
    return this.macOsHelper;
3✔
639
  }
640

641
  /**
642
   * @return the currently installed {@link VersionIdentifier version} of this tool or {@code null} if not installed.
643
   */
644
  public abstract VersionIdentifier getInstalledVersion();
645

646
  /**
647
   * @return {@code true} if this tool is installed, {@code false} otherwise.
648
   */
649
  public boolean isInstalled() {
650

651
    return getInstalledVersion() != null;
7✔
652
  }
653

654
  /**
655
   * @return the installed edition of this tool or {@code null} if not installed.
656
   */
657
  public abstract String getInstalledEdition();
658

659
  /**
660
   * Uninstalls the {@link #getName() tool}.
661
   */
662
  public abstract void uninstall();
663

664
  /**
665
   * @return the {@link ToolRepository}.
666
   */
667
  public ToolRepository getToolRepository() {
668

669
    return this.context.getDefaultToolRepository();
4✔
670
  }
671

672
  /**
673
   * List the available editions of this tool.
674
   */
675
  public void listEditions() {
676

677
    List<String> editions = getToolRepository().getSortedEditions(getName());
6✔
678
    for (String edition : editions) {
10✔
679
      this.context.info(edition);
4✔
680
    }
1✔
681
  }
1✔
682

683
  /**
684
   * List the available versions of this tool.
685
   */
686
  public void listVersions() {
687

688
    List<VersionIdentifier> versions = getToolRepository().getSortedVersions(getName(), getConfiguredEdition(), this);
9✔
689
    for (VersionIdentifier vi : versions) {
10✔
690
      this.context.info(vi.toString());
5✔
691
    }
1✔
692
  }
1✔
693

694
  /**
695
   * @return the {@link com.devonfw.tools.ide.tool.repository.DefaultToolRepository#getSortedVersions(String, String, ToolCommandlet) sorted versions} of this
696
   *     tool.
697
   */
698
  public List<VersionIdentifier> getVersions() {
699
    return getToolRepository().getSortedVersions(getName(), getConfiguredEdition(), this);
9✔
700
  }
701

702
  /**
703
   * Sets the tool version in the environment variable configuration file.
704
   *
705
   * @param version the version (pattern) to set.
706
   */
707
  public void setVersion(String version) {
708

709
    if ((version == null) || version.isBlank()) {
×
710
      throw new IllegalStateException("Version has to be specified!");
×
711
    }
712
    VersionIdentifier configuredVersion = VersionIdentifier.of(version);
×
713
    if (!configuredVersion.isPattern() && !configuredVersion.isValid()) {
×
714
      this.context.warning("Version {} seems to be invalid", version);
×
715
    }
716
    setVersion(configuredVersion, true);
×
717
  }
×
718

719
  /**
720
   * Sets the tool version in the environment variable configuration file.
721
   *
722
   * @param version the version to set. May also be a {@link VersionIdentifier#isPattern() version pattern}.
723
   * @param hint - {@code true} to print the installation hint, {@code false} otherwise.
724
   */
725
  public void setVersion(VersionIdentifier version, boolean hint) {
726

727
    setVersion(version, hint, null);
5✔
728
  }
1✔
729

730
  /**
731
   * Sets the tool version in the environment variable configuration file.
732
   *
733
   * @param version the version to set. May also be a {@link VersionIdentifier#isPattern() version pattern}.
734
   * @param hint - {@code true} to print the installation hint, {@code false} otherwise.
735
   * @param destination - the destination for the property to be set
736
   */
737
  public void setVersion(VersionIdentifier version, boolean hint, EnvironmentVariablesFiles destination) {
738

739
    String edition = getConfiguredEdition();
3✔
740
    ToolRepository toolRepository = getToolRepository();
3✔
741

742
    EnvironmentVariables variables = this.context.getVariables();
4✔
743
    if (destination == null) {
2✔
744
      //use default location
745
      destination = EnvironmentVariablesFiles.SETTINGS;
2✔
746
    }
747
    EnvironmentVariables settingsVariables = variables.getByType(destination.toType());
5✔
748
    String name = EnvironmentVariables.getToolVersionVariable(this.tool);
4✔
749

750
    toolRepository.resolveVersion(this.tool, edition, version, this); // verify that the version actually exists
8✔
751
    settingsVariables.set(name, version.toString(), false);
7✔
752
    settingsVariables.save();
2✔
753
    EnvironmentVariables declaringVariables = variables.findVariable(name);
4✔
754
    if ((declaringVariables != null) && (declaringVariables != settingsVariables)) {
5!
755
      this.context.warning("The variable {} is overridden in {}. Please remove the overridden declaration in order to make the change affect.", name,
13✔
756
          declaringVariables.getSource());
2✔
757
    }
758
    if (hint) {
2✔
759
      this.context.info("To install that version call the following command:");
4✔
760
      this.context.info("ide install {}", this.tool);
11✔
761
    }
762
  }
1✔
763

764
  /**
765
   * Sets the tool edition in the environment variable configuration file.
766
   *
767
   * @param edition the edition to set.
768
   */
769
  public void setEdition(String edition) {
770

771
    setEdition(edition, true);
4✔
772
  }
1✔
773

774
  /**
775
   * Sets the tool edition in the environment variable configuration file.
776
   *
777
   * @param edition the edition to set
778
   * @param hint - {@code true} to print the installation hint, {@code false} otherwise.
779
   */
780
  public void setEdition(String edition, boolean hint) {
781

782
    setEdition(edition, hint, null);
5✔
783
  }
1✔
784

785
  /**
786
   * Sets the tool edition in the environment variable configuration file.
787
   *
788
   * @param edition the edition to set
789
   * @param hint - {@code true} to print the installation hint, {@code false} otherwise.
790
   * @param destination - the destination for the property to be set
791
   */
792
  public void setEdition(String edition, boolean hint, EnvironmentVariablesFiles destination) {
793

794
    if ((edition == null) || edition.isBlank()) {
5!
795
      throw new IllegalStateException("Edition has to be specified!");
×
796
    }
797

798
    if (destination == null) {
2✔
799
      //use default location
800
      destination = EnvironmentVariablesFiles.SETTINGS;
2✔
801
    }
802

803
    if (!getToolRepository().getSortedEditions(this.tool).contains(edition)) {
8✔
804
      this.context.warning("Edition {} seems to be invalid", edition);
10✔
805
    }
806
    EnvironmentVariables variables = this.context.getVariables();
4✔
807
    EnvironmentVariables settingsVariables = variables.getByType(destination.toType());
5✔
808
    String name = EnvironmentVariables.getToolEditionVariable(this.tool);
4✔
809
    settingsVariables.set(name, edition, false);
6✔
810
    settingsVariables.save();
2✔
811

812
    this.context.info("{}={} has been set in {}", name, edition, settingsVariables.getSource());
19✔
813
    EnvironmentVariables declaringVariables = variables.findVariable(name);
4✔
814
    if ((declaringVariables != null) && (declaringVariables != settingsVariables)) {
5!
815
      this.context.warning("The variable {} is overridden in {}. Please remove the overridden declaration in order to make the change affect.", name,
13✔
816
          declaringVariables.getSource());
2✔
817
    }
818
    if (hint) {
2!
819
      this.context.info("To install that edition call the following command:");
4✔
820
      this.context.info("ide install {}", this.tool);
11✔
821
    }
822
  }
1✔
823

824
  /**
825
   * Runs the tool's help command to provide the user with usage information.
826
   */
827
  @Override
828
  public void printHelp(NlsBundle bundle) {
829

830
    super.printHelp(bundle);
3✔
831
    String toolHelpArgs = getToolHelpArguments();
3✔
832
    if (toolHelpArgs != null && getInstalledVersion() != null) {
5!
833
      ProcessContext pc = this.context.newProcess().errorHandling(ProcessErrorHandling.LOG_WARNING)
6✔
834
          .executable(Path.of(getBinaryName())).addArgs(toolHelpArgs);
13✔
835
      pc.run(ProcessMode.DEFAULT);
4✔
836
    }
837
  }
1✔
838

839
  /**
840
   * @return the tool's specific help command. Usually help, --help or -h. Return null if not applicable.
841
   */
842
  public String getToolHelpArguments() {
843

844
    return null;
×
845
  }
846

847
  /**
848
   * Creates a start script for the tool using the tool name.
849
   *
850
   * @param targetDir the {@link Path} of the installation where to create the script. If a "bin" sub-folder is present, the script will be created there
851
   *     instead.
852
   * @param binary name of the binary to execute from the start script.
853
   */
854
  protected void createStartScript(Path targetDir, String binary) {
855

856
    createStartScript(targetDir, binary, false);
×
857
  }
×
858

859
  /**
860
   * Creates a start script for the tool using the tool name.
861
   *
862
   * @param targetDir the {@link Path} of the installation where to create the script. If a "bin" sub-folder is present, the script will be created there
863
   *     instead.
864
   * @param binary name of the binary to execute from the start script.
865
   * @param background {@code true} to run the {@code binary} in background, {@code false} otherwise (foreground).
866
   */
867
  protected void createStartScript(Path targetDir, String binary, boolean background) {
868

869
    Path binFolder = targetDir.resolve("bin");
×
870
    if (!Files.exists(binFolder)) {
×
871
      if (this.context.getSystemInfo().isMac()) {
×
872
        MacOsHelper macOsHelper = getMacOsHelper();
×
873
        Path appDir = macOsHelper.findAppDir(targetDir);
×
874
        binFolder = macOsHelper.findLinkDir(appDir, binary);
×
875
      } else {
×
876
        binFolder = targetDir;
×
877
      }
878
      assert (Files.exists(binFolder));
×
879
    }
880
    Path bashFile = binFolder.resolve(getName());
×
881
    String bashFileContentStart = "#!/usr/bin/env bash\n\"$(dirname \"$0\")/";
×
882
    String bashFileContentEnd = "\" $@";
×
883
    if (background) {
×
884
      bashFileContentEnd += " &";
×
885
    }
886
    try {
887
      Files.writeString(bashFile, bashFileContentStart + binary + bashFileContentEnd);
×
888
    } catch (IOException e) {
×
889
      throw new RuntimeException(e);
×
890
    }
×
891
    assert (Files.exists(bashFile));
×
892
    context.getFileAccess().makeExecutable(bashFile);
×
893
  }
×
894

895
  @Override
896
  public void reset() {
897
    super.reset();
2✔
898
    this.executionDirectory = null;
3✔
899
  }
1✔
900

901
  /**
902
   * @param step the {@link Step} to get {@link Step#asSuccess() success logger} from. May be {@code null}.
903
   * @return the {@link IdeSubLogger} from {@link Step#asSuccess()} or {@link IdeContext#success()} as fallback.
904
   */
905
  protected IdeSubLogger asSuccess(Step step) {
906

907
    if (step == null) {
2!
908
      return this.context.success();
4✔
909
    } else {
910
      return step.asSuccess();
×
911
    }
912
  }
913

914

915
  /**
916
   * @param step the {@link Step} to get {@link Step#asError() error logger} from. May be {@code null}.
917
   * @return the {@link IdeSubLogger} from {@link Step#asError()} or {@link IdeContext#error()} as fallback.
918
   */
919
  protected IdeSubLogger asError(Step step) {
920

921
    if (step == null) {
×
922
      return this.context.error();
×
923
    } else {
924
      return step.asError();
×
925
    }
926
  }
927
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc