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

devonfw / IDEasy / 19868191669

02 Dec 2025 05:46PM UTC coverage: 69.852% (+0.07%) from 69.787%
19868191669

push

github

web-flow
#1633: fix CVE check to only suggest unstable versions if the requested version was unstable (#1635)

3835 of 6021 branches covered (63.69%)

Branch coverage included in aggregate %.

9812 of 13516 relevant lines covered (72.6%)

3.16 hits per line

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

76.89
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, null, args);
6✔
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
    return runTool(request, processMode, args);
6✔
191
  }
192

193
  /**
194
   * Ensures the tool is installed and then runs this tool with the given arguments.
195
   *
196
   * @param request the {@link ToolInstallRequest}.
197
   * @param processMode the {@link ProcessMode}. Should typically be {@link ProcessMode#DEFAULT} or {@link ProcessMode#BACKGROUND}.
198
   * @param args the command-line arguments to run the tool.
199
   * @return the {@link ProcessResult result}.
200
   */
201
  public ProcessResult runTool(ToolInstallRequest request, ProcessMode processMode, String... args) {
202

203
    install(request);
4✔
204
    return runTool(request.getProcessContext(), processMode, args);
7✔
205
  }
206

207
  /**
208
   * @param pc the {@link ProcessContext}.
209
   * @param processMode the {@link ProcessMode}. Should typically be {@link ProcessMode#DEFAULT} or {@link ProcessMode#BACKGROUND}.
210
   * @param args the command-line arguments to run the tool.
211
   * @return the {@link ProcessResult result}.
212
   */
213
  public ProcessResult runTool(ProcessContext pc, ProcessMode processMode, String... args) {
214

215
    if (this.executionDirectory != null) {
3!
216
      pc.directory(this.executionDirectory);
×
217
    }
218
    configureToolBinary(pc, processMode);
4✔
219
    configureToolArgs(pc, processMode, args);
5✔
220
    return pc.run(processMode);
4✔
221
  }
222

223
  /**
224
   * @param pc the {@link ProcessContext}.
225
   * @param processMode the {@link ProcessMode}.
226
   */
227
  protected void configureToolBinary(ProcessContext pc, ProcessMode processMode) {
228

229
    pc.executable(Path.of(getBinaryName()));
8✔
230
  }
1✔
231

232
  /**
233
   * @param pc the {@link ProcessContext}.
234
   * @param processMode the {@link ProcessMode}.
235
   * @param args the command-line arguments to {@link ProcessContext#addArgs(Object...) add}.
236
   */
237
  protected void configureToolArgs(ProcessContext pc, ProcessMode processMode, String... args) {
238

239
    pc.addArgs(args);
4✔
240
  }
1✔
241

242
  /**
243
   * Installs or updates the managed {@link #getName() tool}.
244
   *
245
   * @return the {@link ToolInstallation}.
246
   */
247
  public ToolInstallation install() {
248

249
    return install(true);
4✔
250
  }
251

252
  /**
253
   * Performs the installation of the {@link #getName() tool} managed by this {@link com.devonfw.tools.ide.commandlet.Commandlet}.
254
   *
255
   * @param silent - {@code true} if called recursively to suppress verbose logging, {@code false} otherwise.
256
   * @return the {@link ToolInstallation}.
257
   */
258
  public ToolInstallation install(boolean silent) {
259
    return install(new ToolInstallRequest(silent));
7✔
260
  }
261

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

270
    completeRequest(request);
3✔
271
    return doInstall(request);
4✔
272
  }
273

274
  /**
275
   * Performs the installation (install, update, downgrade) of the {@link #getName() tool} managed by this {@link ToolCommandlet}.
276
   *
277
   * @param request the {@link ToolInstallRequest}.
278
   * @return the {@link ToolInstallation}.
279
   */
280
  protected abstract ToolInstallation doInstall(ToolInstallRequest request);
281

282
  /**
283
   * @param request the {@link ToolInstallRequest} to complete (fill values that are currently {@code null}).
284
   */
285
  protected void completeRequest(ToolInstallRequest request) {
286

287
    completeRequestInstalled(request);
3✔
288
    completeRequestRequested(request); // depends on completeRequestInstalled
3✔
289
    completeRequestProcessContext(request);
3✔
290
  }
1✔
291

