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

devonfw / IDEasy / 11912170929

19 Nov 2024 11:33AM UTC coverage: 67.18% (-0.1%) from 67.282%
11912170929

Pull #748

github

web-flow
Merge 06e9b8af7 into d2a37608d
Pull Request #748: #737: Added cd command to shell commandlet

2461 of 4007 branches covered (61.42%)

Branch coverage included in aggregate %.

6400 of 9183 relevant lines covered (69.69%)

3.07 hits per line

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

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

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

117
  }
118

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

127
    if (newlyInstalled) {
2✔
128
      postInstall();
2✔
129
    }
130
  }
1✔
131

132
  /**
133
   * This method is called after the tool has been newly installed or updated to a new version.
134
   */
135
  protected void postInstall() {
136

137
    // nothing to do by default
138
  }
1✔
139

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

149
  /**
150
   * Determines whether this tool should be installed directly in the software folder or in the software repository.
151
   *
152
   * @return {@code true} if the tool should be installed directly in the software folder, ignoring the central software repository; {@code false} if the tool
153
   *     should be installed in the central software repository (default behavior).
154
   */
155
  protected boolean isIgnoreSoftwareRepo() {
156

157
    return false;
2✔
158
  }
159

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

171
    return installTool(version, environmentContext, getConfiguredEdition());
7✔
172
  }
173

174
  /**
175
   * Performs the installation of the {@link #getName() tool} together with the environment context  managed by this
176
   * {@link com.devonfw.tools.ide.commandlet.Commandlet}.
177
   *
178
   * @param version the {@link GenericVersionRange} requested to be installed.
179
   * @param environmentContext the {@link EnvironmentContext} used to
180
   *     {@link #setEnvironment(EnvironmentContext, ToolInstallation, boolean) configure environment variables}.
181
   * @param edition the specific {@link #getConfiguredEdition() edition} to install.
182
   * @return the {@link ToolInstallation} matching the given {@code version}.
183
   */
184
  public ToolInstallation installTool(GenericVersionRange version, EnvironmentContext environmentContext, String edition) {
185

186
    return installTool(version, environmentContext, edition, this.context.getDefaultToolRepository());
9✔
187
  }
188

189
  /**
190
   * Performs the installation of the {@link #getName() tool} managed by this {@link com.devonfw.tools.ide.commandlet.Commandlet}.
191
   *
192
   * @param version the {@link GenericVersionRange} requested to be installed.
193
   * @param environmentContext the {@link EnvironmentContext} used to
194
   *     {@link #setEnvironment(EnvironmentContext, ToolInstallation, boolean) configure environment variables}.
195
   * @param edition the specific {@link #getConfiguredEdition() edition} to install.
196
   * @param toolRepository the {@link ToolRepository} to use.
197
   * @return the {@link ToolInstallation} matching the given {@code version}.
198
   */
199
  public ToolInstallation installTool(GenericVersionRange version, EnvironmentContext environmentContext, String edition, ToolRepository toolRepository) {
200

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

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

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

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

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

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

292
  }
1✔
293

294
  @Override
295
  public VersionIdentifier getInstalledVersion() {
296

297
    return getInstalledVersion(this.context.getSoftwarePath().resolve(getName()));
9✔
298
  }
299

300
  /**
301
   * @param toolPath the installation {@link Path} where to find the version file.
302
   * @return the currently installed {@link VersionIdentifier version} of this tool or {@code null} if not installed.
303
   */
304
  protected VersionIdentifier getInstalledVersion(Path toolPath) {
305

306
    if (!Files.isDirectory(toolPath)) {
5✔
307
      this.context.debug("Tool {} not installed in {}", getName(), toolPath);
15✔
308
      return null;
2✔
309
    }
310
    Path toolVersionFile = toolPath.resolve(IdeContext.FILE_SOFTWARE_VERSION);
4✔
311
    if (!Files.exists(toolVersionFile)) {
5✔
312
      Path legacyToolVersionFile = toolPath.resolve(IdeContext.FILE_LEGACY_SOFTWARE_VERSION);
4✔
313
      if (Files.exists(legacyToolVersionFile)) {
5✔
314
        toolVersionFile = legacyToolVersionFile;
3✔
315
      } else {
316
        this.context.warning("Tool {} is missing version file in {}", getName(), toolVersionFile);
15✔
317
        return null;
2✔
318
      }
319
    }
320
    this.context.trace("Reading tool version from {}", toolVersionFile);
10✔
321
    try {
322
      String version = Files.readString(toolVersionFile).trim();
4✔
323
      this.context.trace("Read tool version {} from {}", version, toolVersionFile);
14✔
324
      return VersionIdentifier.of(version);
3✔
325
    } catch (IOException e) {
×
326
      throw new IllegalStateException("Failed to read file " + toolVersionFile, e);
×
327
    }
328
  }
329

330
  @Override
331
  public String getInstalledEdition() {
332

333
    return getInstalledEdition(this.context.getSoftwarePath().resolve(getName()));
9✔
334
  }
335

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

343
    if (!Files.isDirectory(toolPath)) {
5✔
344
      this.context.debug("Tool {} not installed in {}", getName(), toolPath);
15✔
345
      return null;
2✔
346
    }
347
    try {
348
      String edition = toolPath.toRealPath().getParent().getFileName().toString();
8✔
349
      if (!this.context.getUrls().getSortedEditions(getName()).contains(edition)) {
9!
350
        edition = getConfiguredEdition();
3✔
351
      }
352
      return edition;
2✔
353
    } catch (IOException e) {
×
354
      throw new IllegalStateException(
×
355
          "Couldn't determine the edition of " + getName() + " from the directory structure of its software path "
×
356
              + toolPath
357
              + ", assuming the name of the parent directory of the real path of the software path to be the edition "
358
              + "of the tool.", e);
359
    }
360
  }
361

362
  @Override
363
  public void uninstall() {
364

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

382
  private ToolInstallation createToolInstallation(Path rootDir, VersionIdentifier resolvedVersion, Path toolVersionFile,
383
      boolean newInstallation, EnvironmentContext environmentContext, boolean extraInstallation) {
384

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

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

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

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