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

devonfw / IDEasy / 13656780447

04 Mar 2025 03:11PM UTC coverage: 68.471% (+0.2%) from 68.253%
13656780447

Pull #1085

github

web-flow
Merge 325976934 into ddb6d002d
Pull Request #1085: #654: improved plugin suppport

3065 of 4919 branches covered (62.31%)

Branch coverage included in aggregate %.

7926 of 11133 relevant lines covered (71.19%)

3.1 hits per line

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

89.12
cli/src/main/java/com/devonfw/tools/ide/tool/LocalToolCommandlet.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.nio.file.StandardOpenOption;
7
import java.util.Collection;
8
import java.util.Locale;
9
import java.util.Set;
10

11
import com.devonfw.tools.ide.common.Tag;
12
import com.devonfw.tools.ide.context.IdeContext;
13
import com.devonfw.tools.ide.io.FileAccess;
14
import com.devonfw.tools.ide.io.FileCopyMode;
15
import com.devonfw.tools.ide.process.EnvironmentContext;
16
import com.devonfw.tools.ide.process.ProcessContext;
17
import com.devonfw.tools.ide.step.Step;
18
import com.devonfw.tools.ide.tool.repository.ToolRepository;
19
import com.devonfw.tools.ide.url.model.file.json.ToolDependency;
20
import com.devonfw.tools.ide.version.GenericVersionRange;
21
import com.devonfw.tools.ide.version.VersionIdentifier;
22
import com.devonfw.tools.ide.version.VersionRange;
23

24
/**
25
 * {@link ToolCommandlet} that is installed locally into the IDEasy.
26
 */
