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

devonfw / IDEasy / 28752358198

05 Jul 2026 07:32PM UTC coverage: 71.835% (+0.003%) from 71.832%
28752358198

Pull #2113

github

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

4761 of 7312 branches covered (65.11%)

Branch coverage included in aggregate %.

12205 of 16306 relevant lines covered (74.85%)

3.17 hits per line

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

73.88
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
        LOG.warn(
4✔
279
            "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.",
280
            request.getRequested());
1✔
281
        return new ProcessResultImpl(this.tool, this.tool, 0, List.of());
10✔
282
      }
283
    }
284
    return runTool(request.getProcessContext(), processMode, args);
7✔
285
  }
286

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

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

303
  /**
304
   * @param pc the {@link ProcessContext}.
305
   * @param processMode the {@link ProcessMode}.
306
   */
307
  protected void configureToolBinary(ProcessContext pc, ProcessMode processMode) {
308

309
    pc.executable(Path.of(getBinaryName()));
8✔
310
  }
1✔
311

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

319
    pc.addArgs(args);
4✔
320
  }
1✔
321

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

329
    return install(true);
4✔
330
  }
331

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

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

350
    completeRequest(request);
3✔
351
    if (request.isInstallLoop()) {
3!
352
      return toolAlreadyInstalled(request);
×
353
    }
354
    return doInstall(request);
4✔
355
  }
356

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

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

370
    completeRequestInstalled(request);
3✔
371
    completeRequestRequested(request); // depends on completeRequestInstalled
3✔
372
    completeRequestProcessContext(request);
3✔
373
    completeRequestToolPath(request);
3✔
374
  }
1✔
375

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

383
  private void completeRequestInstalled(ToolInstallRequest request) {
384

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

415
  private void completeRequestRequested(ToolInstallRequest request) {
416

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

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

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

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

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

468
    // default no-op
469
    return requested;
2✔
470
  }
471

472

473
  private void completeRequestToolPath(ToolInstallRequest request) {
474

475
    Path toolPath = request.getToolPath();
3✔
476
    if (toolPath == null) {
2✔
477
      toolPath = getToolPath();
3✔
478
      request.setToolPath(toolPath);
3✔
479
    }
480
  }
1✔
481

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

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

497
    if (!request.isAlreadyInstalled()) {
3✔
498
      postInstallOnNewInstallation(request);
3✔
499
    }
500
  }
1✔
501

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

509
    // nothing to do by default
510
  }
1✔
511

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

519
  /**
520
   * @param request the {@link ToolInstallRequest}.
521
   * @return the existing {@link ToolInstallation}.
522
   */
523
  protected ToolInstallation createExistingToolInstallation(ToolInstallRequest request) {
524

525
    ToolEditionAndVersion installed = request.getInstalled();
3✔
526

527
    String edition = this.tool;
3✔
528
    VersionIdentifier resolvedVersion = VersionIdentifier.LATEST;
2✔
529

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

539
    return createExistingToolInstallation(edition, resolvedVersion, request.getProcessContext(),
8✔
540
        request.isAdditionalInstallation());
1✔
541
  }
542

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

554
    Path installationPath = getInstallationPath(edition, installedVersion);
5✔
555
    return createToolInstallation(installationPath, installedVersion, false, environmentContext, extraInstallation);
8✔
556
  }
557

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

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

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

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

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

609
    logToolAlreadyInstalled(request);
3✔
610
    cveCheck(request);
4✔
611
    postInstall(request);
3✔
612
    return createExistingToolInstallation(request);
4✔
613
  }
614

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

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

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

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

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

667
    return true;
2✔
668
  }
669

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

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

715
      if (Objects.equals(version, resolvedVersion)) {
4✔
716
        continue; // Skip the entire iteration for resolvedVersion
1✔
717
      }
718

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

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

786
  /**
787
   * @return the {@link MacOsHelper} instance.
788
   */
789
  protected MacOsHelper getMacOsHelper() {
790

791
    if (this.macOsHelper == null) {
3✔
792
      this.macOsHelper = new MacOsHelper(this.context);
7✔
793
    }
794
    return this.macOsHelper;
3✔
795
  }
796

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

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

807
    return getInstalledVersion() != null;
7✔
808
  }
809

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

815
  /**
816
   * Uninstalls the {@link #getName() tool}.
817
   */
818
  public abstract void uninstall();
819

820
  /**
821
   * @return the {@link ToolRepository}.
822
   */
823
  public ToolRepository getToolRepository() {
824

825
    return this.context.getDefaultToolRepository();
4✔
826
  }
827

828
  /**
829
   * List the available editions of this tool.
830
   */
831
  public void listEditions() {
832

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

839
  /**
840
   * List the available versions of this tool.
841
   */
842
  public void listVersions() {
843

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

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

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

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

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

883
    setVersion(version, hint, null);
5✔
884
  }
1✔
885

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

895
    String edition = getConfiguredEdition();
3✔
896
    ToolRepository toolRepository = getToolRepository();
3✔
897

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

906
    toolRepository.resolveVersion(this.tool, edition, version, this); // verify that the version actually exists
8✔
907
    settingsVariables.set(name, version.toString(), false);
7✔
908
    settingsVariables.save();
2✔
909
    EnvironmentVariables declaringVariables = variables.findVariable(name);
4✔
910
    if ((declaringVariables != null) && (declaringVariables != settingsVariables)) {
5!
911
      LOG.warn("The variable {} is overridden in {}. Please remove the overridden declaration in order to make the change affect.", name,
5✔
912
          declaringVariables.getSource());
1✔
913
    }
914
    if (hint) {
2✔
915
      LOG.info("To install that version call the following command:");
3✔
916
      LOG.info("ide install {}", this.tool);
5✔
917
    }
918
  }
1✔
919

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

927
    setEdition(edition, true);
4✔
928
  }
1✔
929

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

938
    setEdition(edition, hint, null);
5✔
939
  }
1✔
940

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

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

954
    if (destination == null) {
2✔
955
      //use default location
956
      destination = EnvironmentVariablesFiles.SETTINGS;
2✔
957
    }
958

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

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

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

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

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

1000
    return null;
×
1001
  }
1002

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

1012
    createStartScript(targetDir, binary, false);
×
1013
  }
×
1014

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

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

1051
  @Override
1052
  public void reset() {
1053
    super.reset();
2✔
1054
    this.executionDirectory = null;
3✔
1055
  }
1✔
1056

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

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

1073
    if (matcher.find()) {
×
1074
      return VersionIdentifier.of(matcher.group(1));
×
1075
    } else {
1076
      return null;
×
1077
    }
1078
  }
1079

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

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

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