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

devonfw / IDEasy / 17731367199

15 Sep 2025 11:23AM UTC coverage: 68.544% (-0.08%) from 68.627%
17731367199

Pull #1463

github

web-flow
Merge 36474e12e into 2efad3d2e
Pull Request #1463: #1454: Add ng commandlet

3413 of 5447 branches covered (62.66%)

Branch coverage included in aggregate %.

8901 of 12518 relevant lines covered (71.11%)

3.12 hits per line

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

66.2
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.List;
7
import java.util.Objects;
8
import java.util.Set;
9

10
import com.devonfw.tools.ide.commandlet.Commandlet;
11
import com.devonfw.tools.ide.common.Tag;
12
import com.devonfw.tools.ide.common.Tags;
13
import com.devonfw.tools.ide.context.IdeContext;
14
import com.devonfw.tools.ide.environment.EnvironmentVariables;
15
import com.devonfw.tools.ide.environment.EnvironmentVariablesFiles;
16
import com.devonfw.tools.ide.log.IdeSubLogger;
17
import com.devonfw.tools.ide.nls.NlsBundle;
18
import com.devonfw.tools.ide.os.MacOsHelper;
19
import com.devonfw.tools.ide.process.EnvironmentContext;
20
import com.devonfw.tools.ide.process.ProcessContext;
21
import com.devonfw.tools.ide.process.ProcessErrorHandling;
22
import com.devonfw.tools.ide.process.ProcessMode;
23
import com.devonfw.tools.ide.process.ProcessResult;
24
import com.devonfw.tools.ide.property.StringProperty;
25
import com.devonfw.tools.ide.step.Step;
26
import com.devonfw.tools.ide.tool.repository.ToolRepository;
27
import com.devonfw.tools.ide.version.GenericVersionRange;
28
import com.devonfw.tools.ide.version.VersionIdentifier;
29

30
/**
31
 * {@link Commandlet} for a tool integrated into the IDE.
32
 */
33
public abstract class ToolCommandlet extends Commandlet implements Tags {
1✔
34

35
  /** @see #getName() */
36
  protected final String tool;
37

38
  private final Set<Tag> tags;
39

40
  /** The commandline arguments to pass to the tool. */
41
  public final StringProperty arguments;
42

43
  private Path executionDirectory;
44

45
  private MacOsHelper macOsHelper;
46

47
  /**
48
   * The constructor.
49
   *
50
   * @param context the {@link IdeContext}.
51
   * @param tool the {@link #getName() tool name}.
52
   * @param tags the {@link #getTags() tags} classifying the tool. Should be created via {@link Set#of(Object) Set.of} method.
53
   */
54
  public ToolCommandlet(IdeContext context, String tool, Set<Tag> tags) {
55

56
    super(context);
3✔
57
    this.tool = tool;
3✔
58
    this.tags = tags;
3✔
59
    addKeyword(tool);
3✔
60
    this.arguments = new StringProperty("", false, true, "args");
9✔
61
    initProperties();
2✔
62
  }
1✔
63

64
  /**
65
   * Add initial Properties to the tool
66
   */
67
  protected void initProperties() {
68

69
    add(this.arguments);
5✔
70
  }
1✔
71

72
  /**
73
   * @return the name of the tool (e.g. "java", "mvn", "npm", "node").
74
   */
75
  @Override
76
  public final String getName() {
77

78
    return this.tool;
3✔
79
  }
80

81
  /**
82
   * @return the name of the binary executable for this tool.
83
   */
84
  protected String getBinaryName() {
85

86
    return this.tool;
3✔
87
  }
88

89
  @Override
90
  public final Set<Tag> getTags() {
91

92
    return this.tags;
3✔
93
  }
94

95
  /**
96
   * @return the execution directory where the tool will be executed. Will be {@code null} by default leading to execution in the users current working
97
   *     directory where IDEasy was called.
98
   * @see #setExecutionDirectory(Path)
99
   */
100
  public Path getExecutionDirectory() {
101
    return this.executionDirectory;
×
102
  }
103

104
  /**
105
   * @param executionDirectory the new value of {@link #getExecutionDirectory()}.
106
   */
107
  public void setExecutionDirectory(Path executionDirectory) {
108
    this.executionDirectory = executionDirectory;
×
109
  }
×
110

111
  /**
112
   * @return the {@link EnvironmentVariables#getToolVersion(String) tool version}.
113
   */
114
  public VersionIdentifier getConfiguredVersion() {
115

116
    return this.context.getVariables().getToolVersion(getName());
7✔
117
  }
118

119
  /**
120
   * @return the {@link EnvironmentVariables#getToolEdition(String) tool edition}.
121
   */
122
  public String getConfiguredEdition() {
123

124
    return this.context.getVariables().getToolEdition(getName());
7✔
125
  }
126

127
  /**
128
   * @return the {@link #getName() tool} with its {@link #getConfiguredEdition() edition}. The edition will be omitted if same as tool.
129
   * @see #getToolWithEdition(String, String)
130
   */
131
  protected final String getToolWithEdition() {
132

133
    return getToolWithEdition(getName(), getConfiguredEdition());
6✔
134
  }
135

136
  /**
137
   * @param tool the tool name.
138
   * @param edition the edition.
139
   * @return the {@link #getName() tool} with its {@link #getConfiguredEdition() edition}. The edition will be omitted if same as tool.
140
   */
141
  protected static String getToolWithEdition(String tool, String edition) {
142

143
    if (tool.equals(edition)) {
4✔
144
      return tool;
2✔
145
    }
146
    return tool + "/" + edition;
4✔
147
  }
148

149
  @Override
150
  public void run() {
151

152
    runTool(this.arguments.asArray());
6✔
153
  }
1✔
154

155
  /**
156
   * @param args the command-line arguments to run the tool.
157
   * @return the {@link ProcessResult result}.
158
   * @see ToolCommandlet#runTool(ProcessMode, GenericVersionRange, String...)
159
   */
160
  public ProcessResult runTool(String... args) {
161

162
    return runTool(ProcessMode.DEFAULT, null, args);
6✔
163
  }
164

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

176
    return runTool(processMode, toolVersion, ProcessErrorHandling.THROW_CLI, args);
7✔
177
  }