292
  private void completeRequestProcessContext(ToolInstallRequest request) {
293
    if (request.getProcessContext() == null) {
3✔
294
      ProcessContext pc = this.context.newProcess().errorHandling(ProcessErrorHandling.THROW_CLI);
6✔
295
      request.setProcessContext(pc);
3✔
296
    }
297
  }
1✔
298

299
  private void completeRequestInstalled(ToolInstallRequest request) {
300

301
    ToolEditionAndVersion installedToolVersion = request.getInstalled();
3✔
302
    if (installedToolVersion == null) {
2✔
303
      installedToolVersion = new ToolEditionAndVersion((GenericVersionRange) null);
6✔
304
      request.setInstalled(installedToolVersion);
3✔
305
    }
306
    if (installedToolVersion.getVersion() == null) {
3✔
307
      VersionIdentifier installedVersion = getInstalledVersion();
3✔
308
      if (installedVersion == null) {
2✔
309
        return;
1✔
310
      }
311
      installedToolVersion.setVersion(installedVersion);
3✔
312
    }
313
    if (installedToolVersion.getEdition() == null) {
3✔
314
      installedToolVersion.setEdition(new ToolEdition(this.tool, getInstalledEdition()));
9✔
315
    }
316
    assert installedToolVersion.getResolvedVersion() != null;
4!
317
  }
1✔
318

319
  private void completeRequestRequested(ToolInstallRequest request) {
320

321
    ToolEdition edition;
322
    ToolEditionAndVersion requested = request.getRequested();
3✔
323
    if (requested == null) {
2✔
324
      edition = new ToolEdition(this.tool, getConfiguredEdition());
8✔
325
      requested = new ToolEditionAndVersion(edition);
5✔
326
      request.setRequested(requested);
4✔
327
    } else {
328
      edition = requested.getEdition();
3✔
329
      if (edition == null) {
2✔
330
        edition = new ToolEdition(this.tool, getConfiguredEdition());
8✔
331
        requested.setEdition(edition);
3✔
332
      }
333
    }
334
    GenericVersionRange version = requested.getVersion();
3✔
335
    if (version == null) {
2✔
336
      version = getConfiguredVersion();
3✔
337
      requested.setVersion(version);
3✔
338
    }
339
    VersionIdentifier resolvedVersion = requested.getResolvedVersion();
3✔
340
    if (resolvedVersion == null) {
2✔
341
      if (this.context.isSkipUpdatesMode()) {
4✔
342
        ToolEditionAndVersion installed = request.getInstalled();
3✔
343
        if (installed != null) {
2!
344
          VersionIdentifier installedVersion = installed.getResolvedVersion();
3✔
345
          if (version.contains(installedVersion)) {
4✔
346
            resolvedVersion = installedVersion;
2✔
347
          }
348
        }
349
      }
350
      if (resolvedVersion == null) {
2✔
351
        resolvedVersion = getToolRepository().resolveVersion(this.tool, edition.edition(), version, this);
10✔
352
      }
353
      requested.setResolvedVersion(resolvedVersion);
3✔
354
    }
355
  }
1✔
356

357
  /**
358
   * This method is called after a tool was requested to be installed or updated.
359
   *
360
   * @param request {@code true} the {@link ToolInstallRequest}.
361
   */
362
  protected void postInstall(ToolInstallRequest request) {
363

364
    if (!request.isAlreadyInstalled()) {
3✔
365
      postInstallOnNewInstallation(request);
3✔
366
    }
367
  }
1✔
368

369
  /**
370
   * This method is called after a tool was requested to be installed or updated and a new installation was performed.
371
   *
372
   * @param request {@code true} the {@link ToolInstallRequest}.
373
   */
374
  protected void postInstallOnNewInstallation(ToolInstallRequest request) {
375

376
    // nothing to do by default
377
  }
1✔
378

379
  /**
380
   * @param edition the {@link #getInstalledEdition() edition}.
381
   * @param version the {@link #getInstalledVersion() version}.
382
   * @return the {@link Path} where this tool is installed (physically) or {@code null} if not available.
383
   */
384
  protected abstract Path getInstallationPath(String edition, VersionIdentifier version);
385

386
  /**
387
   * @param request the {@link ToolInstallRequest}.
388
   * @return the existing {@link ToolInstallation}.
389
   */
390
  protected ToolInstallation createExistingToolInstallation(ToolInstallRequest request) {
391

392
    ToolEditionAndVersion installed = request.getInstalled();
3✔
393
    return createExistingToolInstallation(installed.getEdition().edition(), installed.getResolvedVersion(), request.getProcessContext(),
11✔
394
        request.isAdditionalInstallation());
1✔
395
  }
