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

devonfw / IDEasy / 28826464634

06 Jul 2026 10:05PM UTC coverage: 71.809% (+0.05%) from 71.763%
28826464634

Pull #2113

github

web-flow
Merge e0ff246ee into ce85d84c3
Pull Request #2113: #1659: abort runTool with warning when global tool installer runs in background

4839 of 7440 branches covered (65.04%)

Branch coverage included in aggregate %.

12398 of 16564 relevant lines covered (74.85%)

3.17 hits per line

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

74.08
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 reboot and rerun your 'ide' command in a new terminal session after the installation has completed.",
355
          request.getRequested());
1✔
356
    }
357
    return installation;
2✔
358
  }
359

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

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

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

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

386
  private void completeRequestInstalled(ToolInstallRequest request) {
387

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

418
  private void completeRequestRequested(ToolInstallRequest request) {
419

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

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

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

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

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

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

475

476
  private void completeRequestToolPath(ToolInstallRequest request) {
477

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

485
  /**
486
   * @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
487
   *     determined by the installer.
488
   */
489
  public Path getToolPath() {
490
    return null;
×
491
  }
492

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

670
    return true;
2✔
671
  }
672

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1003
    return null;
×
1004
  }
1005

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

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

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

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

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

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

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

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

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

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

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