178

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

191
    ProcessContext pc = this.context.newProcess().errorHandling(errorHandling);
6✔
192
    install(true, pc, null);
6✔
193
    return runTool(processMode, errorHandling, pc, args);
7✔
194
  }
195

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

205
    if (this.executionDirectory != null) {
3!
206
      pc.directory(this.executionDirectory);
×
207
    }
208
    configureToolBinary(pc, processMode, errorHandling);
5✔
209
    configureToolArgs(pc, processMode, errorHandling, args);
6✔
210
    return pc.run(processMode);
4✔
211
  }
212

213
  /**
214
   * @param pc the {@link ProcessContext}.
215
   * @param processMode the {@link ProcessMode}.
216
   * @param errorHandling the {@link ProcessErrorHandling}.
217
   */
218
  protected void configureToolBinary(ProcessContext pc, ProcessMode processMode, ProcessErrorHandling errorHandling) {
219

220
    pc.executable(Path.of(getBinaryName()));
8✔
221
  }
1✔
222

223
  /**
224
   * @param pc the {@link ProcessContext}.
225
   * @param processMode the {@link ProcessMode}.
226
   * @param errorHandling the {@link ProcessErrorHandling}.
227
   * @param args the command-line arguments to {@link ProcessContext#addArgs(Object...) add}.
228
   */
229
  protected void configureToolArgs(ProcessContext pc, ProcessMode processMode, ProcessErrorHandling errorHandling, String... args) {
230

231
    pc.addArgs(args);
4✔
232
  }
1✔
233

234
  /**
235
   * Creates a new {@link ProcessContext} from the given executable with the provided arguments attached.
236
   *
237
   * @param binaryPath path to the binary executable for this process
238
   * @param args the command-line arguments for this process
239
   * @return {@link ProcessContext}
240
   */
241
  protected ProcessContext createProcessContext(Path binaryPath, String... args) {
242

243
    return this.context.newProcess().errorHandling(ProcessErrorHandling.THROW_ERR).executable(binaryPath).addArgs(args);
×
244
  }
245

246
  /**
247
   * Installs or updates the managed {@link #getName() tool}.
248
   *
249
   * @return {@code true} if the tool was newly installed, {@code false} if the tool was already installed before and nothing has changed.
250
   */
251
  public boolean install() {
252

253
    return install(true);
4✔
254
  }
255