396

397
  /**
398
   * @param edition the {@link #getConfiguredEdition() edition}.
399
   * @param installedVersion the {@link #getConfiguredVersion() version}.
400
   * @param environmentContext the {@link EnvironmentContext}.
401
   * @param extraInstallation {@code true} if the {@link ToolInstallation} is an additional installation to the
402
   *     {@link #getConfiguredVersion() configured version} due to a conflicting version of a {@link ToolDependency}, {@code false} otherwise.
403
   * @return the {@link ToolInstallation}.
404
   */
405
  protected ToolInstallation createExistingToolInstallation(String edition, VersionIdentifier installedVersion, EnvironmentContext environmentContext,
406
      boolean extraInstallation) {
407

408
    Path installationPath = getInstallationPath(edition, installedVersion);
5✔
409
    return createToolInstallation(installationPath, installedVersion, false, environmentContext, extraInstallation);
8✔
410
  }
411

412
  /**
413
   * @param rootDir the {@link ToolInstallation#rootDir() top-level installation directory}.
414
   * @param version the installed {@link VersionIdentifier}.
415
   * @param newInstallation {@link ToolInstallation#newInstallation() new installation} flag.
416
   * @param environmentContext the {@link EnvironmentContext}.
417
   * @param additionalInstallation {@code true} if the {@link ToolInstallation} is an additional installation to the
418
   *     {@link #getConfiguredVersion() configured version} due to a conflicting version of a {@link ToolDependency}, {@code false} otherwise.
419
   * @return the {@link ToolInstallation}.
420
   */
421
  protected ToolInstallation createToolInstallation(Path rootDir, VersionIdentifier version, boolean newInstallation,
422
      EnvironmentContext environmentContext, boolean additionalInstallation) {
423

424
    Path linkDir = rootDir;
2✔
425
    Path binDir = rootDir;
2✔
426
    if (rootDir != null) {
2✔
427
      // on MacOS applications have a very strange structure - see JavaDoc of findLinkDir and ToolInstallation.linkDir for details.
428
      linkDir = getMacOsHelper().findLinkDir(rootDir, getBinaryName());
7✔
429
      binDir = this.context.getFileAccess().getBinPath(linkDir);
6✔
430
    }
431
    return createToolInstallation(rootDir, linkDir, binDir, version, newInstallation, environmentContext, additionalInstallation);
10✔
432
  }
433

434
  /**
435
   * @param rootDir the {@link ToolInstallation#rootDir() top-level installation directory}.
436
   * @param linkDir the {@link ToolInstallation#linkDir() link directory}.
437
   * @param binDir the {@link ToolInstallation#binDir() bin directory}.
438
   * @param version the installed {@link VersionIdentifier}.
439
   * @param newInstallation {@link ToolInstallation#newInstallation() new installation} flag.
440
   * @param environmentContext the {@link EnvironmentContext}.
441
   * @param additionalInstallation {@code true} if the {@link ToolInstallation} is an additional installation to the
442
   *     {@link #getConfiguredVersion() configured version} due to a conflicting version of a {@link ToolDependency}, {@code false} otherwise.
443
   * @return the {@link ToolInstallation}.
444
   */
445
  protected ToolInstallation createToolInstallation(Path rootDir, Path linkDir, Path binDir, VersionIdentifier version, boolean newInstallation,
446
      EnvironmentContext environmentContext, boolean additionalInstallation) {
447

448
    if (linkDir != rootDir) {
3✔
449
      assert (!linkDir.equals(rootDir));
5!
450
      Path toolVersionFile = rootDir.resolve(IdeContext.FILE_SOFTWARE_VERSION);
4✔
451
      if (Files.exists(toolVersionFile)) {
5!
452
        this.context.getFileAccess().copy(toolVersionFile, linkDir, FileCopyMode.COPY_FILE_OVERRIDE);
7✔
453
      }
454
    }
455
    ToolInstallation toolInstallation = new ToolInstallation(rootDir, linkDir, binDir, version, newInstallation);
9✔
456
    setEnvironment(environmentContext, toolInstallation, additionalInstallation);
5✔
457
    return toolInstallation;
2✔
458
  }
459

