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

devonfw / IDEasy / 30638110943

31 Jul 2026 02:19PM UTC coverage: 72.649% (+0.008%) from 72.641%
30638110943

Pull #2144

github

web-flow
Merge 57128bd73 into 468118d46
Pull Request #2144: #1976: extend tool commandlet installation logic

5048 of 7683 branches covered (65.7%)

Branch coverage included in aggregate %.

13102 of 17300 relevant lines covered (75.73%)

3.22 hits per line

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

74.18
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.List;
8
import java.util.Objects;
9
import java.util.Set;
10
import java.util.regex.Matcher;
11
import java.util.regex.Pattern;
12

13
import org.slf4j.Logger;
14
import org.slf4j.LoggerFactory;
15
import org.slf4j.event.Level;
16

17
import com.devonfw.tools.ide.commandlet.Commandlet;
18
import com.devonfw.tools.ide.common.Tag;
19
import com.devonfw.tools.ide.common.Tags;
20
import com.devonfw.tools.ide.completion.AutoCompletionRegistry;
21
import com.devonfw.tools.ide.completion.CompletionCandidateCollector;
22
import com.devonfw.tools.ide.context.IdeContext;
23
import com.devonfw.tools.ide.environment.EnvironmentVariables;
24
import com.devonfw.tools.ide.environment.EnvironmentVariablesFiles;
25
import com.devonfw.tools.ide.log.IdeLogLevel;
26
import com.devonfw.tools.ide.nls.NlsBundle;
27
import com.devonfw.tools.ide.os.MacOsHelper;
28
import com.devonfw.tools.ide.process.EnvironmentContext;
29
import com.devonfw.tools.ide.process.ProcessContext;
30
import com.devonfw.tools.ide.process.ProcessErrorHandling;
31
import com.devonfw.tools.ide.process.ProcessMode;
32
import com.devonfw.tools.ide.process.ProcessResult;
33
import com.devonfw.tools.ide.process.ProcessResultImpl;
34
import com.devonfw.tools.ide.property.Property;
35
import com.devonfw.tools.ide.property.ToolArgumentsProperty;
36
import com.devonfw.tools.ide.security.ToolVersionChoice;
37
import com.devonfw.tools.ide.security.ToolVulnerabilities;
38
import com.devonfw.tools.ide.step.Step;
39
import com.devonfw.tools.ide.tool.repository.ToolRepository;
40
import com.devonfw.tools.ide.url.model.file.json.Cve;
41
import com.devonfw.tools.ide.url.model.file.json.ToolDependency;
42
import com.devonfw.tools.ide.url.model.file.json.ToolSecurity;
43
import com.devonfw.tools.ide.variable.IdeVariables;
44
import com.devonfw.tools.ide.version.GenericVersionRange;
45
import com.devonfw.tools.ide.version.VersionIdentifier;
46

47
/**
48
 * {@link Commandlet} for a tool integrated into the IDE.
49
 */