256
  /**
257
   * Performs the installation of the {@link #getName() tool} managed by this {@link com.devonfw.tools.ide.commandlet.Commandlet}.
258
   *
259
   * @param silent - {@code true} if called recursively to suppress verbose logging, {@code false} otherwise.
260
   * @return {@code true} if the tool was newly installed, {@code false} if the tool was already installed before and nothing has changed.
261
   */
262
  public boolean install(boolean silent) {
263
    ProcessContext pc = this.context.newProcess().errorHandling(ProcessErrorHandling.THROW_CLI);
6✔
264
    return install(silent, pc, null);
6✔
265
  }
266

267
  /**
268
   * Installs or updates the managed {@link #getName() tool}.
269
   *
270
   * @param silent - {@code true} if called recursively to suppress verbose logging, {@code false} otherwise.
271
   * @param processContext the {@link ProcessContext} used to
272
   *     {@link LocalToolCommandlet#setEnvironment(EnvironmentContext, ToolInstallation, boolean) configure environment variables}.
273
   * @param step the {@link Step} to track the installation. May be {@code null} to fail with {@link Exception} on error.
274
   * @return {@code true} if the tool was newly installed, {@code false} if the tool was already installed before and nothing has changed.
275
   */
276
  public abstract boolean install(boolean silent, ProcessContext processContext, Step step);
277

278
  /**
279
   * @return {@code true} to extract (unpack) the downloaded binary file, {@code false} otherwise.
280
   */
281
  protected boolean isExtract() {
282

283
    return true;
2✔
284
  }
285

286
  /**
287
   * @return the {@link MacOsHelper} instance.
288
   */
289
  protected MacOsHelper getMacOsHelper() {
290

291
    if (this.macOsHelper == null) {
3✔
292
      this.macOsHelper = new MacOsHelper(this.context);
7✔
293
    }
294
    return this.macOsHelper;
3✔
295
  }
296

297
  /**
298
   * @return the currently installed {@link VersionIdentifier version} of this tool or {@code null} if not installed.
299
   */
300
  public abstract VersionIdentifier getInstalledVersion();
301

302
  /**
303
   * @return the installed edition of this tool or {@code null} if not installed.
304
   */
305
  public abstract String getInstalledEdition();
306

307
  /**
308
   * Uninstalls the {@link #getName() tool}.
309
   */
310
  public abstract void uninstall();
311

312
  /**
313
   * @return the {@link ToolRepository}.
314
   */
315
  public ToolRepository getToolRepository() {
316

317
    return this.context.getDefaultToolRepository();
4✔
318
  }
319

320
  /**
321
   * List the available editions of this tool.
322
   */
323
  public void listEditions() {
324

325
    List<String> editions = getToolRepository().getSortedEditions(getName());
6✔
326
    for (String edition : editions) {
10✔
327
      this.context.info(edition);
4✔
328
    }
1✔
329
  }
1✔
330

331
  /**
332
   * List the available versions of this tool.
333
   */
334
  public void listVersions() {
335

336
    List<VersionIdentifier> versions = getToolRepository().getSortedVersions(getName(), getConfiguredEdition(), this);
9✔
337
    for (VersionIdentifier vi : versions) {
10✔
338
      this.context.info(vi.toString());
5✔
339
    }
1✔
340
  }
1✔
341

342
  /**
343
   * Sets the tool version in the environment variable configuration file.
344
   *
345
   * @param version the version (pattern) to set.
346
   */
347
  public void setVersion(String version) {
348

349
    if ((version == null) || version.isBlank()) {
×
350
      throw new IllegalStateException("Version has to be specified!");
×
351
    }
352
    VersionIdentifier configuredVersion = VersionIdentifier.of(version);
×
353
    if (!configuredVersion.isPattern() && !configuredVersion.isValid()) {
×
354
      this.context.warning("Version {} seems to be invalid", version);
×
355
    }
356
    setVersion(configuredVersion, true);
×
357
  }
×
358

359
  /**
360
   * Sets the tool version in the environment variable configuration file.
361
   *
362
   * @param version the version to set. May also be a {@link VersionIdentifier#isPattern() version pattern}.
363
   * @param hint - {@code true} to print the installation hint, {@code false} otherwise.
364
   */
365
  public void setVersion(VersionIdentifier version, boolean hint) {
366

367
    setVersion(version, hint, null);
5✔
368
  }
1✔
369