460
  /**
461
   * Called if the tool {@link ToolInstallRequest#isAlreadyInstalled() is already installed in the correct edition and version} so we can skip the
462
   * installation.
463
   *
464
   * @param request the {@link ToolInstallRequest}.
465
   * @return the {@link ToolInstallation}.
466
   */
467
  protected ToolInstallation toolAlreadyInstalled(ToolInstallRequest request) {
468

469
    logToolAlreadyInstalled(request);
3✔
470
    cveCheck(request);
4✔
471
    postInstall(request);
3✔
472
    return createExistingToolInstallation(request);
4✔
473
  }
474

475
  /**
476
   * Log that the tool is already installed.
477
   *
478
   * @param request the {@link ToolInstallRequest}.
479
   */
480
  protected void logToolAlreadyInstalled(ToolInstallRequest request) {
481
    IdeSubLogger logger;
482
    if (request.isSilent()) {
3✔
483
      logger = this.context.debug();
5✔
484
    } else {
485
      logger = this.context.info();
4✔
486
    }
487
    ToolEditionAndVersion installed = request.getInstalled();
3✔
488
    logger.log("Version {} of tool {} is already installed", installed.getVersion(), installed.getEdition());
16✔
489
  }
1✔
490

491
  /**
492
   * Method to get the home path of the given {@link ToolInstallation}.
493
   *
494
   * @param toolInstallation the {@link ToolInstallation}.
495
   * @return the Path to the home of the tool
496
   */
497
  protected Path getToolHomePath(ToolInstallation toolInstallation) {
498
    return toolInstallation.linkDir();
3✔
499
  }
500

501
  /**
502
   * Method to set environment variables for the process context.
503
   *
504
   * @param environmentContext the {@link EnvironmentContext} where to {@link EnvironmentContext#withEnvVar(String, String) set environment variables} for
505
   *     this tool.
506
   * @param toolInstallation the {@link ToolInstallation}.
507
   * @param additionalInstallation {@code true} if the {@link ToolInstallation} is an additional installation to the
508
   *     {@link #getConfiguredVersion() configured version} due to a conflicting version of a {@link ToolDependency}, {@code false} otherwise.
509
   */
510
  public void setEnvironment(EnvironmentContext environmentContext, ToolInstallation toolInstallation, boolean additionalInstallation) {
511

512
    String pathVariable = EnvironmentVariables.getToolVariablePrefix(this.tool) + "_HOME";
5✔
513
    Path toolHomePath = getToolHomePath(toolInstallation);
4✔
514
    if (toolHomePath != null) {
2✔
515
      environmentContext.withEnvVar(pathVariable, toolHomePath.toString());
6✔
516
    }
517
    if (additionalInstallation) {
2✔
518
      environmentContext.withPathEntry(toolInstallation.binDir());
5✔
519
    }
520
  }
1✔
521

522
  /**
523
   * @return {@code true} to extract (unpack) the downloaded binary file, {@code false} otherwise.
524
   */
525
  protected boolean isExtract() {
526

527
    return true;
2✔
528
  }
529

530
  /**
531
   * 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
532
   * something better, we will suggest this to the user and ask him to make his choice.
533
   *
534
   * @param request the {@link ToolInstallRequest}.
535
   * @return the {@link VersionIdentifier} to install. The will may be asked (unless {@code skipSuggestions} is {@code true}) and might choose a different
536
   *     version than the originally requested one.
537
   */
