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

devonfw / IDEasy / 11122792269

01 Oct 2024 09:43AM UTC coverage: 66.525%. Remained the same
11122792269

Pull #667

github

web-flow
Merge e274b240b into dba26968b
Pull Request #667: #659: #664: fix deps

2331 of 3848 branches covered (60.58%)

Branch coverage included in aggregate %.

6123 of 8860 relevant lines covered (69.11%)

3.05 hits per line

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

85.92
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();
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 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
      // TODO https://github.com/devonfw/IDEasy/issues/664
80
      boolean enableOptimization = false;
2✔
81
      // performance: avoid calling installTool if already up-to-date
82
      if (enableOptimization & configuredVersion.equals(installedVersion)) { // here we can add https://github.com/devonfw/IDEasy/issues/637
6!
83
        return toolAlreadyInstalled(silent, installedVersion, step);
×
84
      }
85
      // install configured version of our tool in the software repository if not already installed
86
      ToolInstallation installation = installTool(configuredVersion, environmentContext);
5✔
87

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

118
  }
119

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

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

136
    return false;
2✔
137
  }
138

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

150
    return installTool(version, environmentContext, getConfiguredEdition());
7✔
151
  }
152

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

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

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

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

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

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

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

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

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

267
  }
1✔
268

269
  @Override
270
  public VersionIdentifier getInstalledVersion() {
271

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

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

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

305
  @Override
306
  public String getInstalledEdition() {
307

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

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

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

337
  @Override
338
  public void uninstall() {
339

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

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

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

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

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

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

© 2025 Coveralls, Inc