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

devonfw / IDEasy / 13344877458

15 Feb 2025 12:10PM UTC coverage: 67.959% (-0.5%) from 68.482%
13344877458

Pull #1021

github

web-flow
Merge 3118dedf4 into c70643978
Pull Request #1021: #786: support ide upgrade to automatically update to the latest version of IDEasy

2966 of 4793 branches covered (61.88%)

Branch coverage included in aggregate %.

7690 of 10887 relevant lines covered (70.63%)

3.07 hits per line

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

86.75
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.step.Step;
17
import com.devonfw.tools.ide.tool.repository.ToolRepository;
18
import com.devonfw.tools.ide.url.model.file.json.ToolDependency;
19
import com.devonfw.tools.ide.version.GenericVersionRange;
20
import com.devonfw.tools.ide.version.VersionIdentifier;
21
import com.devonfw.tools.ide.version.VersionRange;
22

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

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

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

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

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

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

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

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

67
  }
1✔
68

69
  @Override
70
  public boolean install(boolean silent, EnvironmentContext environmentContext) {
71

72
    installDependencies();
2✔
73
    VersionIdentifier configuredVersion = getConfiguredVersion();
3✔
74
    // get installed version before installInRepo actually may install the software
75
    VersionIdentifier installedVersion = getInstalledVersion();
3✔
76
    Step step = this.context.newStep(silent, "Install " + this.tool, configuredVersion);
14✔
77
    try {
78
      // install configured version of our tool in the software repository if not already installed
79
      ToolInstallation installation = installTool(configuredVersion, environmentContext);
5✔
80

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

112
  }
113

114
  /**
115
   * This method is called after a tool was requested to be installed or updated.
116
   *
117
   * @param newlyInstalled {@code true} if the tool was installed or updated (at least link to software folder was created/updated), {@code false} otherwise
118
   *     (configured version was already installed and nothing changed).
119
   */
120
  protected void postInstall(boolean newlyInstalled) {
121

122
    if (newlyInstalled) {
2✔
123
      postInstall();
2✔
124
    }
125
  }
1✔
126

127
  /**
128
   * This method is called after the tool has been newly installed or updated to a new version.
129
   */
130
  protected void postInstall() {
131

132
    // nothing to do by default
133
  }
1✔
134

135
  private boolean toolAlreadyInstalled(boolean silent, VersionIdentifier installedVersion, Step step) {
136
    if (!silent) {
2✔
137
      this.context.info("Version {} of tool {} is already installed", installedVersion, getToolWithEdition());
15✔
138
    }
139
    postInstall(false);
3✔
140
    step.success();
2✔
141
    return false;
2✔
142
  }
143

144
  /**
145
   * Determines whether this tool should be installed directly in the software folder or in the software repository.
146
   *
147
   * @return {@code true} if the tool should be installed directly in the software folder, ignoring the central software repository; {@code false} if the tool
148
   *     should be installed in the central software repository (default behavior).
149
   */
150
  protected boolean isIgnoreSoftwareRepo() {
151

152
    return false;
2✔
153
  }
154

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

166
    return installTool(version, environmentContext, getConfiguredEdition());
7✔
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
   * @param edition the specific {@link #getConfiguredEdition() edition} to install.
177
   * @return the {@link ToolInstallation} matching the given {@code version}.
178
   */
179
  public ToolInstallation installTool(GenericVersionRange version, EnvironmentContext environmentContext, String edition) {
180

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

187
    Path installationPath;
188
    boolean ignoreSoftwareRepo = isIgnoreSoftwareRepo();
3✔
189
    if (ignoreSoftwareRepo) {
2✔
190
      installationPath = getToolPath();
4✔
191
    } else {
192
      Path softwareRepoPath = this.context.getSoftwareRepositoryPath().resolve(toolRepository.getId()).resolve(this.tool).resolve(edition);
12✔
193
      installationPath = softwareRepoPath.resolve(resolvedVersion.toString());
5✔
194
    }
195
    Path toolVersionFile = installationPath.resolve(IdeContext.FILE_SOFTWARE_VERSION);
4✔
196
    FileAccess fileAccess = this.context.getFileAccess();
4✔
197
    if (Files.isDirectory(installationPath)) {
5✔
198
      if (Files.exists(toolVersionFile)) {
5!
199
        if (!ignoreSoftwareRepo || resolvedVersion.equals(getInstalledVersion())) {
2!
200
          this.context.debug("Version {} of tool {} is already installed at {}", resolvedVersion, getToolWithEdition(this.tool, edition), installationPath);
21✔
201
          return createToolInstallation(installationPath, resolvedVersion, toolVersionFile, false, environmentContext, extraInstallation);
9✔
202
        }
203
      } else {
204
        this.context.warning("Deleting corrupted installation at {}", installationPath);
×
205
        fileAccess.delete(installationPath);
×
206
      }
207
    }
208
    Path downloadedToolFile = downloadTool(edition, toolRepository, resolvedVersion);
6✔
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, downloadedToolFile);
15✔
212
    }
213
    if (Files.exists(installationPath)) {
5!
214
      fileAccess.backup(installationPath);
×
215
    }
216
    fileAccess.mkdirs(installationPath.getParent());
4✔
217
    fileAccess.extract(downloadedToolFile, 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
   * @param edition the {@link #getConfiguredEdition() tool edition} to download.
229
   * @param toolRepository the {@link ToolRepository} to use.
230
   * @param resolvedVersion the resolved {@link VersionIdentifier version} to download.
231
   * @return the {@link Path} to the downloaded release file.
232
   */
233
  protected Path downloadTool(String edition, ToolRepository toolRepository, VersionIdentifier resolvedVersion) {
234
    return toolRepository.download(this.tool, edition, resolvedVersion, this);
8✔
235
  }
236

237
  /**
238
   * Install this tool as dependency of another tool.
239
   *
240
   * @param version the required {@link VersionRange}. See {@link ToolDependency#versionRange()}.
241
   * @param environmentContext the {@link EnvironmentContext}.
242
   * @return {@code true} if the tool was newly installed, {@code false} otherwise (installation was already present).
243
   */
244
  public boolean installAsDependency(VersionRange version, EnvironmentContext environmentContext) {
245

246
    VersionIdentifier configuredVersion = getConfiguredVersion();
3✔
247
    if (version.contains(configuredVersion)) {
4✔
248
      // prefer configured version if contained in version range
249
      return install(false, environmentContext);
5✔
250
    } else {
251
      if (isIgnoreSoftwareRepo()) {
3!
252
        throw new IllegalStateException(
×
253
            "Cannot satisfy dependency to " + this.tool + " in version " + version + " since it is conflicting with configured version " + configuredVersion
254
                + " and this tool does not support the software repository.");
255
      }
256
      this.context.info(
19✔
257
          "Configured version of tool {} is {} but does not match version to install {} - need to use different version from software repository.",
258
          this.tool, configuredVersion, version);
259
    }
260
    ToolInstallation toolInstallation = installTool(version, environmentContext);
5✔
261
    return toolInstallation.newInstallation();
3✔
262
  }
263

264
  private void installToolDependencies(VersionIdentifier version, String edition, EnvironmentContext environmentContext) {
265
    Collection<ToolDependency> dependencies = getToolRepository().findDependencies(this.tool, edition, version);
8✔
266
    String toolWithEdition = getToolWithEdition(this.tool, edition);
5✔
267
    int size = dependencies.size();
3✔
268
    this.context.debug("Tool {} has {} other tool(s) as dependency", toolWithEdition, size);
15✔
269
    for (ToolDependency dependency : dependencies) {
10✔
270
      this.context.trace("Ensuring dependency {} for tool {}", dependency.tool(), toolWithEdition);
15✔
271
      LocalToolCommandlet dependencyTool = this.context.getCommandletManager().getRequiredLocalToolCommandlet(dependency.tool());
7✔
272
      dependencyTool.installAsDependency(dependency.versionRange(), environmentContext);
6✔
273
    }
1✔
274
  }
1✔
275

276
  /**
277
   * Post-extraction hook that can be overridden to add custom processing after unpacking and before moving to the final destination folder.
278
   *
279
   * @param extractedDir the {@link Path} to the folder with the unpacked tool.
280
   */
281
  protected void postExtract(Path extractedDir) {
282

283
  }
1✔
284

285
  @Override
286
  public VersionIdentifier getInstalledVersion() {
287

288
    return getInstalledVersion(this.context.getSoftwarePath().resolve(getName()));
9✔
289
  }
290

291
  /**
292
   * @param toolPath the installation {@link Path} where to find the version file.
293
   * @return the currently installed {@link VersionIdentifier version} of this tool or {@code null} if not installed.
294
   */
295
  protected VersionIdentifier getInstalledVersion(Path toolPath) {
296

297
    if (!Files.isDirectory(toolPath)) {
5✔
298
      this.context.debug("Tool {} not installed in {}", getName(), toolPath);
15✔
299
      return null;
2✔
300
    }
301
    Path toolVersionFile = toolPath.resolve(IdeContext.FILE_SOFTWARE_VERSION);
4✔
302
    if (!Files.exists(toolVersionFile)) {
5✔
303
      Path legacyToolVersionFile = toolPath.resolve(IdeContext.FILE_LEGACY_SOFTWARE_VERSION);
4✔
304
      if (Files.exists(legacyToolVersionFile)) {
5✔
305
        toolVersionFile = legacyToolVersionFile;
3✔
306
      } else {
307
        this.context.warning("Tool {} is missing version file in {}", getName(), toolVersionFile);
15✔
308
        return null;
2✔
309
      }
310
    }
311
    String version = this.context.getFileAccess().readFileContent(toolVersionFile).trim();
7✔
312
    return VersionIdentifier.of(version);
3✔
313
  }
314

315
  @Override
316
  public String getInstalledEdition() {
317

318
    return getInstalledEdition(this.context.getSoftwarePath().resolve(this.tool));
9✔
319
  }
320

321
  /**
322
   * @param toolPath the installation {@link Path} where to find currently installed tool. The name of the parent directory of the real path corresponding
323
   *     to the passed {@link Path path} must be the name of the edition.
324
   * @return the installed edition of this tool or {@code null} if not installed.
325
   */
326
  private String getInstalledEdition(Path toolPath) {
327

328
    if (!Files.isDirectory(toolPath)) {
5✔
329
      this.context.debug("Tool {} not installed in {}", this.tool, toolPath);
15✔
330
      return null;
2✔
331
    }
332
    Path realPath = this.context.getFileAccess().toRealPath(toolPath);
6✔
333
    // if the realPath changed, a link has been resolved
334
    if (realPath.equals(toolPath)) {
4✔
335
      if (!isIgnoreSoftwareRepo()) {
3!
336
        this.context.warning("Tool {} is not installed via software repository (maybe from devonfw-ide). Please consider reinstalling it.", this.tool);
11✔
337
      }
338
      // 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
339
      return getConfiguredEdition();
3✔
340
    }
341
    Path toolRepoFolder = context.getSoftwareRepositoryPath().resolve(ToolRepository.ID_DEFAULT).resolve(this.tool);
9✔
342
    String edition = getEdition(toolRepoFolder, realPath);
5✔
343
    if (!getToolRepository().getSortedEditions(this.tool).contains(edition)) {
8✔
344
      this.context.warning("Undefined edition {} of tool {}", edition, this.tool);
15✔
345
    }
346
    return edition;
2✔
347
  }
348

349
  private String getEdition(Path toolRepoFolder, Path toolInstallFolder) {
350

351
    int toolRepoNameCount = toolRepoFolder.getNameCount();
3✔
352
    int toolInstallNameCount = toolInstallFolder.getNameCount();
3✔
353
    if (toolRepoNameCount < toolInstallNameCount) {
3!
354
      // ensure toolInstallFolder starts with $IDE_ROOT/_ide/software/default/«tool»
355
      for (int i = 0; i < toolRepoNameCount; i++) {
7✔
356
        if (!toolRepoFolder.getName(i).toString().equals(toolInstallFolder.getName(i).toString())) {
10!
357
          return null;
×
358
        }
359
      }
360
      return toolInstallFolder.getName(toolRepoNameCount).toString();
5✔
361
    }
362
    return null;
×
363
  }
364

365
  @Override
366
  public void uninstall() {
367

368
    try {
369
      Path softwarePath = getToolPath();
3✔
370
      if (Files.exists(softwarePath)) {
5!
371
        try {
372
          this.context.getFileAccess().delete(softwarePath);
5✔
373
          this.context.success("Successfully uninstalled " + this.tool);
6✔
374
        } catch (Exception e) {
×
375
          this.context.error("Couldn't uninstall " + this.tool);
×
376
        }
1✔
377
      } else {
378
        this.context.warning("An installed version of " + this.tool + " does not exist");
×
379
      }
380
    } catch (Exception e) {
×
381
      this.context.error(e.getMessage());
×
382
    }
1✔
383
  }
1✔
384

385
  private ToolInstallation createToolInstallation(Path rootDir, VersionIdentifier resolvedVersion, Path toolVersionFile,
386
      boolean newInstallation, EnvironmentContext environmentContext, boolean extraInstallation) {
387

388
    Path linkDir = getMacOsHelper().findLinkDir(rootDir, getBinaryName());
7✔
389
    Path binDir = linkDir;
2✔
390
    Path binFolder = binDir.resolve(IdeContext.FOLDER_BIN);
4✔
391
    if (Files.isDirectory(binFolder)) {
5✔
392
      binDir = binFolder;
2✔
393
    }
394
    if (linkDir != rootDir) {
3✔
395
      assert (!linkDir.equals(rootDir));
5!
396
      this.context.getFileAccess().copy(toolVersionFile, linkDir, FileCopyMode.COPY_FILE_OVERRIDE);
7✔
397
    }
398
    ToolInstallation toolInstallation = new ToolInstallation(rootDir, linkDir, binDir, resolvedVersion, newInstallation);
9✔
399
    setEnvironment(environmentContext, toolInstallation, extraInstallation);
5✔
400
    return toolInstallation;
2✔
401
  }
402

403
  /**
404
   * Method to set environment variables for the process context.
405
   *
406
   * @param environmentContext the {@link EnvironmentContext} where to {@link EnvironmentContext#withEnvVar(String, String) set environment variables} for
407
   *     this tool.
408
   * @param toolInstallation the {@link ToolInstallation}.
409
   * @param extraInstallation {@code true} if the {@link ToolInstallation} is an additional installation to the
410
   *     {@link #getConfiguredVersion() configured version} due to a conflicting version of a {@link ToolDependency}, {@code false} otherwise.
411
   */
412
  protected void setEnvironment(EnvironmentContext environmentContext, ToolInstallation toolInstallation, boolean extraInstallation) {
413

414
    String pathVariable = this.tool.toUpperCase(Locale.ROOT) + "_HOME";
6✔
415
    environmentContext.withEnvVar(pathVariable, toolInstallation.linkDir().toString());
7✔
416
    if (extraInstallation) {
2✔
417
      environmentContext.withPathEntry(toolInstallation.binDir());
5✔
418
    }
419
  }
1✔
420

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