538
  protected VersionIdentifier cveCheck(ToolInstallRequest request) {
539

540
    ToolEditionAndVersion requested = request.getRequested();
3✔
541
    VersionIdentifier resolvedVersion = requested.getResolvedVersion();
3✔
542
    if (request.isCveCheckDone()) {
3✔
543
      return resolvedVersion;
2✔
544
    }
545
    ToolEdition toolEdition = requested.getEdition();
3✔
546
    GenericVersionRange allowedVersions = requested.getVersion();
3✔
547
    boolean requireStableVersion = true;
2✔
548
    if (allowedVersions instanceof VersionIdentifier vi) {
6✔
549
      requireStableVersion = vi.isStable();
3✔
550
    }
551
    ToolSecurity toolSecurity = this.context.getDefaultToolRepository().findSecurity(this.tool, toolEdition.edition());
9✔
552
    double minSeverity = IdeVariables.CVE_MIN_SEVERITY.get(context);
7✔
553
    Collection<Cve> issues = toolSecurity.findCves(resolvedVersion, this.context, minSeverity);
7✔
554
    ToolVersionChoice currentChoice = ToolVersionChoice.ofCurrent(resolvedVersion, issues);
4✔
555
    request.setCveCheckDone();
2✔
556
    if (logCvesAndReturnTrueForNone(toolEdition, resolvedVersion, currentChoice.option(), issues)) {
8✔
557
      return resolvedVersion;
2✔
558
    }
559
    boolean alreadyInstalled = request.isAlreadyInstalled();
3✔
560
    boolean directForceInstall = this.context.isForceMode() && request.isDirect();
6!
561
    if (alreadyInstalled && !directForceInstall) {
2!
562
      // currently for a transitive dependency it does not make sense to suggest alternative versions, since the choice is not stored anywhere,
563
      // 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
564
      // (e.g. upgrade the tool with the dependency that is causing this).
565
      this.context.interaction("Please run 'ide -f install {}' to check for update suggestions!", this.tool);
×
566
      return resolvedVersion;
×
567
    }
568
    double currentSeveritySum = Cve.severitySum(issues);
3✔
569
    ToolVersionChoice latest = null;
2✔
570
    ToolVersionChoice nearest = null;
2✔
571
    List<VersionIdentifier> toolVersions = getVersions();
3✔
572
    double latestSeveritySum = currentSeveritySum;
2✔
573
    double nearestSeveritySum = currentSeveritySum;
2✔
574
    for (VersionIdentifier version : toolVersions) {
10✔
575
      if (acceptVersion(version, allowedVersions, requireStableVersion)) {
5!
576
        issues = toolSecurity.findCves(version, this.context, minSeverity);
7✔
577
        double newSeveritySum = Cve.severitySum(issues);
3✔
578
        if (newSeveritySum < latestSeveritySum) {
4✔
579
          // we found a better/safer version
580
          if (version.isGreater(resolvedVersion)) {
4!
581
            latest = ToolVersionChoice.ofLatest(version, issues);
4✔
582
            nearest = null;
2✔
583
            latestSeveritySum = newSeveritySum;
3✔
584
          } else {
585
            // latest = null;
586
            nearest = ToolVersionChoice.ofNearest(version, issues);
×
587
            nearestSeveritySum = newSeveritySum;
×
588
          }
589
        } else if (newSeveritySum <= nearestSeveritySum) {
4✔
590
          if ((newSeveritySum < latestSeveritySum) || (nearest == null) || version.isGreater(resolvedVersion)) {
10!
591
            nearest = ToolVersionChoice.ofNearest(version, issues);
4✔
592
          }
593
          nearestSeveritySum = newSeveritySum;
2✔
594
        }
595
      }
596
    }
1✔
597
    if ((latest == null) && (nearest == null)) {
2!
598
      this.context.warning(
×
599
          "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.");
600
      if (alreadyInstalled) {
×
601
        // we came here via "ide -f install ..." but no alternative is available
602
        return resolvedVersion;
×
603
      }
604
    }
605
    List<ToolVersionChoice> choices = new ArrayList<>();
4✔
606
    choices.add(currentChoice);
4✔
607
    boolean addSuggestions;
608
    if (this.context.isForceMode() && request.isDirect()) {
4!
609
      addSuggestions = true;
×
610
    } else {
611
      List<String> skipCveFixTools = IdeVariables.SKIP_CVE_FIX.get(this.context);
6✔
612
      addSuggestions = !skipCveFixTools.contains(this.tool);
8!
613
    }
614
    if (nearest != null) {
2!
615
      if (addSuggestions) {
2!
616
        choices.add(nearest);
4✔
617
      }
618
      logCvesAndReturnTrueForNone(toolEdition, nearest.version(), nearest.option(), nearest.issues());
10✔
619
    }
620
    if (latest != null) {
2!
621
      if (addSuggestions) {
2!
622
        choices.add(latest);
4✔
623
      }
624
      logCvesAndReturnTrueForNone(toolEdition, latest.version(), latest.option(), latest.issues());
10✔
625
    }
626
    ToolVersionChoice[] choicesArray = choices.toArray(ToolVersionChoice[]::new);
8✔
627
    this.context.warning(
4✔
628
        "Please note that by selecting an unsafe version to install, you accept the risk to be attacked.");
629
    ToolVersionChoice answer = this.context.question(choicesArray, "Which version do you want to install?");
9✔
630
    VersionIdentifier version = answer.version();
3✔
631
    requested.setResolvedVersion(version);
3✔
632
    return version;
2✔
633
  }