27
public abstract class LocalToolCommandlet extends ToolCommandlet {
1✔
28

29
  /**
30
   * The constructor.
31
   *
32
   * @param context the {@link IdeContext}.
33
   * @param tool the {@link #getName() tool name}.
34
   * @param tags the {@link #getTags() tags} classifying the tool. Should be created via {@link Set#of(Object) Set.of} method.
35
   */
36
  public LocalToolCommandlet(IdeContext context, String tool, Set<Tag> tags) {
37

38
    super(context, tool, tags);
5✔
39
  }
1✔
40

41
  /**
42
   * @return the {@link Path} where the tool is located (installed).
43
   */
44
  public Path getToolPath() {
45

46
    return this.context.getSoftwarePath().resolve(getName());
7✔
47
  }
48

49
  /**
50
   * @return the {@link Path} where the executables of the tool can be found. Typically a "bin" folder inside {@link #getToolPath() tool path}.
51
   */
52
  public Path getToolBinPath() {
53

54
    Path toolPath = getToolPath();
3✔
55
    Path binPath = this.context.getFileAccess().findFirst(toolPath, path -> path.getFileName().toString().equals("bin"), false);
14✔
56
    if ((binPath != null) && Files.isDirectory(binPath)) {
7!
57
      return binPath;
2✔
58
    }
59
    return toolPath;
2✔
60
  }
61

62
  /**
63
   * @deprecated will be removed once all "dependencies.json" are created in ide-urls.
64
   */
65
  @Deprecated
66
  protected void installDependencies() {
67

68
  }
1✔
69

70
  @Override
71
  public boolean install(boolean silent, EnvironmentContext environmentContext) {
72
    return install(silent, (ProcessContext) environmentContext);
6✔
73
  }
74

75
  /**
76
   * Installs or updates the managed {@link #getName() tool}.
77
   *
78
   * @param silent - {@code true} if called recursively to suppress verbose logging, {@code false} otherwise.
79
   * @param processContext the {@link ProcessContext} used to
80
   *     {@link LocalToolCommandlet#setEnvironment(EnvironmentContext, ToolInstallation, boolean) configure environment variables}.
81
   * @return {@code true} if the tool was newly installed, {@code false} if the tool was already installed before and nothing has changed.
82
   */
83
  public boolean install(boolean silent, ProcessContext processContext) {
84

85
    installDependencies();
2✔
86
    VersionIdentifier configuredVersion = getConfiguredVersion();
3✔
87
    // get installed version before installInRepo actually may install the software
88
    VersionIdentifier installedVersion = getInstalledVersion();
3✔
89
    Step step = this.context.newStep(silent, "Install " + this.tool, configuredVersion);
14✔
90
    try {
91
      // install configured version of our tool in the software repository if not already installed
92
      ToolInstallation installation = installTool(configuredVersion, processContext);
5✔
93

94
      // check if we already have this version installed (linked) locally in IDE_HOME/software
95
      VersionIdentifier resolvedVersion = installation.resolvedVersion();
3✔
96
      if ((resolvedVersion.equals(installedVersion) && !installation.newInstallation())
9✔
97
          || (configuredVersion.matches(installedVersion) && context.isSkipUpdatesMode())) {
6!
98
        return toolAlreadyInstalled(silent, installedVersion, step, processContext);
9✔
99
      }
100
      if (!isIgnoreSoftwareRepo()) {
3✔
101
        // we need to link the version or update the link.
102
        Path toolPath = getToolPath();
3✔
103
        FileAccess fileAccess = this.context.getFileAccess();
4✔
104
        if (Files.exists(toolPath)) {
5✔
105
          fileAccess.backup(toolPath);
4✔
106
        }
107
        fileAccess.mkdirs(toolPath.getParent());
4✔
108
        fileAccess.symlink(installation.linkDir(), toolPath);
5✔
109
      }
110
      this.context.getPath().setPath(this.tool, installation.binDir());
8✔
111
      postInstall(true, processContext);
4✔
112
      if (installedVersion == null) {
2✔
113
        step.success("Successfully installed {} in version {}", this.tool, resolvedVersion);
15✔
114
      } else {
115
        step.success("Successfully installed {} in version {} replacing previous version {}", this.tool, resolvedVersion, installedVersion);
18✔
116
      }
117
      return true;
4✔
118
    } catch (RuntimeException e) {
1✔
119
      step.error(e, true);
4✔
120
      throw e;
2✔
121
    } finally {
122
      step.close();
2✔
123
    }
124

125
  }
126

127
  /**
128
   * This method is called after a tool was requested to be installed or updated.
129
   *
130
   * @param newlyInstalled {@code true} if the tool was installed or updated (at least link to software folder was created/updated), {@code false} otherwise
131
   *     (configured version was already installed and nothing changed).
132
   * @param pc the {@link ProcessContext} to use.
133
   */
134
  protected void postInstall(boolean newlyInstalled, ProcessContext pc) {
135

136
    if (newlyInstalled) {
2✔
137
      postInstall();
2✔
138
    }
139
  }
1✔
140

141
  /**
142
   * This method is called after the tool has been newly installed or updated to a new version.
143
   */
144
  protected void postInstall() {
145

146
    // nothing to do by default
147
  }
1✔
148

149
  private boolean toolAlreadyInstalled(boolean silent, VersionIdentifier installedVersion, Step step, ProcessContext pc) {
150
    if (!silent) {
2✔
151
      this.context.info("Version {} of tool {} is already installed", installedVersion, getToolWithEdition());
15✔
152
    }
153
    postInstall(false, pc);
4✔
154
    step.success();
2✔
155
    return false;
2✔
156
  }
157

158
  /**
159
   * Determines whether this tool should be installed directly in the software folder or in the software repository.
160
   *
161
   * @return {@code true} if the tool should be installed directly in the software folder, ignoring the central software repository; {@code false} if the tool
162
   *     should be installed in the central software repository (default behavior).
163
   */
164
  protected boolean isIgnoreSoftwareRepo() {
165

166
    return false;
2✔
167
  }
168

169
  /**
170
   * Performs the installation of the {@link #getName() tool} together with the environment context, managed by this
171
   * {@link com.devonfw.tools.ide.commandlet.Commandlet}.
172
   *
173
   * @param version the {@link GenericVersionRange} requested to be installed.
174
   * @param environmentContext the {@link EnvironmentContext} used to
175
   *     {@link #setEnvironment(EnvironmentContext, ToolInstallation, boolean) configure environment variables}.
176
   * @return the {@link ToolInstallation} matching the given {@code version}.
177
   */
178
  public ToolInstallation installTool(GenericVersionRange version, EnvironmentContext environmentContext) {
179

180
    return installTool(version, environmentContext, getConfiguredEdition());
7✔
181
  }
182

183
  /**
184
   * Performs the installation of the {@link #getName() tool} together with the environment context  managed by this
185
   * {@link com.devonfw.tools.ide.commandlet.Commandlet}.
186
   *
187
   * @param version the {@link GenericVersionRange} requested to be installed.
188
   * @param environmentContext the {@link EnvironmentContext} used to
189
   *     {@link #setEnvironment(EnvironmentContext, ToolInstallation, boolean) configure environment variables}.
190
   * @param edition the specific {@link #getConfiguredEdition() edition} to install.
191
   * @return the {@link ToolInstallation} matching the given {@code version}.
192
   */
193
  public ToolInstallation installTool(GenericVersionRange version, EnvironmentContext environmentContext, String edition) {
194

195
    // if version is a VersionRange, we are not called from install() but directly from installAsDependency() due to a version conflict of a dependency
196
    boolean extraInstallation = (version instanceof VersionRange);
3✔
197
    ToolRepository toolRepository = getToolRepository();
3✔
198
    VersionIdentifier resolvedVersion = toolRepository.resolveVersion(this.tool, edition, version, this);
8✔
199
    installToolDependencies(resolvedVersion, edition, environmentContext);
5✔
200

201
    Path installationPath;
202
    boolean ignoreSoftwareRepo = isIgnoreSoftwareRepo();
3✔
203
    if (ignoreSoftwareRepo) {
2✔
204
      installationPath = getToolPath();
4✔
205
    } else {
206
      Path softwareRepoPath = this.context.getSoftwareRepositoryPath().resolve(toolRepository.getId()).resolve(this.tool).resolve(edition);
12✔
207
      installationPath = softwareRepoPath.resolve(resolvedVersion.toString());
5✔
208
    }
209
    Path toolVersionFile = installationPath.resolve(IdeContext.FILE_SOFTWARE_VERSION);
4✔
210
    FileAccess fileAccess = this.context.getFileAccess();
4✔
211
    if (Files.isDirectory(installationPath)) {
5✔
212
      if (Files.exists(toolVersionFile)) {
5!
213
        if (!ignoreSoftwareRepo || resolvedVersion.equals(getInstalledVersion())) {
2!
214
          this.context.debug("Version {} of tool {} is already installed at {}", resolvedVersion, getToolWithEdition(this.tool, edition), installationPath);
21✔
215
          return createToolInstallation(installationPath, resolvedVersion, toolVersionFile, false, environmentContext, extraInstallation);
9✔
216
        }
217
      } else {
218
        this.context.warning("Deleting corrupted installation at {}", installationPath);
×
219
        fileAccess.delete(installationPath);
×
220
      }
221
    }
222
    Path downloadedToolFile = downloadTool(edition, toolRepository, resolvedVersion);
6✔
223
    boolean extract = isExtract();
3✔
224
    if (!extract) {
2✔
225
      this.context.trace("Extraction is disabled for '{}' hence just moving the downloaded file {}.", this.tool, downloadedToolFile);
15✔
226
    }
227
    if (Files.exists(installationPath)) {
5!
228
      fileAccess.backup(installationPath);
×
229
    }
230
    fileAccess.mkdirs(installationPath.getParent());
4✔
231
    fileAccess.extract(downloadedToolFile, installationPath, this::postExtract, extract);
7✔
232
    try {
233
      Files.writeString(toolVersionFile, resolvedVersion.toString(), StandardOpenOption.CREATE_NEW);
11✔
234
    } catch (IOException e) {
×
235
      throw new IllegalStateException("Failed to write version file " + toolVersionFile, e);
×
236
    }
1✔
237
    this.context.debug("Installed {} in version {} at {}", this.tool, resolvedVersion, installationPath);
19✔
238
    return createToolInstallation(installationPath, resolvedVersion, toolVersionFile, true, environmentContext, extraInstallation);
9✔
239
  }
240

241
  /**
242
   * @param edition the {@link #getConfiguredEdition() tool edition} to download.
243
   * @param toolRepository the {@link ToolRepository} to use.
244
   * @param resolvedVersion the resolved {@link VersionIdentifier version} to download.
245
   * @return the {@link Path} to the downloaded release file.
246
   */
247
  protected Path downloadTool(String edition, ToolRepository toolRepository, VersionIdentifier resolvedVersion) {
248
    return toolRepository.download(this.tool, edition, resolvedVersion, this);
8✔
249
  }
250

251
  /**
252
   * Install this tool as dependency of another tool.
253
   *
254
   * @param version the required {@link VersionRange}. See {@link ToolDependency#versionRange()}.
255
   * @param environmentContext the {@link EnvironmentContext}.
256
   * @return {@code true} if the tool was newly installed, {@code false} otherwise (installation was already present).
257
   */
258
  public boolean installAsDependency(VersionRange version, EnvironmentContext environmentContext) {
259

260
    VersionIdentifier configuredVersion = getConfiguredVersion();
3✔
261
    if (version.contains(configuredVersion)) {
4✔
262
      // prefer configured version if contained in version range
263
      return install(false, environmentContext);
5✔
264
    } else {
265
      if (isIgnoreSoftwareRepo()) {
3!
266
        throw new IllegalStateException(
×
267
            "Cannot satisfy dependency to " + this.tool + " in version " + version + " since it is conflicting with configured version " + configuredVersion
268
                + " and this tool does not support the software repository.");
269
      }
270
      this.context.info(
19✔
271
          "Configured version of tool {} is {} but does not match version to install {} - need to use different version from software repository.",
272
          this.tool, configuredVersion, version);
273
    }
274
    ToolInstallation toolInstallation = installTool(version, environmentContext);
5✔
275
    return toolInstallation.newInstallation();
3✔
276
  }
277

278
  private void installToolDependencies(VersionIdentifier version, String edition, EnvironmentContext environmentContext) {
279
    Collection<ToolDependency> dependencies = getToolRepository().findDependencies(this.tool, edition, version);
8✔
280
    String toolWithEdition = getToolWithEdition(this.tool, edition);
5✔
281
    int size = dependencies.size();
3✔
282
    this.context.debug("Tool {} has {} other tool(s) as dependency", toolWithEdition, size);
15✔
283
    for (ToolDependency dependency : dependencies) {
10✔
284
      this.context.trace("Ensuring dependency {} for tool {}", dependency.tool(), toolWithEdition);
15✔
285
      LocalToolCommandlet dependencyTool = this.context.getCommandletManager().getRequiredLocalToolCommandlet(dependency.tool());
7✔
286
      dependencyTool.installAsDependency(dependency.versionRange(), environmentContext);
6✔
287
    }
1✔
288
  }
1✔
289

290
  /**
291
   * Post-extraction hook that can be overridden to add custom processing after unpacking and before moving to the final destination folder.
292
   *
293
   * @param extractedDir the {@link Path} to the folder with the unpacked tool.
294
   */
295
  protected void postExtract(Path extractedDir) {
296

297
  }
1✔
298

299
  @Override
300
  public VersionIdentifier getInstalledVersion() {
301

302
    return getInstalledVersion(this.context.getSoftwarePath().resolve(getName()));
9✔
303
  }
304

305
  /**
306
   * @param toolPath the installation {@link Path} where to find the version file.
307
   * @return the currently installed {@link VersionIdentifier version} of this tool or {@code null} if not installed.
308
   */
309
  protected VersionIdentifier getInstalledVersion(Path toolPath) {
310

311
    if (!Files.isDirectory(toolPath)) {
5✔
312
      this.context.debug("Tool {} not installed in {}", getName(), toolPath);
15✔
313
      return null;
2✔
314
    }
315
    Path toolVersionFile = toolPath.resolve(IdeContext.FILE_SOFTWARE_VERSION);
4✔
316
    if (!Files.exists(toolVersionFile)) {
5✔
317
      Path legacyToolVersionFile = toolPath.resolve(IdeContext.FILE_LEGACY_SOFTWARE_VERSION);
4✔
318
      if (Files.exists(legacyToolVersionFile)) {
5✔
319
        toolVersionFile = legacyToolVersionFile;
3✔
320
      } else {
321
        this.context.warning("Tool {} is missing version file in {}", getName(), toolVersionFile);
15✔
322
        return null;
2✔
323
      }
324
    }
325
    String version = this.context.getFileAccess().readFileContent(toolVersionFile).trim();
7✔
326
    return VersionIdentifier.of(version);
3✔
327
  }
328

329
  @Override
330
  public String getInstalledEdition() {
331

332
    if (this.context.getSoftwarePath() == null) {
4✔
333
      return "";
2✔
334
    }
335
    return getInstalledEdition(this.context.getSoftwarePath().resolve(this.tool));
9✔
336
  }
337

338
  /**
339
   * @param toolPath the installation {@link Path} where to find currently installed tool. The name of the parent directory of the real path corresponding
340
   *     to the passed {@link Path path} must be the name of the edition.
341
   * @return the installed edition of this tool or {@code null} if not installed.
342
   */
343
  private String getInstalledEdition(Path toolPath) {
344

345
    if (!Files.isDirectory(toolPath)) {
5✔
346
      this.context.debug("Tool {} not installed in {}", this.tool, toolPath);
15✔
347
      return null;
2✔
348
    }
349
    Path realPath = this.context.getFileAccess().toRealPath(toolPath);
6✔
350
    // if the realPath changed, a link has been resolved
351
    if (realPath.equals(toolPath)) {
4✔
352
      if (!isIgnoreSoftwareRepo()) {
3!
353
        this.context.warning("Tool {} is not installed via software repository (maybe from devonfw-ide). Please consider reinstalling it.", this.tool);
11✔
354
      }
355
      // I do not see any reliable way how we could determine the edition of a tool that does not use software repo or that was installed by devonfw-ide
356
      return getConfiguredEdition();
3✔
357
    }
358
    Path toolRepoFolder = context.getSoftwareRepositoryPath().resolve(ToolRepository.ID_DEFAULT).resolve(this.tool);
9✔
359
    String edition = getEdition(toolRepoFolder, realPath);
5✔
360
    if (!getToolRepository().getSortedEditions(this.tool).contains(edition)) {
8✔
361
      this.context.warning("Undefined edition {} of tool {}", edition, this.tool);
15✔
362
    }
363
    return edition;
2✔
364
  }
365

366
  private String getEdition(Path toolRepoFolder, Path toolInstallFolder) {
367

368
    int toolRepoNameCount = toolRepoFolder.getNameCount();
3✔
369
    int toolInstallNameCount = toolInstallFolder.getNameCount();
3✔
370
    if (toolRepoNameCount < toolInstallNameCount) {
3!
371
      // ensure toolInstallFolder starts with $IDE_ROOT/_ide/software/default/«tool»
372
      for (int i = 0; i < toolRepoNameCount; i++) {
7✔
373
        if (!toolRepoFolder.getName(i).toString().equals(toolInstallFolder.getName(i).toString())) {
10!
374
          return null;
×
375
        }
376
      }
377
      return toolInstallFolder.getName(toolRepoNameCount).toString();
5✔
378
    }
379
    return null;
×
380
  }
381

382
  @Override
383
  public void uninstall() {
384

385
    try {
386
      Path softwarePath = getToolPath();
3✔
387
      if (Files.exists(softwarePath)) {
5!
388
        try {
389
          this.context.getFileAccess().delete(softwarePath);
5✔
390
          this.context.success("Successfully uninstalled " + this.tool);
6✔
391
        } catch (Exception e) {
×
392
          this.context.error("Couldn't uninstall " + this.tool);
×
393
        }
1✔
394
      } else {
395
        this.context.warning("An installed version of " + this.tool + " does not exist");
×
396
      }
397
    } catch (Exception e) {
×
398
      this.context.error(e.getMessage());
×
399
    }
1✔
400
  }
1✔
401

402
  private ToolInstallation createToolInstallation(Path rootDir, VersionIdentifier resolvedVersion, Path toolVersionFile,
403
      boolean newInstallation, EnvironmentContext environmentContext, boolean extraInstallation) {
404

405
    Path linkDir = getMacOsHelper().findLinkDir(rootDir, getBinaryName());
7✔
406
    Path binDir = linkDir;
2✔
407
    Path binFolder = binDir.resolve(IdeContext.FOLDER_BIN);
4✔
408
    if (Files.isDirectory(binFolder)) {
5✔
409
      binDir = binFolder;
2✔
410
    }
411
    if (linkDir != rootDir) {
3✔
412
      assert (!linkDir.equals(rootDir));
5!
413
      this.context.getFileAccess().copy(toolVersionFile, linkDir, FileCopyMode.COPY_FILE_OVERRIDE);
7✔
414
    }
415
    ToolInstallation toolInstallation = new ToolInstallation(rootDir, linkDir, binDir, resolvedVersion, newInstallation);
9✔
416
    setEnvironment(environmentContext, toolInstallation, extraInstallation);
5✔
417
    return toolInstallation;
2✔
418
  }
419

420
  /**
421
   * Method to set environment variables for the process context.
422
   *
423
   * @param environmentContext the {@link EnvironmentContext} where to {@link EnvironmentContext#withEnvVar(String, String) set environment variables} for
424
   *     this tool.
425
   * @param toolInstallation the {@link ToolInstallation}.
426
   * @param extraInstallation {@code true} if the {@link ToolInstallation} is an additional installation to the
427
   *     {@link #getConfiguredVersion() configured version} due to a conflicting version of a {@link ToolDependency}, {@code false} otherwise.
428
   */
429
  public void setEnvironment(EnvironmentContext environmentContext, ToolInstallation toolInstallation, boolean extraInstallation) {
430

431
    String pathVariable = this.tool.toUpperCase(Locale.ROOT) + "_HOME";
6✔
432
    environmentContext.withEnvVar(pathVariable, toolInstallation.linkDir().toString());
7✔
433
    if (extraInstallation) {
2✔
434
      environmentContext.withPathEntry(toolInstallation.binDir());
5✔
435
    }
436
  }
1✔
437

438

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