370
  /**
371
   * Sets the tool version in the environment variable configuration file.
372
   *
373
   * @param version the version to set. May also be a {@link VersionIdentifier#isPattern() version pattern}.
374
   * @param hint - {@code true} to print the installation hint, {@code false} otherwise.
375
   * @param destination - the destination for the property to be set
376
   */
377
  public void setVersion(VersionIdentifier version, boolean hint, EnvironmentVariablesFiles destination) {
378

379
    String edition = getConfiguredEdition();
3✔
380
    ToolRepository toolRepository = getToolRepository();
3✔
381
    VersionIdentifier versionIdentifier = toolRepository.resolveVersion(this.tool, edition, version, this);
8✔
382
    Objects.requireNonNull(versionIdentifier);
3✔
383

384
    EnvironmentVariables variables = this.context.getVariables();
4✔
385
    if (destination == null) {
2✔
386
      //use default location
387
      destination = EnvironmentVariablesFiles.SETTINGS;
2✔
388
    }
389
    EnvironmentVariables settingsVariables = variables.getByType(destination.toType());
5✔
390
    String name = EnvironmentVariables.getToolVersionVariable(this.tool);
4✔
391

392
    VersionIdentifier resolvedVersion = toolRepository.resolveVersion(this.tool, edition, version, this);
8✔
393
    if (version.isPattern()) {
3!
394
      this.context.debug("Resolved version {} to {} for tool {}/{}", version, resolvedVersion, this.tool, edition);
×
395
    }
396
    settingsVariables.set(name, resolvedVersion.toString(), false);
7✔
397
    settingsVariables.save();
2✔
398
    this.context.info("{}={} has been set in {}", name, version, settingsVariables.getSource());
19✔
399
    EnvironmentVariables declaringVariables = variables.findVariable(name);
4✔
400
    if ((declaringVariables != null) && (declaringVariables != settingsVariables)) {
5!
401
      this.context.warning("The variable {} is overridden in {}. Please remove the overridden declaration in order to make the change affect.", name,
13✔
402
          declaringVariables.getSource());
2✔
403
    }
404
    if (hint) {
2✔
405
      this.context.info("To install that version call the following command:");
4✔
406
      this.context.info("ide install {}", this.tool);
11✔
407
    }
408
  }
1✔
409

410
  /**
411
   * Sets the tool edition in the environment variable configuration file.
412
   *
413
   * @param edition the edition to set.
414
   */
415
  public void setEdition(String edition) {
416

417
    setEdition(edition, true);
4✔
418
  }
1✔
419

420
  /**
421
   * Sets the tool edition in the environment variable configuration file.
422
   *
423
   * @param edition the edition to set
424
   * @param hint - {@code true} to print the installation hint, {@code false} otherwise.
425
   */
426
  public void setEdition(String edition, boolean hint) {
427

428
    setEdition(edition, hint, null);
5✔
429
  }
1✔
430

431
  /**
432
   * Sets the tool edition in the environment variable configuration file.
433
   *
434
   * @param edition the edition to set
435
   * @param hint - {@code true} to print the installation hint, {@code false} otherwise.
436
   * @param destination - the destination for the property to be set
437
   */
438
  public void setEdition(String edition, boolean hint, EnvironmentVariablesFiles destination) {
439

440
    if ((edition == null) || edition.isBlank()) {
5!
441
      throw new IllegalStateException("Edition has to be specified!");
×
442
    }
443

444
    if (destination == null) {
2✔
445
      //use default location
446
      destination = EnvironmentVariablesFiles.SETTINGS;
2✔
447
    }
448

449
    if (!getToolRepository().getSortedEditions(this.tool).contains(edition)) {
8✔
450
      this.context.warning("Edition {} seems to be invalid", edition);
10✔
451
    }
452
    EnvironmentVariables variables = this.context.getVariables();
4✔
453
    EnvironmentVariables settingsVariables = variables.getByType(destination.toType());
5✔
454
    String name = EnvironmentVariables.getToolEditionVariable(this.tool);
4✔
455
    settingsVariables.set(name, edition, false);
6✔
456
    settingsVariables.save();
2✔
457

458
    this.context.info("{}={} has been set in {}", name, edition, settingsVariables.getSource());
19✔
459
    EnvironmentVariables declaringVariables = variables.findVariable(name);
4✔
460
    if ((declaringVariables != null) && (declaringVariables != settingsVariables)) {
5!
461
      this.context.warning("The variable {} is overridden in {}. Please remove the overridden declaration in order to make the change affect.", name,
13✔
462
          declaringVariables.getSource());
2✔
463
    }
464
    if (hint) {
2!
465
      this.context.info("To install that edition call the following command:");
4✔
466
      this.context.info("ide install {}", this.tool);
11✔
467
    }
468
  }