634

635
  private static boolean acceptVersion(VersionIdentifier version, GenericVersionRange allowedVersions, boolean requireStableVersion) {
636
    if (allowedVersions.isPattern() && !allowedVersions.contains(version)) {
3!
637
      return false;
×
638
    } else if (requireStableVersion && !version.isStable()) {
5!
639
      return false;
×
640
    }
641
    return true;
2✔
642
  }
643

644
  private boolean logCvesAndReturnTrueForNone(ToolEdition toolEdition, VersionIdentifier version, String option, Collection<Cve> issues) {
645
    if (issues.isEmpty()) {
3✔
646
      this.context.info("No CVEs found for {} version {} of tool {}.", option, version, toolEdition);
18✔
647
      return true;
2✔
648
    }
649
    this.context.warning("For {} version {} of tool {} we found {} CVE(s):", option, version, toolEdition, issues.size());
24✔
650
    for (Cve cve : issues) {
10✔
651
      logCve(cve);
3✔
652
    }
1✔
653
    return false;
2✔
654
  }
655

656
  private void logCve(Cve cve) {
657

658
    this.context.warning("{} with severity {} and affected versions: {} ", cve.id(), cve.severity(), cve.versions());
22✔
659
    this.context.warning("https://nvd.nist.gov/vuln/detail/" + cve.id());
6✔
660
    this.context.info("");
4✔
661
  }
1✔
662

663
  /**
664
   * @return the {@link MacOsHelper} instance.
665
   */
666
  protected MacOsHelper getMacOsHelper() {
667

668
    if (this.macOsHelper == null) {
3✔
669
      this.macOsHelper = new MacOsHelper(this.context);
7✔
670
    }
671
    return this.macOsHelper;
3✔
672
  }
673

674
  /**
675
   * @return the currently installed {@link VersionIdentifier version} of this tool or {@code null} if not installed.
676
   */
677
  public abstract VersionIdentifier getInstalledVersion();
678

679
  /**
680
   * @return {@code true} if this tool is installed, {@code false} otherwise.
681
   */
682
  public boolean isInstalled() {
683

684
    return getInstalledVersion() != null;
7✔
685
  }
686

687
  /**
688
   * @return the installed edition of this tool or {@code null} if not installed.
689
   */
690
  public abstract String getInstalledEdition();
691

692
  /**
693
   * Uninstalls the {@link #getName() tool}.
694
   */
695
  public abstract void uninstall();
696

697
  /**
698
   * @return the {@link ToolRepository}.
699
   */
700
  public ToolRepository getToolRepository() {
701

702
    return this.context.getDefaultToolRepository();
4✔
703
  }
704

705
  /**
706
   * List the available editions of this tool.
707
   */
708
  public void listEditions() {
709

710
    List<String> editions = getToolRepository().getSortedEditions(getName());
6✔
711
    for (String edition : editions) {
10✔
712
      this.context.info(edition);
4✔
713
    }
1✔
714
  }
1✔
715

716
  /**
717
   * List the available versions of this tool.
718
   */
719
  public void listVersions() {
720

721
    List<VersionIdentifier> versions = getToolRepository().getSortedVersions(getName(), getConfiguredEdition(), this);
9✔
722
    for (VersionIdentifier vi : versions) {
10✔
723
      this.context.info(vi.toString());
5✔
724
    }
1✔
725
  }
1✔
726

727
  /**
728
   * @return the {@link com.devonfw.tools.ide.tool.repository.DefaultToolRepository#getSortedVersions(String, String, ToolCommandlet) sorted versions} of this
729
   *     tool.
730
   */
731
  public List<VersionIdentifier> getVersions() {
732
    return getToolRepository().getSortedVersions(getName(), getConfiguredEdition(), this);
9✔
733
  }
734

735
  /**
736
   * Sets the tool version in the environment variable configuration file.
737
   *
738
   * @param version the version (pattern) to set.
739
   */
740
  public void setVersion(String version) {
741

742
    if ((version == null) || version.isBlank()) {
×
743
      throw new IllegalStateException("Version has to be specified!");
×
744
    }
745
    VersionIdentifier configuredVersion = VersionIdentifier.of(version);
×
746
    if (!configuredVersion.isPattern() && !configuredVersion.isValid()) {
×
747
      this.context.warning("Version {} seems to be invalid", version);
×
748
    }
749
    setVersion(configuredVersion, true);
×
750
  }
