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

devonfw / IDEasy / 11061200804

26 Sep 2024 10:27PM UTC coverage: 66.053% (-0.05%) from 66.107%
11061200804

push

github

web-flow
#593: #651: #564: #439: fixed bugs, refactored tool dependencies (#652)

2312 of 3848 branches covered (60.08%)

Branch coverage included in aggregate %.

6078 of 8854 relevant lines covered (68.65%)

3.03 hits per line

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

80.86
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.log.IdeLogLevel;
16
import com.devonfw.tools.ide.process.EnvironmentContext;
17
import com.devonfw.tools.ide.repo.ToolRepository;
18
import com.devonfw.tools.ide.step.Step;
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();
×
55
    Path binPath = this.context.getFileAccess().findFirst(toolPath, path -> path.getFileName().toString().equals("bin"), false);
×
56
    if ((binPath != null) && Files.isDirectory(binPath)) {
×
57
      return binPath;
×
58
    }
59
    return toolPath;
×
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 final boolean install(boolean silent, EnvironmentContext environmentContext) {
72

73
    installDependencies();
2✔
74
    VersionIdentifier configuredVersion = getConfiguredVersion();
3✔
75
    // get installed version before installInRepo actually may install the software
76
    VersionIdentifier installedVersion = getInstalledVersion();
3✔
77
    Step step = this.context.newStep(silent, "Install " + this.tool, configuredVersion);
14✔
78
    try {
79
      // performance: avoid calling installTool if already up-to-date
80
      if (configuredVersion.equals(installedVersion)) { // here we can add https://github.com/devonfw/IDEasy/issues/637
4✔
81
        return toolAlreadyInstalled(silent, installedVersion, step);
8✔
82
      }
83
      // install configured version of our tool in the software repository if not already installed
84
      ToolInstallation installation = installTool(configuredVersion, environmentContext);
5✔
85

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

116
  }
117

118
  private boolean toolAlreadyInstalled(boolean silent, VersionIdentifier installedVersion, Step step) {
119
    IdeLogLevel level = silent ? IdeLogLevel.DEBUG : IdeLogLevel.INFO;
6✔
120
    this.context.level(level).log("Version {} of tool {} is already installed", installedVersion, getToolWithEdition());
18✔
121
    postInstall(false);
3✔
122
    step.success();
2✔
123
    return false;
2✔
124
  }
125

126
  /**
127
   * Determines whether this tool should be installed directly in the software folder or in the software repository.
128
   *
129
   * @return {@code true} if the tool should be installed directly in the software folder, ignoring the central software repository; {@code false} if the tool
130
   *     should be installed in the central software repository (default behavior).
131
   */
132
  protected boolean isIgnoreSoftwareRepo() {
133

134
    return false;
2✔
135
  }
136

137
  /**
138
   * Performs the installation of the {@link #getName() tool} together with the environment context, managed by this
139
   * {@link com.devonfw.tools.ide.commandlet.Commandlet}.
140
   *
141
   * @param version the {@link GenericVersionRange} requested to be installed.
142
   * @param environmentContext the {@link EnvironmentContext} used to
143
   *     {@link #setEnvironment(EnvironmentContext, ToolInstallation, boolean) configure environment variables}.
144
   * @return the {@link ToolInstallation} matching the given {@code version}.
145
   */
146
  public ToolInstallation installTool(GenericVersionRange version, EnvironmentContext environmentContext) {
147

148
    return installTool(version, environmentContext, getConfiguredEdition());
7✔
149
  }
150

151
  /**
152
   * Performs the installation of the {@link #getName() tool} together with the environment context  managed by this
153
   * {@link com.devonfw.tools.ide.commandlet.Commandlet}.
154
   *
155
   * @param version the {@link GenericVersionRange} requested to be installed.
156
   * @param environmentContext the {@link EnvironmentContext} used to
157
   *     {@link #setEnvironment(EnvironmentContext, ToolInstallation, boolean) configure environment variables}.
158
   * @param edition the specific {@link #getConfiguredEdition() edition} to install.
159
   * @return the {@link ToolInstallation} matching the given {@code version}.
160
   */
161
  public ToolInstallation installTool(GenericVersionRange version, EnvironmentContext environmentContext, String edition) {
162

163
    return installTool(version, environmentContext, edition, this.context.getDefaultToolRepository());
9✔
164
  }
165

166
  /**
167
   * Performs the installation of the {@link #getName() tool} managed by this {@link com.devonfw.tools.ide.commandlet.Commandlet}.
168
   *
169
   * @param version the {@link GenericVersionRange} requested to be installed.
170
   * @param environmentContext the {@link EnvironmentContext} used to
171
   *     {@link #setEnvironment(EnvironmentContext, ToolInstallation, boolean) configure environment variables}.
172
   * @param edition the specific {@link #getConfiguredEdition() edition} to install.
173
   * @param toolRepository the {@link ToolRepository} to use.
174
   * @return the {@link ToolInstallation} matching the given {@code version}.
175
   */
176
  public ToolInstallation installTool(GenericVersionRange version, EnvironmentContext environmentContext, String edition, ToolRepository toolRepository) {
177

178
    // if version is a VersionRange, we are not called from install() but directly from installAsDependency() due to a version conflict of a dependency
179
    boolean extraInstallation = (version instanceof VersionRange);
3✔
180
    VersionIdentifier resolvedVersion = toolRepository.resolveVersion(this.tool, edition, version);
7✔
181
    installToolDependencies(resolvedVersion, edition, environmentContext, toolRepository);
6✔
182

183
    Path installationPath;
184
    boolean ignoreSoftwareRepo = isIgnoreSoftwareRepo();
3✔
185
    if (ignoreSoftwareRepo) {
2✔
186
      installationPath = getToolPath();
4✔
187
    } else {
188
      Path softwareRepoPath = this.context.getSoftwareRepositoryPath().resolve(toolRepository.getId()).resolve(this.tool).resolve(edition);
12✔
189
      installationPath = softwareRepoPath.resolve(resolvedVersion.toString());
5✔
190
    }
191
    Path toolVersionFile = installationPath.resolve(IdeContext.FILE_SOFTWARE_VERSION);
4✔
192
    FileAccess fileAccess = this.context.getFileAccess();
4✔
193
    if (Files.isDirectory(installationPath)) {
5✔
194
      if (Files.exists(toolVersionFile)) {
5!
195
        if (this.context.isForceMode()) {
4!
196
          fileAccess.delete(installationPath);
×
197
        } else {
198
          if (!ignoreSoftwareRepo || resolvedVersion.equals(getInstalledVersion())) {
2!
199
            this.context.debug("Version {} of tool {} is already installed at {}", resolvedVersion, getToolWithEdition(this.tool, edition), installationPath);
21✔
200
            return createToolInstallation(installationPath, resolvedVersion, toolVersionFile, false, environmentContext, extraInstallation);
9✔
201
          }
202
        }
203
      } else {
204
        this.context.warning("Deleting corrupted installation at {}", installationPath);
×
205
        fileAccess.delete(installationPath);
×
206
      }
207
    }
208
    Path target = toolRepository.download(this.tool, edition, resolvedVersion);
7✔
209
    boolean extract = isExtract();
3✔
210
    if (!extract) {
2✔
211
      this.context.trace("Extraction is disabled for '{}' hence just moving the downloaded file {}.", this.tool, target);
15✔
212
    }
213
    if (Files.exists(installationPath)) {
5!
214
      fileAccess.backup(installationPath);
×
215
    }
216
    fileAccess.mkdirs(installationPath.getParent());
4✔
217
    fileAccess.extract(target, installationPath, this::postExtract, extract);
7✔
218
    try {
219
      Files.writeString(toolVersionFile, resolvedVersion.toString(), StandardOpenOption.CREATE_NEW);
11✔
220
    } catch (IOException e) {
×
221
      throw new IllegalStateException("Failed to write version file " + toolVersionFile, e);
×
222
    }
1✔
223
    this.context.debug("Installed {} in version {} at {}", this.tool, resolvedVersion, installationPath);
19✔
224
    return createToolInstallation(installationPath, resolvedVersion, toolVersionFile, true, environmentContext, extraInstallation);
9✔
225
  }
226

227
  /**
228
   * Install this tool as dependency of another tool.
229
   *
230
   * @param version the required {@link VersionRange}. See {@link ToolDependency#versionRange()}.
231
   * @param environmentContext the {@link EnvironmentContext}.
232
   * @return {@code true} if the tool was newly installed, {@code false} otherwise (installation was already present).
233
   */
234
  public boolean installAsDependency(VersionRange version, EnvironmentContext environmentContext) {
235

236
    VersionIdentifier configuredVersion = getConfiguredVersion();
3✔
237
    if (version.contains(configuredVersion)) {
4!
238
      // prefer configured version if contained in version range
239
      return install();
×
240
    } else {
241
      if (isIgnoreSoftwareRepo()) {
3!
242
        throw new IllegalStateException(
×
243
            "Cannot satisfy dependency to " + this.tool + " in version " + version + " since it is conflicting with configured version " + configuredVersion
244
                + " and this tool does not support the software repository.");
245
      }
246
      this.context.info("Configured version is {} but does not match version to install {} - need to use different version from software repository.",
14✔
247
          configuredVersion, version);
248
    }
249
    ToolInstallation toolInstallation = installTool(version, environmentContext);
5✔
250
    return toolInstallation.newInstallation();
3✔
251
  }
252

253
  private void installToolDependencies(VersionIdentifier version, String edition, EnvironmentContext environmentContext, ToolRepository toolRepository) {
254
    Collection<ToolDependency> dependencies = toolRepository.findDependencies(this.tool, edition, version);
7✔
255
    for (ToolDependency dependency : dependencies) {
10✔
256
      LocalToolCommandlet dependencyTool = this.context.getCommandletManager().getRequiredLocalToolCommandlet(dependency.tool());
7✔
257
      dependencyTool.installAsDependency(dependency.versionRange(), environmentContext);
6✔
258
    }
1✔
259
  }
1✔
260

261
  /**
262
   * Post-extraction hook that can be overridden to add custom processing after unpacking and before moving to the final destination folder.
263
   *
264
   * @param extractedDir the {@link Path} to the folder with the unpacked tool.
265
   */
266
  protected void postExtract(Path extractedDir) {
267

268
  }
1✔
269

270
  @Override
271
  public VersionIdentifier getInstalledVersion() {
272

273
    return getInstalledVersion(this.context.getSoftwarePath().resolve(getName()));
9✔
274
  }
275

276
  /**
277
   * @param toolPath the installation {@link Path} where to find the version file.
278
   * @return the currently installed {@link VersionIdentifier version} of this tool or {@code null} if not installed.
279
   */
280
  protected VersionIdentifier getInstalledVersion(Path toolPath) {
281

282
    if (!Files.isDirectory(toolPath)) {
5✔
283
      this.context.debug("Tool {} not installed in {}", getName(), toolPath);
15✔
284
      return null;
2✔
285
    }
286
    Path toolVersionFile = toolPath.resolve(IdeContext.FILE_SOFTWARE_VERSION);
4✔
287
    if (!Files.exists(toolVersionFile)) {
5✔
288
      Path legacyToolVersionFile = toolPath.resolve(IdeContext.FILE_LEGACY_SOFTWARE_VERSION);
4✔
289
      if (Files.exists(legacyToolVersionFile)) {
5✔
290
        toolVersionFile = legacyToolVersionFile;
3✔
291
      } else {
292
        this.context.warning("Tool {} is missing version file in {}", getName(), toolVersionFile);
15✔
293
        return null;
2✔
294
      }
295
    }
296
    this.context.trace("Reading tool version from {}", toolVersionFile);
10✔
297
    try {
298
      String version = Files.readString(toolVersionFile).trim();
4✔
299
      this.context.trace("Read tool version {} from {}", version, toolVersionFile);
14✔
300
      return VersionIdentifier.of(version);
3✔
301
    } catch (IOException e) {
×
302
      throw new IllegalStateException("Failed to read file " + toolVersionFile, e);
×
303
    }
304
  }
305

306
  @Override
307
  public String getInstalledEdition() {
308

309
    return getInstalledEdition(this.context.getSoftwarePath().resolve(getName()));
9✔
310
  }
311

312
  /**
313
   * @param toolPath the installation {@link Path} where to find currently installed tool. The name of the parent directory of the real path corresponding
314
   *     to the passed {@link Path path} must be the name of the edition.
315
   * @return the installed edition of this tool or {@code null} if not installed.
316
   */
317
  public String getInstalledEdition(Path toolPath) {
318

319
    if (!Files.isDirectory(toolPath)) {
5✔
320
      this.context.debug("Tool {} not installed in {}", getName(), toolPath);
15✔
321
      return null;
2✔
322
    }
323
    try {
324
      String edition = toolPath.toRealPath().getParent().getFileName().toString();
8✔
325
      if (!this.context.getUrls().getSortedEditions(getName()).contains(edition)) {
9!
326
        edition = getConfiguredEdition();
3✔
327
      }
328
      return edition;
2✔
329
    } catch (IOException e) {
×
330
      throw new IllegalStateException(
×
331
          "Couldn't determine the edition of " + getName() + " from the directory structure of its software path "
×
332
              + toolPath
333
              + ", assuming the name of the parent directory of the real path of the software path to be the edition "
334
              + "of the tool.", e);
335
    }
336
  }
337

338
  @Override
339
  public void uninstall() {
340

341
    try {
342
      Path softwarePath = getToolPath();
3✔
343
      if (Files.exists(softwarePath)) {
5✔
344
        try {
345
          this.context.getFileAccess().delete(softwarePath);
5✔
346
          this.context.success("Successfully uninstalled " + this.tool);
6✔
347
        } catch (Exception e) {
1✔
348
          this.context.error("Couldn't uninstall " + this.tool);
6✔
349
        }
2✔
350
      } else {
351
        this.context.warning("An installed version of " + this.tool + " does not exist");
6✔
352
      }
353
    } catch (Exception e) {
×
354
      this.context.error(e.getMessage());
×
355
    }
1✔
356
  }
1✔
357

358
  private ToolInstallation createToolInstallation(Path rootDir, VersionIdentifier resolvedVersion, Path toolVersionFile,
359
      boolean newInstallation, EnvironmentContext environmentContext, boolean extraInstallation) {
360

361
    Path linkDir = getMacOsHelper().findLinkDir(rootDir, getBinaryName());
7✔
362
    Path binDir = linkDir;
2✔
363
    Path binFolder = binDir.resolve(IdeContext.FOLDER_BIN);
4✔
364
    if (Files.isDirectory(binFolder)) {
5✔
365
      binDir = binFolder;
2✔
366
    }
367
    if (linkDir != rootDir) {
3✔
368
      assert (!linkDir.equals(rootDir));
5!
369
      this.context.getFileAccess().copy(toolVersionFile, linkDir, FileCopyMode.COPY_FILE_OVERRIDE);
7✔
370
    }
371
    ToolInstallation toolInstallation = new ToolInstallation(rootDir, linkDir, binDir, resolvedVersion, newInstallation);
9✔
372
    setEnvironment(environmentContext, toolInstallation, extraInstallation);
5✔
373
    return toolInstallation;
2✔
374
  }
375

376
  /**
377
   * Method to set environment variables for the process context.
378
   *
379
   * @param environmentContext the {@link EnvironmentContext} where to {@link EnvironmentContext#withEnvVar(String, String) set environment variables} for
380
   *     this tool.
381
   * @param toolInstallation the {@link ToolInstallation}.
382
   * @param extraInstallation {@code true} if the {@link ToolInstallation} is an additional installation to the
383
   *     {@link #getConfiguredVersion() configured version} due to a conflicting version of a {@link ToolDependency}, {@code false} otherwise.
384
   */
385
  protected void setEnvironment(EnvironmentContext environmentContext, ToolInstallation toolInstallation, boolean extraInstallation) {
386

387
    String pathVariable = this.tool.toUpperCase(Locale.ROOT) + "_HOME";
6✔
388
    environmentContext.withEnvVar(pathVariable, toolInstallation.linkDir().toString());
7✔
389
    if (extraInstallation) {
2✔
390
      environmentContext.withPathEntry(toolInstallation.binDir());
5✔
391
    }
392
  }
1✔
393

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