1✔
469

470
  /**
471
   * Runs the tool's help command to provide the user with usage information.
472
   */
473
  @Override
474
  public void printHelp(NlsBundle bundle) {
475

476
    super.printHelp(bundle);
3✔
477
    String toolHelpArgs = getToolHelpArguments();
3✔
478
    if (toolHelpArgs != null && getInstalledVersion() != null) {
5!
479
      ProcessContext pc = this.context.newProcess().errorHandling(ProcessErrorHandling.LOG_WARNING)
6✔
480
          .executable(Path.of(getBinaryName())).addArgs(toolHelpArgs);
13✔
481
      pc.run(ProcessMode.DEFAULT);
4✔
482
    }
483
  }
1✔
484

485
  /**
486
   * @return the tool's specific help command. Usually help, --help or -h. Return null if not applicable.
487
   */
488
  public String getToolHelpArguments() {
489

490
    return null;
×
491
  }
492

493
  /**
494
   * Creates a start script for the tool using the tool name.
495
   *
496
   * @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
497
   *     instead.
498
   * @param binary name of the binary to execute from the start script.
499
   */
500
  protected void createStartScript(Path targetDir, String binary) {
501

502
    createStartScript(targetDir, binary, false);
×
503
  }
×
504

505
  /**
506
   * Creates a start script for the tool using the tool name.
507
   *
508
   * @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
509
   *     instead.
510
   * @param binary name of the binary to execute from the start script.
511
   * @param background {@code true} to run the {@code binary} in background, {@code false} otherwise (foreground).
512
   */
513
  protected void createStartScript(Path targetDir, String binary, boolean background) {
514

515
    Path binFolder = targetDir.resolve("bin");
×
516
    if (!Files.exists(binFolder)) {
×
517
      if (this.context.getSystemInfo().isMac()) {
×
518
        MacOsHelper macOsHelper = getMacOsHelper();
×
519
        Path appDir = macOsHelper.findAppDir(targetDir);
×
520
        binFolder = macOsHelper.findLinkDir(appDir, binary);
×
521
      } else {
×
522
        binFolder = targetDir;
×
523
      }
524
      assert (Files.exists(binFolder));
×
525
    }
526
    Path bashFile = binFolder.resolve(getName());
×
527
    String bashFileContentStart = "#!/usr/bin/env bash\n\"$(dirname \"$0\")/";
×
528
    String bashFileContentEnd = "\" $@";
×
529
    if (background) {
×
530
      bashFileContentEnd += " &";
×
531
    }
532
    try {
533
      Files.writeString(bashFile, bashFileContentStart + binary + bashFileContentEnd);
×
534
    } catch (IOException e) {
×
535
      throw new RuntimeException(e);
×
536
    }
×
537
    assert (Files.exists(bashFile));
×
538
    context.getFileAccess().makeExecutable(bashFile);
×
539
  }
×
540

541
  @Override
542
  public void reset() {
543
    super.reset();
2✔
544
    this.executionDirectory = null;
3✔
545
  }
1✔
546

547
  /**
548
   * @param step the {@link Step} to get {@link Step#asSuccess() success logger} from. May be {@code null}.
549
   * @return the {@link IdeSubLogger} from {@link Step#asSuccess()} or {@link IdeContext#success()} as fallback.
550
   */
551
  protected IdeSubLogger asSuccess(Step step) {
552

553
    if (step == null) {
2!
554
      return this.context.success();
4✔
555
    } else {
556
      return step.asSuccess();
×
557
    }
558
  }
559

560

561
  /**
562
   * @param step the {@link Step} to get {@link Step#asError() error logger} from. May be {@code null}.
563
   * @return the {@link IdeSubLogger} from {@link Step#asError()} or {@link IdeContext#error()} as fallback.
564
   */
565
  protected IdeSubLogger asError(Step step) {
566

567
    if (step == null) {
×
568
      return this.context.error();
×
569
    } else {
570
      return step.asError();
×
571
    }
572
  }
573
}
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