×
751

752
  /**
753
   * Sets the tool version in the environment variable configuration file.
754
   *
755
   * @param version the version to set. May also be a {@link VersionIdentifier#isPattern() version pattern}.
756
   * @param hint - {@code true} to print the installation hint, {@code false} otherwise.
757
   */
758
  public void setVersion(VersionIdentifier version, boolean hint) {
759

760
    setVersion(version, hint, null);
5✔
761
  }
1✔
762

763
  /**
764
   * Sets the tool version in the environment variable configuration file.
765
   *
766
   * @param version the version to set. May also be a {@link VersionIdentifier#isPattern() version pattern}.
767
   * @param hint - {@code true} to print the installation hint, {@code false} otherwise.
768
   * @param destination - the destination for the property to be set
769
   */
770
  public void setVersion(VersionIdentifier version, boolean hint, EnvironmentVariablesFiles destination) {
771

772
    String edition = getConfiguredEdition();
3✔
773
    ToolRepository toolRepository = getToolRepository();
3✔
774

775
    EnvironmentVariables variables = this.context.getVariables();
4✔
776
    if (destination == null) {
2✔
777
      //use default location
778
      destination = EnvironmentVariablesFiles.SETTINGS;
2✔
779
    }
780
    EnvironmentVariables settingsVariables = variables.getByType(destination.toType());
5✔
781
    String name = EnvironmentVariables.getToolVersionVariable(this.tool);
4✔
782

783
    toolRepository.resolveVersion(this.tool, edition, version, this); // verify that the version actually exists
8✔
784
    settingsVariables.set(name, version.toString(), false);
7✔
785
    settingsVariables.save();
2✔
786
    EnvironmentVariables declaringVariables = variables.findVariable(name);
4✔
787
    if ((declaringVariables != null) && (declaringVariables != settingsVariables)) {
5!
788
      this.context.warning("The variable {} is overridden in {}. Please remove the overridden declaration in order to make the change affect.", name,
13✔
789
          declaringVariables.getSource());
2✔
790
    }
791
    if (hint) {
2✔
792
      this.context.info("To install that version call the following command:");
4✔
793
      this.context.info("ide install {}", this.tool);
11✔
794
    }
795
  }
1✔
796

797
  /**
798
   * Sets the tool edition in the environment variable configuration file.
799
   *
800
   * @param edition the edition to set.
801
   */
802
  public void setEdition(String edition) {
803

804
    setEdition(edition, true);
4✔
805
  }
1✔
806

807
  /**
808
   * Sets the tool edition in the environment variable configuration file.
809
   *
810
   * @param edition the edition to set
811
   * @param hint - {@code true} to print the installation hint, {@code false} otherwise.
812
   */
813
  public void setEdition(String edition, boolean hint) {
814

815
    setEdition(edition, hint, null);
5✔
816
  }
1✔
817

818
  /**
819
   * Sets the tool edition in the environment variable configuration file.
820
   *
821
   * @param edition the edition to set
822
   * @param hint - {@code true} to print the installation hint, {@code false} otherwise.
823
   * @param destination - the destination for the property to be set
824
   */
825
  public void setEdition(String edition, boolean hint, EnvironmentVariablesFiles destination) {
826

827
    if ((edition == null) || edition.isBlank()) {
5!
828
      throw new IllegalStateException("Edition has to be specified!");
×
829
    }
830

831
    if (destination == null) {
2✔
832
      //use default location
833
      destination = EnvironmentVariablesFiles.SETTINGS;
2✔
834
    }
835

836
    if (!getToolRepository().getSortedEditions(this.tool).contains(edition)) {
8✔
837
      this.context.warning("Edition {} seems to be invalid", edition);
10✔
838
    }
839
    EnvironmentVariables variables = this.context.getVariables();
4✔
840
    EnvironmentVariables settingsVariables = variables.getByType(destination.toType());
5✔
841
    String name = EnvironmentVariables.getToolEditionVariable(this.tool);
4✔
842
    settingsVariables.set(name, edition, false);
6✔
843
    settingsVariables.save();
2✔
844

845
    this.context.info("{}={} has been set in {}", name, edition, settingsVariables.getSource());
19✔
846
    EnvironmentVariables declaringVariables = variables.findVariable(name);
4✔
847
    if ((declaringVariables != null) && (declaringVariables != settingsVariables)) {
5!
848
      this.context.warning("The variable {} is overridden in {}. Please remove the overridden declaration in order to make the change affect.", name,
13✔
849
          declaringVariables.getSource());
2✔
850
    }
851
    if (hint) {
2!
852
      this.context.info("To install that edition call the following command:");
4✔
853
      this.context.info("ide install {}", this.tool);
11✔
854
    }
855
  }
