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

devonfw / IDEasy / 17832256085

18 Sep 2025 02:38PM UTC coverage: 68.464% (-0.08%) from 68.539%
17832256085

Pull #1499

github

web-flow
Merge 0ad75342a into 147222dbe
Pull Request #1499: #907: add NpmRepository and further node/npm support as preparation for yarn and corepack

3430 of 5487 branches covered (62.51%)

Branch coverage included in aggregate %.

8977 of 12635 relevant lines covered (71.05%)

3.12 hits per line

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

65.71
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.Set;
8

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

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

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

37
  private final Set<Tag> tags;
38

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

42
  private Path executionDirectory;
43

44
  private MacOsHelper macOsHelper;
45

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

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

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

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

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

77
    return this.tool;
3✔
78
  }
79

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

85
    return this.tool;
3✔
86
  }
87

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

91
    return this.tags;
3✔
92
  }
93

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

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

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

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

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

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

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

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

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

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

148
  @Override
149
  public void run() {
150

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

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

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

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

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

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

190
    if (toolVersion != null) {
2!
191
      throw new UnsupportedOperationException("Not implemented yet");
×
192
    }
193
    ProcessContext pc = this.context.newProcess().errorHandling(errorHandling);
6✔
194
    install(true, pc, null);
6✔
195
    return runTool(processMode, errorHandling, pc, args);
7✔
196
  }
197

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

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

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

222
    pc.executable(Path.of(getBinaryName()));
8✔
223
  }
1✔
224

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

233
    pc.addArgs(args);
4✔
234
  }
1✔
235

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

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

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

255
    return install(true);
4✔
256
  }
257

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

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

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

285
    return true;
2✔
286
  }
287

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

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

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

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

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

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

319
    return this.context.getDefaultToolRepository();
4✔
320
  }
321

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

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

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

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

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

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

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

369
    setVersion(version, hint, null);
5✔
370
  }
1✔
371

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

381
    String edition = getConfiguredEdition();
3✔
382
    ToolRepository toolRepository = getToolRepository();
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
    toolRepository.resolveVersion(this.tool, edition, version, this); // verify that the version actually exists
8✔
393
    settingsVariables.set(name, version.toString(), false);
7✔
394
    settingsVariables.save();
2✔
395
    EnvironmentVariables declaringVariables = variables.findVariable(name);
4✔
396
    if ((declaringVariables != null) && (declaringVariables != settingsVariables)) {
5!
397
      this.context.warning("The variable {} is overridden in {}. Please remove the overridden declaration in order to make the change affect.", name,
13✔
398
          declaringVariables.getSource());
2✔
399
    }
400
    if (hint) {
2✔
401
      this.context.info("To install that version call the following command:");
4✔
402
      this.context.info("ide install {}", this.tool);
11✔
403
    }
404
  }
1✔
405

406
  /**
407
   * Sets the tool edition in the environment variable configuration file.
408
   *
409
   * @param edition the edition to set.
410
   */
411
  public void setEdition(String edition) {
412

413
    setEdition(edition, true);
4✔
414
  }
1✔
415

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

424
    setEdition(edition, hint, null);
5✔
425
  }
1✔
426

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

436
    if ((edition == null) || edition.isBlank()) {
5!
437
      throw new IllegalStateException("Edition has to be specified!");
×
438
    }
439

440
    if (destination == null) {
2✔
441
      //use default location
442
      destination = EnvironmentVariablesFiles.SETTINGS;
2✔
443
    }
444

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

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

466
  /**
467
   * Runs the tool's help command to provide the user with usage information.
468
   */
469
  @Override
470
  public void printHelp(NlsBundle bundle) {
471

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

481
  /**
482
   * @return the tool's specific help command. Usually help, --help or -h. Return null if not applicable.
483
   */
484
  public String getToolHelpArguments() {
485

486
    return null;
×
487
  }
488

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

498
    createStartScript(targetDir, binary, false);
×
499
  }
×
500

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

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

537
  @Override
538
  public void reset() {
539
    super.reset();
2✔
540
    this.executionDirectory = null;
3✔
541
  }
1✔
542

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

549
    if (step == null) {
2!
550
      return this.context.success();
4✔
551
    } else {
552
      return step.asSuccess();
×
553
    }
554
  }
555

556

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

563
    if (step == null) {
×
564
      return this.context.error();
×
565
    } else {
566
      return step.asError();
×
567
    }
568
  }
569
}
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