50
public abstract class ToolCommandlet extends Commandlet implements Tags {
51

52
  private static final Logger LOG = LoggerFactory.getLogger(ToolCommandlet.class);
4✔
53

54
  /** @see #getName() */
55
  protected final String tool;
56

57
  private final Set<Tag> tags;
58

59
  /** The commandline arguments to pass to the tool. */
60
  public final ToolArgumentsProperty arguments;
61

62
  private Path executionDirectory;
63

64
  private MacOsHelper macOsHelper;
65

66
  /**
67
   * Registry for tool-specific auto-completion candidates.
68
   */
69
  private AutoCompletionRegistry autoCompletionRegistry;
70

71
  /**
72
   * The constructor.
73
   *
74
   * @param context the {@link IdeContext}.
75
   * @param tool the {@link #getName() tool name}.
76
   * @param tags the {@link #getTags() tags} classifying the tool. Should be created via {@link Set#of(Object) Set.of} method.
77
   */
78
  public ToolCommandlet(IdeContext context, String tool, Set<Tag> tags) {
79

80
    super(context);
3✔
81
    this.tool = tool;
3✔
82
    this.tags = tags;
3✔
83
    addKeyword(tool);
3✔
84
    this.arguments = new ToolArgumentsProperty("", false, true, "args");
9✔
85
    initProperties();
2✔
86
  }
1✔
87

88
  /**
89
   * Gets the auto-completion registry for this tool.
90
   *
91
   * @return the {@link AutoCompletionRegistry}.
92
   */
93
  protected AutoCompletionRegistry getAutoCompletionRegistry() {
94

95
    if (this.autoCompletionRegistry == null) {
3!
96
      this.autoCompletionRegistry = new AutoCompletionRegistry();
5✔
97
      initAutoCompletionRegistry(this.autoCompletionRegistry);
4✔
98
    }
99

100
    return this.autoCompletionRegistry;
3✔
101
  }
102

103

104
  /**
105
   * Initializes the auto-completion registry for this tool.
106
   *
107
   * @param registry the {@link AutoCompletionRegistry} to initialize.
108
   */
109
  protected void initAutoCompletionRegistry(AutoCompletionRegistry registry) {
110
    // default empty
111
  }
×
112

113
  /**
114
   * Completes tool-specific arguments.
115
   *
116
   * @param arg the current argument to complete.
117
   * @param collector the {@link CompletionCandidateCollector}.
118
   * @param property the {@link Property} that triggered completion.
119
   */
120
  public void completeToolArguments(String arg, CompletionCandidateCollector collector, Property<?> property) {
121

122
    getAutoCompletionRegistry().complete(arg, collector, property, this);
7✔
123
  }
1✔
124

125
  /**
126
   * Add initial Properties to the tool
127
   */
128
  protected void initProperties() {
129

130
    add(this.arguments);
5✔
131
  }
1✔
132

133
  /**
134
   * @return the name of the tool (e.g. "java", "mvn", "npm", "node").
135
   */
136
  @Override
137
  public final String getName() {
138

139
    return this.tool;
3✔
140
  }
141

142
  /**
143
   * @return the name of the binary executable for this tool.
144
   */
145
  protected String getBinaryName() {
146

147
    return this.tool;
3✔
148
  }
149

150
  /**
151
   * @return the {@link Path} to the installed {@link #getBinaryName() binary} or {@code null} if not found on the
152
   *     {@link com.devonfw.tools.ide.common.SystemPath}.
153
   */
154
  protected Path getBinaryExecutable() {
155

156
    Path binary = this.context.getPath().findBinaryPathByName(getBinaryName());
×
157
    if (binary.getParent() == null) {
×
158
      return null;
×
159
    }
160
    return binary;
×
161
  }
162

163
  @Override
164
  public final Set<Tag> getTags() {
165

166
    return this.tags;
3✔
167
  }
168

169
  /**
170
   * @return the execution directory where the tool will be executed. Will be {@code null} by default leading to execution in the users current working
171
   *     directory where IDEasy was called.
172
   * @see #setExecutionDirectory(Path)
173
   */
174
  public Path getExecutionDirectory() {
175
    return this.executionDirectory;
×
176
  }
177

178
  /**
179
   * @param executionDirectory the new value of {@link #getExecutionDirectory()}.
180
   */
181
  public void setExecutionDirectory(Path executionDirectory) {
182
    this.executionDirectory = executionDirectory;
×
183
  }
×
184

185
  /**
186
   * @return the {@link EnvironmentVariables#getToolVersion(String) tool version}.
187
   */
188
  public VersionIdentifier getConfiguredVersion() {
189

190
    return this.context.getVariables().getToolVersion(getName());
7✔
191
  }
192

193
  /**
194
   * @return the {@link EnvironmentVariables#getToolEdition(String) tool edition}.
195
   */
196
  public String getConfiguredEdition() {
197

198
    return this.context.getVariables().getToolEdition(getName());
7✔
199
  }
200

201
  /**
202
   * @return the {@link ToolEdition} with {@link #getName() tool} with its {@link #getConfiguredEdition() edition}.
203
   */
204
  protected final ToolEdition getToolWithConfiguredEdition() {
205

206
    return new ToolEdition(this.tool, getConfiguredEdition());
8✔
207
  }
208

209
  @Override
210
  protected void doRun() {
211

212
    runTool(this.arguments.asList());
6✔
213
  }
1✔
214

215
  /**
216
   * @param args the command-line arguments to run the tool.
217
   * @return the {@link ProcessResult result}.
218
   * @see ToolCommandlet#runTool(ProcessMode, GenericVersionRange, List)
219
   */
220
  public ProcessResult runTool(List<String> args) {
221

222
    return runTool(ProcessMode.DEFAULT, null, args);
6✔
223
  }
224

225
  /**
226
   * Ensures the tool is installed and then runs this tool with the given arguments.
227
   *
228
   * @param processMode the {@link ProcessMode}. Should typically be {@link ProcessMode#DEFAULT} or {@link ProcessMode#BACKGROUND}.
229
   * @param toolVersion the explicit {@link GenericVersionRange version} to run. Typically {@code null} to run the
230
   *     {@link #getConfiguredVersion() configured version}. Otherwise, the specified version will be used (from the software repository, if not compatible).
231
   * @param args the command-line arguments to run the tool.
232
   * @return the {@link ProcessResult result}.
233
   */
234
  public final ProcessResult runTool(ProcessMode processMode, GenericVersionRange toolVersion, List<String> args) {
235

236
    return runTool(processMode, toolVersion, ProcessErrorHandling.THROW_CLI, args);
7✔
237
  }
238

239
  /**
240
   * Ensures the tool is installed and then runs this tool with the given arguments.
241
   *
242
   * @param processMode the {@link ProcessMode}. Should typically be {@link ProcessMode#DEFAULT} or {@link ProcessMode#BACKGROUND}.
243
   * @param toolVersion the explicit {@link GenericVersionRange version} to run. Typically {@code null} to run the
244
   *     {@link #getConfiguredVersion() configured version}. Otherwise, the specified version will be used (from the software repository, if not compatible).
245
   * @param errorHandling the {@link ProcessErrorHandling}.
246
   * @param args the command-line arguments to run the tool.
247
   * @return the {@link ProcessResult result}.
248
   */
249
  public ProcessResult runTool(ProcessMode processMode, GenericVersionRange toolVersion, ProcessErrorHandling errorHandling, List<String> args) {
250

251
    ProcessContext pc = this.context.newProcess().errorHandling(errorHandling);
6✔
252
    ToolInstallRequest request = new ToolInstallRequest(true);
5✔
253
    if (toolVersion != null) {
2!
254
      request.setRequested(new ToolEditionAndVersion(toolVersion));
×
255
    }
256
    request.setProcessContext(pc);
3✔
257
    return runTool(request, processMode, args);
6✔
258
  }
259

260
  /**
261
   * Ensures the tool is installed and then runs this tool with the given arguments.
262
   *
263
   * @param request the {@link ToolInstallRequest}.
264
   * @param processMode the {@link ProcessMode}. Should typically be {@link ProcessMode#DEFAULT} or {@link ProcessMode#BACKGROUND}.
265
   * @param args the command-line arguments to run the tool.
266
   * @return the {@link ProcessResult result}.
267
   */
268
  public ProcessResult runTool(ToolInstallRequest request, ProcessMode processMode, List<String> args) {
269

270
    if (request.isCveCheckDone()) {
3!
271
      // if the CVE check has already been done, we can assume that the install(request) has already been called before
272
      // most likely a postInstall* method was overridden calling this method with the same request what is a programming error
273
      // we render this warning so the error gets detected and can be fixed but we do not block the user by skipping the installation.
274
      LOG.warn("Preventing infinity loop during installation of {}", request.getRequested(), new RuntimeException());
×
275
    } else {
276
      ToolInstallation installation = install(request);
4✔
277
      if (installation != null && installation.installedAsynchronously()) {
5!
278
        return new ProcessResultImpl(this.tool, this.tool, 0, List.of());
10✔
279
      }
280
    }
281
    return runTool(request.getProcessContext(), processMode, args);
7✔
282
  }
283

284
  /**
285
   * @param pc the {@link ProcessContext}.
286
   * @param processMode the {@link ProcessMode}. Should typically be {@link ProcessMode#DEFAULT} or {@link ProcessMode#BACKGROUND}.
287
   * @param args the command-line arguments to run the tool.
288
   * @return the {@link ProcessResult result}.
289
   */
290
  public ProcessResult runTool(ProcessContext pc, ProcessMode processMode, List<String> args) {
291

292
    if (this.executionDirectory != null) {
3!
293
      pc.directory(this.executionDirectory);
×
294
    }
295
    configureToolBinary(pc, processMode);
4✔
296
    configureToolArgs(pc, processMode, args);
5✔
297
    return pc.run(processMode);
4✔
298
  }
299

300
  /**
301
   * @param pc the {@link ProcessContext}.
302
   * @param processMode the {@link ProcessMode}.
303
   */
304
  protected void configureToolBinary(ProcessContext pc, ProcessMode processMode) {
305

306
    pc.executable(Path.of(getBinaryName()));
8✔
307
  }
1✔
308

309
  /**
310
   * @param pc the {@link ProcessContext}.
311
   * @param processMode the {@link ProcessMode}.
312
   * @param args the command-line arguments to {@link ProcessContext#addArgs(List) add}.
313
   */
314
  protected void configureToolArgs(ProcessContext pc, ProcessMode processMode, List<String> args) {
315

316
    pc.addArgs(args);
4✔
317
  }
1✔
318

319
  /**
320
   * Installs or updates the managed {@link #getName() tool}.
321
   *
322
   * @return the {@link ToolInstallation}.
323
   */
324
  public ToolInstallation install() {
325

326
    return install(true);
4✔
327
  }
328

329
  /**
330
   * Performs the installation of the {@link #getName() tool} managed by this {@link com.devonfw.tools.ide.commandlet.Commandlet}.
331
   *
332
   * @param silent - {@code true} if called recursively to suppress verbose logging, {@code false} otherwise.
333
   * @return the {@link ToolInstallation}.
334
   */
335
  public ToolInstallation install(boolean silent) {
336
    return install(new ToolInstallRequest(silent));
7✔
337
  }
338

339
  /**
340
   * Performs the installation (install, update, downgrade) of the {@link #getName() tool} managed by this {@link ToolCommandlet}.
341
   *
342
   * @param request the {@link ToolInstallRequest}.
343
   * @return the {@link ToolInstallation}.
344
   */
345
  public ToolInstallation install(ToolInstallRequest request) {
346

347
    completeRequest(request);
3✔
348
    if (request.isInstallLoop()) {
3!
349
      return toolAlreadyInstalled(request);
×
350
    }
351
    ToolInstallation installation = doInstall(request);
4✔
352
    if (installation != null && installation.installedAsynchronously()) {
5!
353
      LOG.warn(
4✔
354
          "The installation of {} is currently running in the background!\nYou need to complete the installation, potentially "
355
              + "reboot and rerun your 'ide' command in a new terminal session after the installation has completed.",
356
          request.getRequested());
1✔
357
    }
358
    return installation;
2✔
359
  }
360

361
  /**
362
   * Performs the installation (install, update, downgrade) of the {@link #getName() tool} managed by this {@link ToolCommandlet}.
363
   *
364
   * @param request the {@link ToolInstallRequest}.
365
   * @return the {@link ToolInstallation}.
366
   */
367
  protected abstract ToolInstallation doInstall(ToolInstallRequest request);
368

369
  /**
370
   * @param request the {@link ToolInstallRequest} to complete (fill values that are currently {@code null}).
371
   */
372
  protected void completeRequest(ToolInstallRequest request) {
373

374
    completeRequestInstalled(request);
3✔
375
    completeRequestRequested(request); // depends on completeRequestInstalled
3✔
376
    completeRequestProcessContext(request);
3✔
377
    completeRequestToolPath(request);
3✔
378
  }
1✔
379

380
  private void completeRequestProcessContext(ToolInstallRequest request) {
381
    if (request.getProcessContext() == null) {
3✔
382
      ProcessContext pc = this.context.newProcess().errorHandling(ProcessErrorHandling.THROW_CLI);
6✔
383
      request.setProcessContext(pc);
3✔
384
    }
385
  }
1✔
386

387
  private void completeRequestInstalled(ToolInstallRequest request) {
388

389
    ToolEditionAndVersion installedToolVersion = request.getInstalled();
3✔
390
    if (installedToolVersion == null) {
2✔
391
      installedToolVersion = new ToolEditionAndVersion((GenericVersionRange) null);
6✔
392
      request.setInstalled(installedToolVersion);
3✔
393
    }
394
    Path toolPath = request.getToolPath();
3✔
395
    if (installedToolVersion.getVersion() == null) {
3✔
396
      VersionIdentifier installedVersion;
397
      if ((toolPath != null) && (this instanceof LocalToolCommandlet ltc)) {
10!
398
        installedVersion = ltc.getInstalledVersion(toolPath);
5✔
399
      } else {
400
        installedVersion = getInstalledVersion();
3✔
401
      }
402
      if (installedVersion == null) {
2✔
403
        return;
1✔
404
      }
405
      installedToolVersion.setVersion(installedVersion);
3✔
406
    }
407
    if (installedToolVersion.getEdition() == null) {
3✔
408
      String installedEdition;
409
      if ((toolPath != null) && (this instanceof LocalToolCommandlet ltc)) {
2!
410
        installedEdition = ltc.getInstalledEdition(toolPath);
×
411
      } else {
412
        installedEdition = getInstalledEdition();
3✔
413
      }
414
      installedToolVersion.setEdition(new ToolEdition(this.tool, installedEdition));
8✔
415
    }
416
    assert installedToolVersion.getResolvedVersion() != null;
4!
417
  }
1✔
418

419
  private void completeRequestRequested(ToolInstallRequest request) {
420

421
    ToolEdition edition;
422
    ToolEditionAndVersion requested = request.getRequested();
3✔
423
    if (requested == null) {
2✔
424
      edition = new ToolEdition(this.tool, getConfiguredEdition());
8✔
425
      requested = new ToolEditionAndVersion(edition);
5✔
426
      request.setRequested(requested);
4✔
427

428
    } else {
429
      edition = requested.getEdition();
3✔
430
      if (edition == null) {
2✔
431
        // If no edition was specified, set it to the configured one
432
        edition = new ToolEdition(this.tool, getConfiguredEdition());
8✔
433
        requested.setEdition(edition);
3✔
434
      }
435
    }
436

437
    // Adjust edition if necessary based on requested version. This is needed for tools like IntelliJ where we may need to automatically switch editions
438
    requested = adjustRequestedEdition(requested);
4✔
439
    edition = requested.getEdition();
3✔
440

441
    GenericVersionRange version = requested.getVersion();
3✔
442
    if (version == null) {
2✔
443
      version = request.isIgnoreProject() ? VersionIdentifier.LATEST : getConfiguredVersion();
8✔
444
      requested.setVersion(version);
3✔
445
    }
446
    VersionIdentifier resolvedVersion = requested.getResolvedVersion();
3✔
447
    if (resolvedVersion == null) {
2✔
448
      if (this.context.isSkipUpdatesMode()) {
4✔
449
        ToolEditionAndVersion installed = request.getInstalled();
3✔
450
        if (installed != null) {
2!
451
          VersionIdentifier installedVersion = installed.getResolvedVersion();
3✔
452
          if (version.contains(installedVersion)) {
4✔
453
            resolvedVersion = installedVersion;
2✔
454
          }
455
        }
456
      }
457
      if (resolvedVersion == null) {
2✔
458
        resolvedVersion = getToolRepository().resolveVersion(this.tool, edition.edition(), version, this);
10✔
459
      }
460
      requested.setResolvedVersion(resolvedVersion);
3✔
461
    }
462
  }
1✔
463

464
  /**
465
   * Hook for subclasses to adjust the requested tool edition before the version is finalized.
466
   *
467
   * @param requested the requested {@link ToolEditionAndVersion}
468
   * @return the given or trgansformed {@link ToolEditionAndVersion}
469
   */
470
  protected ToolEditionAndVersion adjustRequestedEdition(ToolEditionAndVersion requested) {
471

472
    // default no-op
473
    return requested;
2✔
474
  }
475

476

477
  private void completeRequestToolPath(ToolInstallRequest request) {
478

479
    Path toolPath = request.getToolPath();
3✔
480
    if (toolPath == null) {
2✔
481
      toolPath = getToolPath();
3✔
482
      request.setToolPath(toolPath);
3✔
483
    }
484
  }
1✔
485

486
  /**
487
   * @return the {@link Path} where the tool is located (installed). Will be {@code null} for global tools that do not know the {@link Path} since it is
488
   *     determined by the installer.
489
   */
490
  public Path getToolPath() {
491
    return null;
×
492
  }
493

494
  /**
495
   * This method is called after a tool was requested to be installed or updated.
496
   *
497
   * @param request {@code true} the {@link ToolInstallRequest}.
498
   */
499
  protected void postInstall(ToolInstallRequest request) {
500

501
    if (!request.isAlreadyInstalled()) {
3✔
502
      postInstallOnNewInstallation(request);
3✔
503
    }
504
  }
1✔
505

506
  /**
507
   * This method is called after a tool was requested to be installed or updated and a new installation was performed.
508
   *
509
   * @param request {@code true} the {@link ToolInstallRequest}.
510
   */
511
  protected void postInstallOnNewInstallation(ToolInstallRequest request) {
512

513
    // nothing to do by default
514
  }
1✔
515

516
  /**
517
   * @param edition the {@link #getInstalledEdition() edition}.
518
   * @param version the {@link #getInstalledVersion() version}.
519
   * @return the {@link Path} where this tool is installed (physically) or {@code null} if not available.
520
   */
521
  protected abstract Path getInstallationPath(String edition, VersionIdentifier version);
522

523
  /**
524
   * @param request the {@link ToolInstallRequest}.
525
   * @return the existing {@link ToolInstallation}.
526
   */
527
  protected ToolInstallation createExistingToolInstallation(ToolInstallRequest request) {
528

529
    ToolEditionAndVersion installed = request.getInstalled();
3✔
530

531
    String edition = this.tool;
3✔
532
    VersionIdentifier resolvedVersion = VersionIdentifier.LATEST;
2✔
533

534
    if (installed != null) {
2!
535
      if (installed.getEdition() != null) {
3!
536
        edition = installed.getEdition().edition();
4✔
537
      }
538
      if (installed.getResolvedVersion() != null) {
3!
539
        resolvedVersion = installed.getResolvedVersion();
3✔
540
      }
541
    }
542

543
    return createExistingToolInstallation(edition, resolvedVersion, request.getProcessContext(),
8✔
544
        request.isAdditionalInstallation());
1✔
545
  }
546

547
  /**
548
   * @param edition the {@link #getConfiguredEdition() edition}.
549
   * @param installedVersion the {@link #getConfiguredVersion() version}.
550
   * @param environmentContext the {@link EnvironmentContext}.
551
   * @param extraInstallation {@code true} if the {@link ToolInstallation} is an additional installation to the
552
   *     {@link #getConfiguredVersion() configured version} due to a conflicting version of a {@link ToolDependency}, {@code false} otherwise.
553
   * @return the {@link ToolInstallation}.
554
   */
555
  protected ToolInstallation createExistingToolInstallation(String edition, VersionIdentifier installedVersion, EnvironmentContext environmentContext,
556
      boolean extraInstallation) {
557

558
    Path installationPath = getInstallationPath(edition, installedVersion);
5✔
559
    return createToolInstallation(installationPath, installedVersion, false, environmentContext, extraInstallation);
8✔
560
  }
561

562
  /**
563
   * @param rootDir the {@link ToolInstallation#rootDir() top-level installation directory}.
564
   * @param version the installed {@link VersionIdentifier}.
565
   * @param newInstallation {@link ToolInstallation#newInstallation() new installation} flag.
566
   * @param environmentContext the {@link EnvironmentContext}.
567
   * @param additionalInstallation {@code true} if the {@link ToolInstallation} is an additional installation to the
568
   *     {@link #getConfiguredVersion() configured version} due to a conflicting version of a {@link ToolDependency}, {@code false} otherwise.
569
   * @return the {@link ToolInstallation}.
570
   */
571
  protected ToolInstallation createToolInstallation(Path rootDir, VersionIdentifier version, boolean newInstallation,
572
      EnvironmentContext environmentContext, boolean additionalInstallation) {
573

574
    Path linkDir = rootDir;
2✔
575
    Path binDir = rootDir;
2✔
576
    if (rootDir != null) {
2!
577
      // on MacOS applications have a very strange structure - see JavaDoc of findLinkDir and ToolInstallation.linkDir for details.
578
      linkDir = getMacOsHelper().findLinkDir(rootDir, getBinaryName());
7✔
579
      binDir = this.context.getFileAccess().getBinPath(linkDir);
6✔
580
    }
581
    return createToolInstallation(rootDir, linkDir, binDir, version, newInstallation, environmentContext, additionalInstallation);
10✔
582
  }
583

584
  /**
585
   * @param rootDir the {@link ToolInstallation#rootDir() top-level installation directory}.
586
   * @param linkDir the {@link ToolInstallation#linkDir() link directory}.
587
   * @param binDir the {@link ToolInstallation#binDir() bin directory}.
588
   * @param version the installed {@link VersionIdentifier}.
589
   * @param newInstallation {@link ToolInstallation#newInstallation() new installation} flag.
590
   * @param environmentContext the {@link EnvironmentContext}.
591
   * @param additionalInstallation {@code true} if the {@link ToolInstallation} is an additional installation to the
592
   *     {@link #getConfiguredVersion() configured version} due to a conflicting version of a {@link ToolDependency}, {@code false} otherwise.
593
   * @return the {@link ToolInstallation}.
594
   */
595
  protected ToolInstallation createToolInstallation(Path rootDir, Path linkDir, Path binDir, VersionIdentifier version, boolean newInstallation,
596
      EnvironmentContext environmentContext, boolean additionalInstallation) {
597

598
    // do not copy the version file into macOS .app bundles: changing the bundle after codesigning breaks the seal.
599
    ToolInstallation toolInstallation = new ToolInstallation(rootDir, linkDir, binDir, version, newInstallation);
9✔
600
    setEnvironment(environmentContext, toolInstallation, additionalInstallation);
5✔
601
    return toolInstallation;
2✔
602
  }
603

604
  /**
605
   * Called if the tool {@link ToolInstallRequest#isAlreadyInstalled() is already installed in the correct edition and version} so we can skip the
606
   * installation.
607
   *
608
   * @param request the {@link ToolInstallRequest}.
609
   * @return the {@link ToolInstallation}.
610
   */
611
  protected ToolInstallation toolAlreadyInstalled(ToolInstallRequest request) {
612

613
    logToolAlreadyInstalled(request);
3✔
614
    cveCheck(request);
4✔
615
    postInstall(request);
3✔
616
    return createExistingToolInstallation(request);
4✔
617
  }
618

619
  /**
620
   * Log that the tool is already installed.
621
   *
622
   * @param request the {@link ToolInstallRequest}.
623
   */
624
  protected void logToolAlreadyInstalled(ToolInstallRequest request) {
625
    Level level;
626
    if (request.isSilent()) {
3✔
627
      level = Level.DEBUG;
3✔
628
    } else {
629
      level = Level.INFO;
2✔
630
    }
631
    ToolEditionAndVersion installed = request.getInstalled();
3✔
632
    LOG.atLevel(level).log("Version {} of tool {} is already installed", installed.getVersion(), installed.getEdition());
9✔
633
  }
1✔
634

635
  /**
636
   * Method to get the home path of the given {@link ToolInstallation}.
637
   *
638
   * @param toolInstallation the {@link ToolInstallation}.
639
   * @return the Path to the home of the tool
640
   */
641
  protected Path getToolHomePath(ToolInstallation toolInstallation) {
642
    return toolInstallation.linkDir();
3✔
643
  }
644

645
  /**
646
   * Method to set environment variables for the process context.
647
   *
648
   * @param environmentContext the {@link EnvironmentContext} where to {@link EnvironmentContext#withEnvVar(String, String) set environment variables} for
649
   *     this tool.
650
   * @param toolInstallation the {@link ToolInstallation}.
651
   * @param additionalInstallation {@code true} if the {@link ToolInstallation} is an additional installation to the
652
   *     {@link #getConfiguredVersion() configured version} due to a conflicting version of a {@link ToolDependency}, {@code false} otherwise.
653
   */
654
  public void setEnvironment(EnvironmentContext environmentContext, ToolInstallation toolInstallation, boolean additionalInstallation) {
655

656
    String pathVariable = EnvironmentVariables.getToolVariablePrefix(this.tool) + "_HOME";
5✔
657
    Path toolHomePath = getToolHomePath(toolInstallation);
4✔
658
    if (toolHomePath != null) {
2!
659
      environmentContext.withEnvVar(pathVariable, toolHomePath.toString());
6✔
660
    }
661
    if (additionalInstallation) {
2✔
662
      environmentContext.withPathEntry(toolInstallation.binDir());
5✔
663
    }
664
  }
1✔
665

666
  /**
667
   * @return {@code true} to extract (unpack) the downloaded binary file, {@code false} otherwise.
668
   */
669
  protected boolean isExtract() {
670

671
    return true;
2✔
672
  }
673

674
  /**
675
   * 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
676
   * something better, we will suggest this to the user and ask him to make his choice.
677
   *
678
   * @param request the {@link ToolInstallRequest}.
679
   * @return the {@link VersionIdentifier} to install. The will may be asked (unless {@code skipSuggestions} is {@code true}) and might choose a different
680
   *     version than the originally requested one.
681
   */
682
  protected VersionIdentifier cveCheck(ToolInstallRequest request) {
683

684
    ToolEditionAndVersion requested = request.getRequested();
3✔
685
    VersionIdentifier resolvedVersion = requested.getResolvedVersion();
3✔
686
    if (request.isCveCheckDone()) {
3✔
687
      return resolvedVersion;
2✔
688
    }
689
    ToolEdition toolEdition = requested.getEdition();
3✔
690
    GenericVersionRange allowedVersions = requested.getVersion();
3✔
691
    boolean requireStableVersion = true;
2✔
692
    if (allowedVersions instanceof VersionIdentifier vi) {
6✔
693
      requireStableVersion = vi.isStable();
3✔
694
    }
695
    ToolSecurity toolSecurity = this.context.getDefaultToolRepository().findSecurity(this.tool, toolEdition.edition());
9✔
696
    double minSeverity = IdeVariables.CVE_MIN_SEVERITY.get(context);
7✔
697
    ToolVulnerabilities currentVulnerabilities = toolSecurity.findCves(resolvedVersion, minSeverity);
5✔
698
    ToolVersionChoice currentChoice = ToolVersionChoice.ofCurrent(requested, currentVulnerabilities);
4✔
699
    request.setCveCheckDone();
2✔
700
    if (currentChoice.logAndCheckIfEmpty()) {
3✔
701
      return resolvedVersion;
2✔
702
    }
703
    boolean alreadyInstalled = request.isAlreadyInstalled();
3✔
704
    boolean directForceInstall = this.context.isForceMode() && request.isDirect();
6!
705
    if (alreadyInstalled && !directForceInstall) {
2!
706
      // currently for a transitive dependency it does not make sense to suggest alternative versions, since the choice is not stored anywhere,
707
      // 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
708
      // (e.g. upgrade the tool with the dependency that is causing this).
709
      IdeLogLevel.INTERACTION.log(LOG, "Please run 'ide -f install {}' to check for update suggestions!", this.tool);
×
710
      return resolvedVersion;
×
711
    }
712
    ToolVersionChoice latest = null;
2✔
713
    ToolVulnerabilities latestVulnerabilities = currentVulnerabilities;
2✔
714
    ToolVersionChoice nearest = null;
2✔
715
    ToolVulnerabilities nearestVulnerabilities = currentVulnerabilities;
2✔
716
    List<VersionIdentifier> toolVersions = getVersions();
3✔
717
    for (VersionIdentifier version : toolVersions) {
10✔
718

719
      if (Objects.equals(version, resolvedVersion)) {
4✔
720
        continue; // Skip the entire iteration for resolvedVersion
1✔
721
      }
722

723
      if (acceptVersion(version, allowedVersions, requireStableVersion)) {
5!
724
        ToolVulnerabilities newVulnerabilities = toolSecurity.findCves(version, minSeverity);
5✔
725
        if (newVulnerabilities.isSafer(latestVulnerabilities)) {
4✔
726
          // we found a better/safer version
727
          ToolEditionAndVersion toolEditionAndVersion = new ToolEditionAndVersion(toolEdition, version);
6✔
728
          if (version.isGreater(resolvedVersion)) {
4!
729
            latestVulnerabilities = newVulnerabilities;
2✔
730
            latest = ToolVersionChoice.ofLatest(toolEditionAndVersion, latestVulnerabilities);
4✔
731
            nearest = null;
3✔
732
          } else {
733
            nearestVulnerabilities = newVulnerabilities;
×
734
            nearest = ToolVersionChoice.ofNearest(toolEditionAndVersion, nearestVulnerabilities);
×
735
          }
736
        } else if (newVulnerabilities.isSaferOrEqual(nearestVulnerabilities)) {
5✔
737
          if (newVulnerabilities.isSafer(nearestVulnerabilities) || version.isGreater(resolvedVersion)) {
8!
738
            nearest = ToolVersionChoice.ofNearest(new ToolEditionAndVersion(toolEdition, version), newVulnerabilities);
8✔
739
          }
740
          nearestVulnerabilities = newVulnerabilities;
2✔
741
        }
742
      }
743
    }
1✔
744
    if ((latest == null) && (nearest == null)) {
2!
745
      LOG.warn("Could not find any other version resolving your CVEs.\n"
×
746
          + "Please keep attention to this tool and consider updating as soon as security fixes are available.");
747
      if (alreadyInstalled) {
×
748
        // we came here via "ide -f install ..." but no alternative is available
749
        return resolvedVersion;
×
750
      }
751
    }
752
    List<ToolVersionChoice> choices = new ArrayList<>();
4✔
753
    choices.add(currentChoice);
4✔
754
    boolean addSuggestions;
755
    if (this.context.isForceMode() && request.isDirect()) {
4!
756
      addSuggestions = true;
×
757
    } else {
758
      List<String> skipCveFixTools = IdeVariables.SKIP_CVE_FIX.get(this.context);
6✔
759
      addSuggestions = !skipCveFixTools.contains(this.tool);
8!
760
    }
761
    if (nearest != null) {
2!
762
      if (addSuggestions) {
2!
763
        choices.add(nearest);
4✔
764
      }
765
      nearest.logAndCheckIfEmpty();
3✔
766
    }
767
    if (latest != null) {
2!
768
      if (addSuggestions) {
2!
769
        choices.add(latest);
4✔
770
      }
771
      latest.logAndCheckIfEmpty();
3✔
772
    }
773
    ToolVersionChoice[] choicesArray = choices.toArray(ToolVersionChoice[]::new);
8✔
774
    LOG.warn("Please note that by selecting an unsafe version to install, you accept the risk to be attacked.");
3✔
775
    ToolVersionChoice answer = this.context.question(choicesArray, "Which version do you want to install?");
9✔
776
    VersionIdentifier version = answer.toolEditionAndVersion().getResolvedVersion();
4✔
777
    requested.setResolvedVersion(version);
3✔
778
    return version;
2✔
779
  }
780

781
  private static boolean acceptVersion(VersionIdentifier version, GenericVersionRange allowedVersions, boolean requireStableVersion) {
782
    if (allowedVersions.isPattern() && !allowedVersions.contains(version)) {
3!
783
      return false;
×
784
    } else if (requireStableVersion && !version.isStable()) {
5!
785
      return false;
×
786
    }
787
    return true;
2✔
788
  }
789

790
  /**
791
   * @return the {@link MacOsHelper} instance.
792
   */
793
  protected MacOsHelper getMacOsHelper() {
794

795
    if (this.macOsHelper == null) {
3✔
796
      this.macOsHelper = new MacOsHelper(this.context);
7✔
797
    }
798
    return this.macOsHelper;
3✔
799
  }
800

801
  /**
802
   * @return the currently installed {@link VersionIdentifier version} of this tool or {@code null} if not installed.
803
   */
804
  public abstract VersionIdentifier getInstalledVersion();
805

806
  /**
807
   * @return {@code true} if this tool is installed, {@code false} otherwise.
808
   */
809
  public boolean isInstalled() {
810

811
    return getInstalledVersion() != null;
7✔
812
  }
813

814
  /**
815
   * @return the installed edition of this tool or {@code null} if not installed.
816
   */
817
  public abstract String getInstalledEdition();
818

819
  /**
820
   * Uninstalls the {@link #getName() tool}.
821
   */
822
  public abstract void uninstall();
823

824
  /**
825
   * @return the {@link ToolRepository}.
826
   */
827
  public ToolRepository getToolRepository() {
828

829
    return this.context.getDefaultToolRepository();
4✔
830
  }
831

832
  /**
833
   * List the available editions of this tool.
834
   */
835
  public void listEditions() {
836

837
    List<String> editions = getToolRepository().getSortedEditions(getName());
6✔
838
    for (String edition : editions) {
10✔
839
      LOG.info(edition);
3✔
840
    }
1✔
841
  }
1✔
842

843
  /**
844
   * List the available versions of this tool.
845
   */
846
  public void listVersions() {
847

848
    List<VersionIdentifier> versions = getToolRepository().getSortedVersions(getName(), getConfiguredEdition(), this);
9✔
849
    for (VersionIdentifier vi : versions) {
10✔
850
      LOG.info(vi.toString());
4✔
851
    }
1✔
852
  }
1✔
853

854
  /**
855
   * @return the {@link com.devonfw.tools.ide.tool.repository.DefaultToolRepository#getSortedVersions(String, String, ToolCommandlet) sorted versions} of this
856
   *     tool.
857
   */
858
  public List<VersionIdentifier> getVersions() {
859
    return getToolRepository().getSortedVersions(getName(), getConfiguredEdition(), this);
9✔
860
  }
861

862
  /**
863
   * Sets the tool version in the environment variable configuration file.
864
   *
865
   * @param version the version (pattern) to set.
866
   */
867
  public void setVersion(String version) {
868

869
    if ((version == null) || version.isBlank()) {
×
870
      throw new IllegalStateException("Version has to be specified!");
×
871
    }
872
    VersionIdentifier configuredVersion = VersionIdentifier.of(version);
×
873
    if (!configuredVersion.isPattern() && !configuredVersion.isValid()) {
×
874
      LOG.warn("Version {} seems to be invalid", version);
×
875
    }
876
    setVersion(configuredVersion, true);
×
877
  }
×
878

879
  /**
880
   * Sets the tool version in the environment variable configuration file.
881
   *
882
   * @param version the version to set. May also be a {@link VersionIdentifier#isPattern() version pattern}.
883
   * @param hint - {@code true} to print the installation hint, {@code false} otherwise.
884
   */
885
  public void setVersion(VersionIdentifier version, boolean hint) {
886

887
    setVersion(version, hint, null);
5✔
888
  }
1✔
889

890
  /**
891
   * Sets the tool version in the environment variable configuration file.
892
   *
893
   * @param version the version to set. May also be a {@link VersionIdentifier#isPattern() version pattern}.
894
   * @param hint - {@code true} to print the installation hint, {@code false} otherwise.
895
   * @param destination - the destination for the property to be set
896
   */
897
  public void setVersion(VersionIdentifier version, boolean hint, EnvironmentVariablesFiles destination) {
898

899
    String edition = getConfiguredEdition();
3✔
900
    ToolRepository toolRepository = getToolRepository();
3✔
901

902
    EnvironmentVariables variables = this.context.getVariables();
4✔
903
    if (destination == null) {
2✔
904
      //use default location
905
      destination = EnvironmentVariablesFiles.SETTINGS;
2✔
906
    }
907
    EnvironmentVariables settingsVariables = variables.getByType(destination.toType());
5✔
908
    String variableName = EnvironmentVariables.getToolVersionVariable(this.tool);
4✔
909

910
    VersionIdentifier resolvedVersion = toolRepository.resolveVersion(this.tool, edition, version, this); // verify that the version actually exists
8✔
911
    settingsVariables.set(variableName, version.toString(), false);
7✔
912
    settingsVariables.save();
2✔
913
    EnvironmentVariables declaringVariables = variables.findVariable(variableName);
4✔
914
    if ((declaringVariables != null) && (declaringVariables != settingsVariables)) {
5!
915
      LOG.warn("The variable {} is overridden in {}. Please remove the overridden declaration in order to make the change affect.", variableName,
5✔
916
          declaringVariables.getSource());
1✔
917
    }
918
    LOG.info("Version of tool {} has been set to {} ({}={})", this.tool, version, variableName, version);
22✔
919
    if (hint && !resolvedVersion.equals(getInstalledVersion())) {
7✔
920
      IdeLogLevel.INTERACTION.log(LOG, "To install that version call the following command:\nide install {}", this.tool);
11✔
921
    }
922
  }
1✔
923

924
  /**
925
   * Sets the tool edition in the environment variable configuration file.
926
   *
927
   * @param edition the edition to set.
928
   */
929
  public void setEdition(String edition) {
930

931
    setEdition(edition, true);
4✔
932
  }
1✔
933

934
  /**
935
   * Sets the tool edition in the environment variable configuration file.
936
   *
937
   * @param edition the edition to set
938
   * @param hint - {@code true} to print the installation hint, {@code false} otherwise.
939
   */
940
  public void setEdition(String edition, boolean hint) {
941

942
    setEdition(edition, hint, null);
5✔
943
  }
1✔
944

945
  /**
946
   * Sets the tool edition in the environment variable configuration file.
947
   *
948
   * @param edition the edition to set
949
   * @param hint - {@code true} to print the installation hint, {@code false} otherwise.
950
   * @param destination - the destination for the property to be set
951
   */
952
  public void setEdition(String edition, boolean hint, EnvironmentVariablesFiles destination) {
953

954
    if ((edition == null) || edition.isBlank()) {
5!
955
      throw new IllegalStateException("Edition has to be specified!");
×
956
    }
957

958
    if (destination == null) {
2✔
959
      //use default location
960
      destination = EnvironmentVariablesFiles.SETTINGS;
2✔
961
    }
962

963
    if (!getToolRepository().getSortedEditions(this.tool).contains(edition)) {
8✔
964
      LOG.warn("Edition {} seems to be invalid", edition);
4✔
965
    }
966
    EnvironmentVariables variables = this.context.getVariables();
4✔
967
    EnvironmentVariables settingsVariables = variables.getByType(destination.toType());
5✔
968
    String name = EnvironmentVariables.getToolEditionVariable(this.tool);
4✔
969
    settingsVariables.set(name, edition, false);
6✔
970
    settingsVariables.save();
2✔
971

972
    LOG.info("{}={} has been set in {}", name, edition, settingsVariables.getSource());
18✔
973
    EnvironmentVariables declaringVariables = variables.findVariable(name);
4✔
974
    if ((declaringVariables != null) && (declaringVariables != settingsVariables)) {
5!
975
      LOG.warn("The variable {} is overridden in {}. Please remove the overridden declaration in order to make the change affect.", name,
5✔
976
          declaringVariables.getSource());
1✔
977
    }
978
    if (hint) {
2!
979
      LOG.info("To install that edition call the following command:");
3✔
980
      LOG.info("ide install {}", this.tool);
5✔
981
    }
982
  }
1✔
983

984
  /**
985
   * Runs the tool's help command to provide the user with usage information.
986
   */
987
  @Override
988
  public void printHelp(NlsBundle bundle) {
989

990
    super.printHelp(bundle);
3✔
991
    String toolHelpArgs = getToolHelpArguments();
3✔
992
    if (toolHelpArgs != null && getInstalledVersion() != null) {
5!
993
      ProcessContext pc = this.context.newProcess().errorHandling(ProcessErrorHandling.LOG_WARNING)
6✔
994
          .executable(Path.of(getBinaryName())).addArgs(toolHelpArgs);
13✔
995
      pc.run(ProcessMode.DEFAULT);
4✔
996
    }
997
  }
1✔
998

999
  /**
1000
   * @return the tool's specific help command. Usually help, --help or -h. Return null if not applicable.
1001
   */
1002
  public String getToolHelpArguments() {
1003

1004
    return null;
×
1005
  }
1006

1007
  /**
1008
   * Creates a start script for the tool using the tool name.
1009
   *
1010
   * @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
1011
   *     instead.
1012
   * @param binary name of the binary to execute from the start script.
1013
   */
1014
  protected void createStartScript(Path targetDir, String binary) {
1015

1016
    createStartScript(targetDir, binary, false);
×
1017
  }
×
1018

1019
  /**
1020
   * Creates a start script for the tool using the tool name.
1021
   *
1022
   * @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
1023
   *     instead.
1024
   * @param binary name of the binary to execute from the start script.
1025
   * @param background {@code true} to run the {@code binary} in background, {@code false} otherwise (foreground).
1026
   */
1027
  protected void createStartScript(Path targetDir, String binary, boolean background) {
1028

1029
    Path binFolder = targetDir.resolve("bin");
×
1030
    if (!Files.exists(binFolder)) {
×
1031
      if (this.context.getSystemInfo().isMac()) {
×
1032
        MacOsHelper macOsHelper = getMacOsHelper();
×
1033
        Path appDir = macOsHelper.findAppDir(targetDir);
×
1034
        binFolder = macOsHelper.findLinkDir(appDir, binary);
×
1035
      } else {
×
1036
        binFolder = targetDir;
×
1037
      }
1038
      assert (Files.exists(binFolder));
×
1039
    }
1040
    Path bashFile = binFolder.resolve(getName());
×
1041
    String bashFileContentStart = "#!/usr/bin/env bash\n\"$(dirname \"$0\")/";
×
1042
    String bashFileContentEnd = "\" $@";
×
1043
    if (background) {
×
1044
      bashFileContentEnd += " &";
×
1045
    }
1046
    try {
1047
      Files.writeString(bashFile, bashFileContentStart + binary + bashFileContentEnd);
×
1048
    } catch (IOException e) {
×
1049
      throw new RuntimeException(e);
×
1050
    }
×
1051
    assert (Files.exists(bashFile));
×
1052
    context.getFileAccess().makeExecutable(bashFile);
×
1053
  }
×
1054

1055
  @Override
1056
  public void reset() {
1057
    super.reset();
2✔
1058
    this.executionDirectory = null;
3✔
1059
  }
1✔
1060

1061
  /**
1062
   * @param command the binary that will be searched in the PATH e.g. docker
1063
   * @return true if the command is available to use
1064
   */
1065
  protected boolean isCommandAvailable(String command) {
1066
    return this.context.getPath().hasBinaryOnPath(command);
×
1067
  }
1068

1069
  /**
1070
   * @param output the raw output string from executed command e.g. 'docker version'
1071
   * @param pattern Regular Expression pattern that filters out the unnecessary texts.
1072
   * @return version that has been processed.
1073
   */
1074
  protected VersionIdentifier resolveVersionWithPattern(String output, Pattern pattern) {
1075
    Matcher matcher = pattern.matcher(output);
×
1076

1077
    if (matcher.find()) {
×
1078
      return VersionIdentifier.of(matcher.group(1));
×
1079
    } else {
1080
      return null;
×
1081
    }
1082
  }
1083

1084
  /**
1085
   * @deprecated directly log success message and then report success on step if not null.
1086
   */
1087
  @Deprecated
1088
  protected void success(Step step, String message, Object... args) {
1089

1090
    if (step == null) {
×
1091
      IdeLogLevel.SUCCESS.log(LOG, message, args);
×
1092
    } else {
1093
      step.success(message, args);
×
1094
    }
1095
  }
×
1096

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