1✔
856

857
  /**
858
   * Runs the tool's help command to provide the user with usage information.
859
   */
860
  @Override
861
  public void printHelp(NlsBundle bundle) {
862

863
    super.printHelp(bundle);
3✔
864
    String toolHelpArgs = getToolHelpArguments();
3✔
865
    if (toolHelpArgs != null && getInstalledVersion() != null) {
5!
866
      ProcessContext pc = this.context.newProcess().errorHandling(ProcessErrorHandling.LOG_WARNING)
6✔
867
          .executable(Path.of(getBinaryName())).addArgs(toolHelpArgs);
13✔
868
      pc.run(ProcessMode.DEFAULT);
4✔
869
    }
870
  }
1✔
871

872
  /**
873
   * @return the tool's specific help command. Usually help, --help or -h. Return null if not applicable.
874
   */
875
  public String getToolHelpArguments() {
876

877
    return null;
×
878
  }
879

880
  /**
881
   * Creates a start script for the tool using the tool name.
882
   *
883
   * @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
884
   *     instead.
885
   * @param binary name of the binary to execute from the start script.
886
   */
887
  protected void createStartScript(Path targetDir, String binary) {
888

889
    createStartScript(targetDir, binary, false);
×
890
  }
×
891

892
  /**
893
   * Creates a start script for the tool using the tool name.
894
   *
895
   * @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
896
   *     instead.
897
   * @param binary name of the binary to execute from the start script.
898
   * @param background {@code true} to run the {@code binary} in background, {@code false} otherwise (foreground).
899
   */
900
  protected void createStartScript(Path targetDir, String binary, boolean background) {
901

902
    Path binFolder = targetDir.resolve("bin");
×
903
    if (!Files.exists(binFolder)) {
×
904
      if (this.context.getSystemInfo().isMac()) {
×
905
        MacOsHelper macOsHelper = getMacOsHelper();
×
906
        Path appDir = macOsHelper.findAppDir(targetDir);
×
907
        binFolder = macOsHelper.findLinkDir(appDir, binary);
×
908
      } else {
×
909
        binFolder = targetDir;
×
910
      }
911
      assert (Files.exists(binFolder));
×
912
    }
913
    Path bashFile = binFolder.resolve(getName());
×
914
    String bashFileContentStart = "#!/usr/bin/env bash\n\"$(dirname \"$0\")/";
×
915
    String bashFileContentEnd = "\" $@";
×
916
    if (background) {
×
917
      bashFileContentEnd += " &";
×
918
    }
919
    try {
920
      Files.writeString(bashFile, bashFileContentStart + binary + bashFileContentEnd);
×
921
    } catch (IOException e) {
×
922
      throw new RuntimeException(e);
×
923
    }
×
924
    assert (Files.exists(bashFile));
×
925
    context.getFileAccess().makeExecutable(bashFile);
×
926
  }
×
927

928
  @Override
929
  public void reset() {
930
    super.reset();
2✔
931
    this.executionDirectory = null;
3✔
932
  }
1✔
933

934
  /**
935
   * @param step the {@link Step} to get {@link Step#asSuccess() success logger} from. May be {@code null}.
936
   * @return the {@link IdeSubLogger} from {@link Step#asSuccess()} or {@link IdeContext#success()} as fallback.
937
   */
938
  protected IdeSubLogger asSuccess(Step step) {
939

940
    if (step == null) {
2!
941
      return this.context.success();
4✔
942
    } else {
943
      return step.asSuccess();
×
944
    }
945
  }
946

947

948
  /**
949
   * @param step the {@link Step} to get {@link Step#asError() error logger} from. May be {@code null}.
950
   * @return the {@link IdeSubLogger} from {@link Step#asError()} or {@link IdeContext#error()} as fallback.
951
   */
952
  protected IdeSubLogger asError(Step step) {
953

954
    if (step == null) {
×
955
      return this.context.error();
×
956
    } else {
957
      return step.asError();
×
958
    }
959
  }
960
}
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