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

devonfw / IDEasy / 26283433836

22 May 2026 10:49AM UTC coverage: 71.121% (+0.006%) from 71.115%
26283433836

Pull #1962

github

web-flow
Merge 98e4c1766 into e59aac534
Pull Request #1962: #1255: Enhance snapshot version recognition in IDEasy

4478 of 6970 branches covered (64.25%)

Branch coverage included in aggregate %.

11567 of 15590 relevant lines covered (74.19%)

3.14 hits per line

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

73.15
cli/src/main/java/com/devonfw/tools/ide/tool/IdeasyCommandlet.java
1
package com.devonfw.tools.ide.tool;
2

3
import java.io.Reader;
4
import java.io.Writer;
5
import java.nio.file.Files;
6
import java.nio.file.Path;
7
import java.util.ArrayList;
8
import java.util.Iterator;
9
import java.util.List;
10
import java.util.Map;
11
import java.util.Set;
12
import java.util.regex.Matcher;
13
import java.util.regex.Pattern;
14

15
import org.slf4j.Logger;
16
import org.slf4j.LoggerFactory;
17

18
import com.devonfw.tools.ide.cli.CliException;
19
import com.devonfw.tools.ide.commandlet.UpgradeMode;
20
import com.devonfw.tools.ide.common.SimpleSystemPath;
21
import com.devonfw.tools.ide.common.Tag;
22
import com.devonfw.tools.ide.context.IdeContext;
23
import com.devonfw.tools.ide.io.FileAccess;
24
import com.devonfw.tools.ide.io.ini.IniFile;
25
import com.devonfw.tools.ide.io.ini.IniSection;
26
import com.devonfw.tools.ide.log.IdeLogLevel;
27
import com.devonfw.tools.ide.os.WindowsHelper;
28
import com.devonfw.tools.ide.os.WindowsPathSyntax;
29
import com.devonfw.tools.ide.process.ProcessMode;
30
import com.devonfw.tools.ide.process.ProcessResult;
31
import com.devonfw.tools.ide.tool.mvn.MvnArtifact;
32
import com.devonfw.tools.ide.tool.mvn.MvnBasedLocalToolCommandlet;
33
import com.devonfw.tools.ide.tool.mvn.MvnRepository;
34
import com.devonfw.tools.ide.variable.IdeVariables;
35
import com.devonfw.tools.ide.version.IdeVersion;
36
import com.devonfw.tools.ide.version.VersionIdentifier;
37
import com.fasterxml.jackson.databind.JsonNode;
38
import com.fasterxml.jackson.databind.ObjectMapper;
39
import com.fasterxml.jackson.databind.node.ArrayNode;
40
import com.fasterxml.jackson.databind.node.ObjectNode;
41

42
/**
43
 * {@link MvnBasedLocalToolCommandlet} for IDEasy (ide-cli).
44
 */
45
public class IdeasyCommandlet extends MvnBasedLocalToolCommandlet {
46

47
  private static final Logger LOG = LoggerFactory.getLogger(IdeasyCommandlet.class);
3✔
48

49
  /** The {@link MvnArtifact} for IDEasy. */
50
  public static final MvnArtifact ARTIFACT = MvnArtifact.ofIdeasyCli("*!", "tar.gz", "${os}-${arch}");
5✔
51

52
  private static final String BASH_CODE_SOURCE_FUNCTIONS = "source \"$IDE_ROOT/_ide/installation/functions\"";
53

54
  /** The {@link #getName() tool name}. */
55
  public static final String TOOL_NAME = "ideasy";
56
  public static final String BASHRC = ".bashrc";
57
  public static final String ZSHRC = ".zshrc";
58
  public static final String IDE_BIN = "\\_ide\\bin";
59
  public static final String IDE_INSTALLATION_BIN = "\\_ide\\installation\\bin";
60

61

62
  private static final Map<String, Boolean> REQUIRED_INSTALLATION_ARTIFACTS = Map.of(
4✔
63
      //artifactName: String, required: boolean
64
      "bin", true,
3✔
65
      "functions", true,
3✔
66
      "internal", true,
3✔
67
      "gui", true,
3✔
68
      "system", true,
3✔
69
      "IDEasy.pdf", true,
3✔
70
      "setup", true,
3✔
71
      "setup.bat", false
1✔
72
  );
73

74
  private final UpgradeMode mode;
75

76
  /** Pattern for IDEasy SNAPSHOT versions built locally. */
77
  private static final Pattern PATTERN_IDEASY_SNAPSHOT_VERSION = Pattern.compile("^(\\d{4}\\.\\d{2}\\.\\d{3})-(\\d{2})_(\\d{2})_(\\d{2}).*-SNAPSHOT$");
3✔
78

79
  /** Pattern for Maven/Nexus SNAPSHOT versions from downloads . */
80
  private static final Pattern PATTERN_MAVEN_SNAPSHOT_VERSION = Pattern.compile("^(\\d{4}\\.\\d{2}\\.\\d{3})-(\\d{4})(\\d{2})(\\d{2})\\.(\\d{2})\\d{4}.*$");
4✔
81

82
  // Group numbers for PATTERN_IDEASY_SNAPSHOT_VERSION
83
  private static final int GROUP_IDEASY_BASE = 1;
84
  private static final int GROUP_IDEASY_MONTH = 2;
85
  private static final int GROUP_IDEASY_DAY = 3;
86
  private static final int GROUP_IDEASY_HOUR = 4;
87

88
  // Group numbers for PATTERN_MAVEN_SNAPSHOT_VERSION
89
  private static final int GROUP_MAVEN_BASE = 1;
90
  private static final int GROUP_MAVEN_YEAR = 2;
91
  private static final int GROUP_MAVEN_MONTH = 3;
92
  private static final int GROUP_MAVEN_DAY = 4;
93
  private static final int GROUP_MAVEN_HOUR = 5;
94

95
  /**
96
   * The constructor.
97
   *
98
   * @param context the {@link IdeContext}.
99
   */
100
  public IdeasyCommandlet(IdeContext context) {
101
    this(context, UpgradeMode.STABLE);
4✔
102
  }
1✔
103

104
  /**
105
   * The constructor.
106
   *
107
   * @param context the {@link IdeContext}.
108
   * @param mode the {@link UpgradeMode}.
109
   */
110
  public IdeasyCommandlet(IdeContext context, UpgradeMode mode) {
111

112
    super(context, TOOL_NAME, ARTIFACT, Set.of(Tag.PRODUCTIVITY, Tag.IDE));
8✔
113
    this.mode = mode;
3✔
114
  }
1✔
115

116
  @Override
117
  public VersionIdentifier getInstalledVersion() {
118

119
    return IdeVersion.getVersionIdentifier();
2✔
120
  }
121

122
  @Override
123
  public String getInstalledEdition() {
124

125
    return this.tool;
3✔
126
  }
127

128
  @Override
129
  public String getConfiguredEdition() {
130

131
    return this.tool;
3✔
132
  }
133

134
  @Override
135
  public VersionIdentifier getConfiguredVersion() {
136

137
    UpgradeMode upgradeMode = this.mode;
3✔
138
    if (upgradeMode == null) {
2!
139
      if (IdeVersion.isSnapshot()) {
2!
140
        upgradeMode = UpgradeMode.SNAPSHOT;
3✔
141
      } else {
142
        if (IdeVersion.getVersionIdentifier().getDevelopmentPhase().isStable()) {
×
143
          upgradeMode = UpgradeMode.STABLE;
×
144
        } else {
145
          upgradeMode = UpgradeMode.UNSTABLE;
×
146
        }
147
      }
148
    }
149
    return upgradeMode.getVersion();
3✔
150
  }
151

152
  @Override
153
  public Path getToolPath() {
154

155
    return this.context.getIdeInstallationPath();
4✔
156
  }
157

158
  @Override
159
  protected ToolInstallation doInstall(ToolInstallRequest request) {
160

161
    this.context.requireOnline("upgrade of IDEasy", true);
5✔
162

163
    if (IdeVersion.isUndefined() && !this.context.isForceMode()) {
6!
164
      VersionIdentifier version = IdeVersion.getVersionIdentifier();
2✔
165
      LOG.warn("You are using IDEasy version {} which indicates local development - skipping upgrade.", version);
4✔
166
      return toolAlreadyInstalled(request);
4✔
167
    }
168
    return super.doInstall(request);
×
169
  }
170

171
  /**
172
   * @return the latest released {@link VersionIdentifier version} of IDEasy.
173
   */
174
  public VersionIdentifier getLatestVersion() {
175

176
    if (!this.context.isForceMode()) {
4!
177
      VersionIdentifier currentVersion = IdeVersion.getVersionIdentifier();
2✔
178
      if (IdeVersion.isUndefined()) {
2!
179
        return currentVersion;
2✔
180
      }
181
    }
182
    VersionIdentifier configuredVersion = getConfiguredVersion();
×
183
    return getToolRepository().resolveVersion(this.tool, getConfiguredEdition(), configuredVersion, this);
×
184
  }
185

186
  /**
187
   * Checks if an update is available and logs according information.
188
   *
189
   * @return {@code true} if an update is available, {@code false} otherwise.
190
   */
191
  public boolean checkIfUpdateIsAvailable() {
192
    VersionIdentifier installedVersion = getInstalledVersion();
3✔
193
    IdeLogLevel.SUCCESS.log(LOG, "Your version of IDEasy is {}.", installedVersion);
10✔
194
    if (IdeVersion.isSnapshot()) {
2!
195
      LOG.warn("You are using a SNAPSHOT version of IDEasy. For stability consider switching to a stable release via 'ide upgrade --mode=stable'");
3✔
196
    }
197
    if (this.context.isOffline()) {
4✔
198
      LOG.warn("Skipping check for newer version of IDEasy because you are offline.");
3✔
199
      return false;
2✔
200
    }
201
    VersionIdentifier latestVersion = getLatestVersion();
3✔
202
    if (IdeVersion.isSnapshot()) {
2!
203
      if (isSameSnapshotVersion(installedVersion.toString(), latestVersion.toString())) {
7✔
204
        IdeLogLevel.SUCCESS.log(LOG, "Your are using the latest snapshot version of IDEasy and no update is available.");
4✔
205
        return false;
2✔
206
      }
207
    } else if (installedVersion.equals(latestVersion)) {
×
208
      IdeLogLevel.SUCCESS.log(LOG, "Your are using the latest stable version of IDEasy and no update is available.");
×
209
      return false;
×
210
    }
211
    IdeLogLevel.INTERACTION.log(LOG,
14✔
212
        "Your version of IDEasy is {} but version {} is available. Please run the following command to upgrade to the latest version:\n"
213
            + "ide upgrade", installedVersion, latestVersion);
214
    return true;
2✔
215
  }
216

217
  /**
218
   * Checks if two snapshot versions represent the version
219
   *
220
   * @param installed the installed version string
221
   * @param latest the latest available version string
222
   * @return {@code true} if both versions represent the same version, {@code false} otherwise.
223
   */
224
  private boolean isSameSnapshotVersion(String installed, String latest) {
225
    if (installed == null || latest == null) {
4!
226
      return false;
×
227
    }
228

229
    Matcher installedMatcher = PATTERN_IDEASY_SNAPSHOT_VERSION.matcher(installed);
4✔
230
    Matcher latestMatcher = PATTERN_MAVEN_SNAPSHOT_VERSION.matcher(latest);
4✔
231

232
    if (!installedMatcher.matches() || !latestMatcher.matches()) {
6!
233
      return false;
2✔
234
    }
235

236
    // Compare base versions
237
    String baseInstalled = installedMatcher.group(GROUP_IDEASY_BASE);
4✔
238
    String baseLatest = latestMatcher.group(GROUP_MAVEN_BASE);
4✔
239
    if (!baseInstalled.equals(baseLatest)) {
4✔
240
      return false;
2✔
241
    }
242

243
    // Compare year
244
    String yearLatest = latestMatcher.group(GROUP_MAVEN_YEAR);
4✔
245
    String baseYear = baseInstalled.split("\\.")[0];
6✔
246
    if (!baseYear.equals(yearLatest)) {
4!
247
      return false;
×
248
    }
249

250
    // Compare MMDD.HH for both versions
251
    String keyInstalled =
2✔
252
        installedMatcher.group(GROUP_IDEASY_MONTH) + installedMatcher.group(GROUP_IDEASY_DAY) + "." + installedMatcher.group(GROUP_IDEASY_HOUR);
9✔
253
    String keyLatest = latestMatcher.group(GROUP_MAVEN_MONTH) + latestMatcher.group(GROUP_MAVEN_DAY) + "." + latestMatcher.group(GROUP_MAVEN_HOUR);
11✔
254

255
    return keyInstalled.equals(keyLatest);
4✔
256
  }
257

258
  /**
259
   * Initial installation of IDEasy.
260
   *
261
   * @param cwd the {@link Path} to the current working directory.
262
   * @see com.devonfw.tools.ide.commandlet.InstallCommandlet
263
   */
264
  public void installIdeasy(Path cwd) {
265
    Path ideRoot = determineIdeRoot(cwd);
4✔
266
    Path idePath = ideRoot.resolve(IdeContext.FOLDER_UNDERSCORE_IDE);
4✔
267
    Path installationPath = idePath.resolve(IdeContext.FOLDER_INSTALLATION);
4✔
268
    Path ideasySoftwarePath = idePath.resolve(IdeContext.FOLDER_SOFTWARE).resolve(MvnRepository.ID).resolve(IdeasyCommandlet.TOOL_NAME)
8✔
269
        .resolve(IdeasyCommandlet.TOOL_NAME);
2✔
270
    Path ideasyVersionPath = ideasySoftwarePath.resolve(IdeVersion.getVersionString());
4✔
271
    FileAccess fileAccess = this.context.getFileAccess();
4✔
272
    if (Files.isDirectory(ideasyVersionPath)) {
5✔
273
      LOG.error("IDEasy is already installed at {} - if your installation is broken, delete it manually and rerun setup!", ideasyVersionPath);
5✔
274
    } else {
275
      List<Path> installationArtifacts = new ArrayList<>();
4✔
276
      for (Map.Entry<String, Boolean> artifactEntry : REQUIRED_INSTALLATION_ARTIFACTS.entrySet()) {
11✔
277
        String artifactName = artifactEntry.getKey();
4✔
278
        boolean required = artifactEntry.getValue();
5✔
279
        boolean success = addInstallationArtifact(cwd, artifactName, required, installationArtifacts);
7✔
280
        if (!success) {
2!
281
          throw new CliException("IDEasy release is inconsistent at %s [artifact=%s]".formatted(cwd, artifactName));
×
282
        }
283
      }
1✔
284

285
      fileAccess.mkdirs(ideasyVersionPath);
3✔
286
      for (Path installationArtifact : installationArtifacts) {
10✔
287
        fileAccess.copy(installationArtifact, ideasyVersionPath);
4✔
288
      }
1✔
289
      this.context.writeVersionFile(IdeVersion.getVersionIdentifier(), ideasyVersionPath);
5✔
290
    }
291
    fileAccess.symlink(ideasyVersionPath, installationPath);
4✔
292
    addToShellRc(BASHRC, ideRoot, null);
5✔
293
    addToShellRc(ZSHRC, ideRoot, "autoload -U +X bashcompinit && bashcompinit");
5✔
294
    installIdeasyWindowsEnv(ideRoot, installationPath);
4✔
295
    IdeLogLevel.SUCCESS.log(LOG, "IDEasy has been installed successfully on your system.");
4✔
296
    LOG.warn("IDEasy has been setup for new shells but it cannot work in your current shell(s).\n"
3✔
297
        + "To use it here, run 'source ~/.bashrc' (or your shell config). Otherwise, open a new terminal or reboot.");
298
  }
1✔
299

300
  private void installIdeasyWindowsEnv(Path ideRoot, Path installationPath) {
301
    if (!this.context.getSystemInfo().isWindows()) {
5✔
302
      return;
1✔
303
    }
304
    WindowsHelper helper = WindowsHelper.get(this.context);
4✔
305
    helper.setUserEnvironmentValue(IdeVariables.IDE_ROOT.getName(), ideRoot.toString());
6✔
306
    String userPath = helper.getUserEnvironmentValue(IdeVariables.PATH.getName());
5✔
307
    if (userPath == null) {
2!
308
      LOG.error("Could not read user PATH from registry!");
×
309
    } else {
310
      LOG.info("Found user PATH={}", userPath);
4✔
311
      Path ideasyBinPath = installationPath.resolve("bin");
4✔
312
      SimpleSystemPath path = SimpleSystemPath.of(userPath, ';');
4✔
313
      if (path.getEntries().isEmpty()) {
4!
314
        LOG.warn("ATTENTION:\n"
×
315
            + "Your user specific PATH variable seems to be empty.\n"
316
            + "You can double check this by pressing [Windows][r] and launch the program SystemPropertiesAdvanced.\n"
317
            + "Then click on 'Environment variables' and check if 'PATH' is set in the 'user variables' from the upper list.\n"
318
            + "In case 'PATH' is defined there non-empty and you get this message, please abort and give us feedback:\n"
319
            + "https://github.com/devonfw/IDEasy/issues\n"
320
            + "Otherwise all is correct and you can continue.");
321
        this.context.askToContinue("Are you sure you want to override your PATH?");
×
322
      } else {
323
        path.removeEntries(s -> s.endsWith(IDE_INSTALLATION_BIN));
7✔
324
      }
325
      path.getEntries().add(ideasyBinPath.toString());
6✔
326
      helper.setUserEnvironmentValue(IdeVariables.PATH.getName(), path.toString());
6✔
327
      setGitLongpaths();
2✔
328
    }
329
  }
1✔
330

331
  private void setGitLongpaths() {
332
    this.context.getGitContext().findGitRequired();
5✔
333
    Path configPath = this.context.getUserHome().resolve(".gitconfig");
6✔
334
    FileAccess fileAccess = this.context.getFileAccess();
4✔
335
    IniFile iniFile = fileAccess.readIniFile(configPath);
4✔
336
    IniSection coreSection = iniFile.getOrCreateSection("core");
4✔
337
    coreSection.setProperty("longpaths", "true");
4✔
338
    fileAccess.writeIniFile(iniFile, configPath);
4✔
339
  }
1✔
340

341
  /**
342
   * Sets up Windows Terminal with Git Bash integration.
343
   */
344
  public void setupWindowsTerminal() {
345
    if (!this.context.getSystemInfo().isWindows()) {
×
346
      return;
×
347
    }
348
    if (!isWindowsTerminalInstalled()) {
×
349
      try {
350
        installWindowsTerminal();
×
351
      } catch (Exception e) {
×
352
        LOG.error("Failed to install Windows Terminal!", e);
×
353
      }
×
354
    }
355
    configureWindowsTerminalGitBash();
×
356
  }
×
357

358
  /**
359
   * Checks if Windows Terminal is installed.
360
   *
361
   * @return {@code true} if Windows Terminal is installed, {@code false} otherwise.
362
   */
363
  private boolean isWindowsTerminalInstalled() {
364
    try {
365
      ProcessResult result = this.context.newProcess()
×
366
          .executable("powershell")
×
367
          .addArgs("-Command", "Get-AppxPackage -Name Microsoft.WindowsTerminal")
×
368
          .run(ProcessMode.DEFAULT_CAPTURE);
×
369
      return result.isSuccessful() && !result.getOut().isEmpty();
×
370
    } catch (Exception e) {
×
371
      LOG.debug("Failed to check Windows Terminal installation.", e);
×
372
      return false;
×
373
    }
374
  }
375

376
  /**
377
   * Installs Windows Terminal using winget.
378
   */
379
  private void installWindowsTerminal() {
380
    try {
381
      LOG.info("Installing Windows Terminal...");
×
382
      ProcessResult result = this.context.newProcess()
×
383
          .executable("winget")
×
384
          .addArgs("install", "Microsoft.WindowsTerminal")
×
385
          .run(ProcessMode.DEFAULT);
×
386
      if (result.isSuccessful()) {
×
387
        IdeLogLevel.SUCCESS.log(LOG, "Windows Terminal has been installed successfully.");
×
388
      } else {
389
        LOG.warn("Failed to install Windows Terminal. Please install it manually from Microsoft Store.");
×
390
      }
391
    } catch (Exception e) {
×
392
      LOG.warn("Failed to install Windows Terminal: {}. Please install it manually from Microsoft Store.", e.toString());
×
393
    }
×
394
  }
×
395

396
  /**
397
   * Configures Git Bash integration in Windows Terminal.
398
   */
399
  protected void configureWindowsTerminalGitBash() {
400
    Path settingsPath = getWindowsTerminalSettingsPath();
3✔
401
    if (settingsPath == null || !Files.exists(settingsPath)) {
7!
402
      LOG.warn("Windows Terminal settings file not found. Cannot configure Git Bash integration.");
×
403
      return;
×
404
    }
405

406
    try {
407
      Path bashPath = this.context.findBash();
4✔
408
      if (bashPath == null) {
2!
409
        LOG.warn("Git Bash not found. Cannot configure Windows Terminal integration.");
×
410
        return;
×
411
      }
412

413
      configureGitBashProfile(settingsPath, bashPath.toString());
5✔
414
      IdeLogLevel.SUCCESS.log(LOG, "Git Bash has been configured in Windows Terminal.");
4✔
415
    } catch (Exception e) {
×
416
      LOG.warn("Failed to configure Git Bash in Windows Terminal: {}", e.getMessage());
×
417
    }
1✔
418
  }
1✔
419

420
  /**
421
   * Gets the Windows Terminal settings file path.
422
   *
423
   * @return the {@link Path} to the Windows Terminal settings file, or {@code null} if not found.
424
   */
425
  protected Path getWindowsTerminalSettingsPath() {
426
    Path localAppData = this.context.getUserHome().resolve("AppData").resolve("Local");
8✔
427
    Path packagesPath = localAppData.resolve("Packages");
4✔
428

429
    // Try the new Windows Terminal package first
430
    Path newTerminalPath = packagesPath.resolve("Microsoft.WindowsTerminal_8wekyb3d8bbwe")
4✔
431
        .resolve("LocalState").resolve("settings.json");
4✔
432
    if (Files.exists(newTerminalPath)) {
5!
433
      return newTerminalPath;
2✔
434
    }
435

436
    // Try the old Windows Terminal Preview package
437
    Path previewPath = packagesPath.resolve("Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe")
×
438
        .resolve("LocalState").resolve("settings.json");
×
439
    if (Files.exists(previewPath)) {
×
440
      return previewPath;
×
441
    }
442

443
    return null;
×
444
  }
445

446
  /**
447
   * Configures Git Bash profile in Windows Terminal settings.
448
   *
449
   * @param settingsPath the {@link Path} to the Windows Terminal settings file.
450
   * @param bashPath the path to the Git Bash executable.
451
   */
452
  private void configureGitBashProfile(Path settingsPath, String bashPath) throws Exception {
453

454
    ObjectMapper mapper = new ObjectMapper();
4✔
455
    ObjectNode root;
456
    try (Reader reader = Files.newBufferedReader(settingsPath)) {
3✔
457
      JsonNode rootNode = mapper.readTree(reader);
4✔
458
      root = (ObjectNode) rootNode;
3✔
459
    }
460

461
    // Get or create profiles object
462
    ObjectNode profiles = (ObjectNode) root.get("profiles");
5✔
463
    if (profiles == null) {
2!
464
      profiles = mapper.createObjectNode();
×
465
      root.set("profiles", profiles);
×
466
    }
467

468
    // Get or create list array of profiles object
469
    JsonNode profilesList = profiles.get("list");
4✔
470
    if (profilesList == null || !profilesList.isArray()) {
5!
471
      profilesList = mapper.createArrayNode();
×
472
      profiles.set("list", profilesList);
×
473
    }
474

475
    // Check if Git Bash profile already exists
476
    boolean gitBashProfileExists = false;
2✔
477
    for (JsonNode profile : profilesList) {
10✔
478
      if (profile.has("name") && profile.get("name").asText().equals("Git Bash")) {
11!
479
        gitBashProfileExists = true;
×
480
        break;
×
481
      }
482
    }
1✔
483

484
    // Add Git Bash profile if it doesn't exist
485
    if (gitBashProfileExists) {
2!
486
      LOG.info("Git Bash profile already exists in {}.", settingsPath);
×
487
    } else {
488
      ObjectNode gitBashProfile = mapper.createObjectNode();
3✔
489
      String newGuid = "{2ece5bfe-50ed-5f3a-ab87-5cd4baafed2b}";
2✔
490
      String iconPath = getGitBashIconPath(bashPath);
4✔
491
      String startingDirectory = this.context.getIdeRoot().toString();
5✔
492

493
      gitBashProfile.put("guid", newGuid);
5✔
494
      gitBashProfile.put("name", "Git Bash");
5✔
495
      gitBashProfile.put("commandline", bashPath);
5✔
496
      gitBashProfile.put("icon", iconPath);
5✔
497
      gitBashProfile.put("startingDirectory", startingDirectory);
5✔
498

499
      ((ArrayNode) profilesList).add(gitBashProfile);
5✔
500

501
      // Set Git Bash as default profile
502
      root.put("defaultProfile", newGuid);
5✔
503

504
      // Write back to file
505
      try (Writer writer = Files.newBufferedWriter(settingsPath)) {
5✔
506
        mapper.writerWithDefaultPrettyPrinter().writeValue(writer, root);
5✔
507
      }
508
    }
509
  }
1✔
510

511
  private String getGitBashIconPath(String bashPathString) {
512
    Path bashPath = Path.of(bashPathString);
5✔
513
    // "C:\\Program Files\\Git\\bin\\bash.exe"
514
    // "C:\\Program Files\\Git\\mingw64\\share\\git\\git-for-windows.ico"
515
    Path parent = bashPath.getParent();
3✔
516
    if (parent != null) {
2!
517
      Path iconPath = parent.resolve("mingw64/share/git/git-for-windows.ico");
4✔
518
      if (Files.exists(iconPath)) {
5!
519
        LOG.debug("Found git-bash icon at {}", iconPath);
×
520
        return iconPath.toString();
×
521
      }
522
      LOG.debug("Git Bash icon not found at {}. Using default icon.", iconPath);
4✔
523
    }
524
    return "ms-appx:///ProfileIcons/{0caa0dad-35be-5f56-a8ff-afceeeaa6101}.png";
2✔
525
  }
526

527
  static String removeObsoleteEntryFromWindowsPath(String userPath) {
528
    return removeEntryFromWindowsPath(userPath, IDE_BIN);
4✔
529
  }
530

531
  static String removeEntryFromWindowsPath(String userPath, String suffix) {
532
    int len = userPath.length();
3✔
533
    int start = 0;
2✔
534
    while ((start >= 0) && (start < len)) {
5!
535
      int end = userPath.indexOf(';', start);
5✔
536
      if (end < 0) {
2✔
537
        end = len;
2✔
538
      }
539
      String entry = userPath.substring(start, end);
5✔
540
      if (entry.endsWith(suffix)) {
4✔
541
        String prefix = "";
2✔
542
        int offset = 1;
2✔
543
        if (start > 0) {
2✔
544
          prefix = userPath.substring(0, start - 1);
7✔
545
          offset = 0;
2✔
546
        }
547
        if (end == len) {
3✔
548
          return prefix;
2✔
549
        } else {
550
          return removeEntryFromWindowsPath(prefix + userPath.substring(end + offset), suffix);
10✔
551
        }
552
      }
553
      start = end + 1;
4✔
554
    }
1✔
555
    return userPath;
2✔
556
  }
557

558
  /**
559
   * Adds ourselves to the shell RC (run-commands) configuration file.
560
   *
561
   * @param filename the name of the RC file.
562
   * @param ideRoot the IDE_ROOT {@link Path}.
563
   */
564
  private void addToShellRc(String filename, Path ideRoot, String extraLine) {
565

566
    modifyShellRc(filename, ideRoot, true, extraLine);
6✔
567
  }
1✔
568

569
  private void removeFromShellRc(String filename, Path ideRoot) {
570

571
    modifyShellRc(filename, ideRoot, false, null);
6✔
572
  }
1✔
573

574
  /**
575
   * Adds ourselves to the shell RC (run-commands) configuration file.
576
   *
577
   * @param filename the name of the RC file.
578
   * @param ideRoot the IDE_ROOT {@link Path}.
579
   */
580
  private void modifyShellRc(String filename, Path ideRoot, boolean add, String extraLine) {
581

582
    if (add) {
2✔
583
      LOG.info("Configuring IDEasy in {}", filename);
5✔
584
    } else {
585
      LOG.info("Removing IDEasy from {}", filename);
4✔
586
    }
587
    Path rcFile = this.context.getUserHome().resolve(filename);
6✔
588
    FileAccess fileAccess = this.context.getFileAccess();
4✔
589
    List<String> lines = fileAccess.readFileLines(rcFile);
4✔
590
    if (lines == null) {
2✔
591
      if (!add) {
2!
592
        return;
×
593
      }
594
      lines = new ArrayList<>();
5✔
595
    } else {
596
      // since it is unspecified if the returned List may be immutable we want to get sure
597
      lines = new ArrayList<>(lines);
5✔
598
    }
599
    Iterator<String> iterator = lines.iterator();
3✔
600
    int removeCount = 0;
2✔
601
    while (iterator.hasNext()) {
3✔
602
      String line = iterator.next();
4✔
603
      line = line.trim();
3✔
604
      if (isObsoleteRcLine(line)) {
3✔
605
        LOG.info("Removing obsolete line from {}: {}", filename, line);
5✔
606
        iterator.remove();
2✔
607
        removeCount++;
2✔
608
      } else if (line.equals(extraLine)) {
4✔
609
        extraLine = null;
2✔
610
      }
611
    }
1✔
612
    if (add) {
2✔
613
      if (extraLine != null) {
2!
614
        lines.add(extraLine);
×
615
      }
616
      if (!this.context.getSystemInfo().isWindows()) {
5✔
617
        lines.add("export IDE_ROOT=\"" + WindowsPathSyntax.MSYS.format(ideRoot) + "\"");
7✔
618
      }
619
      lines.add(BASH_CODE_SOURCE_FUNCTIONS);
4✔
620
    }
621
    fileAccess.writeFileLines(lines, rcFile);
4✔
622
    LOG.debug("Successfully updated {}", filename);
4✔
623
  }
1✔
624

625
  private static boolean isObsoleteRcLine(String line) {
626
    if (line.startsWith("alias ide=")) {
4!
627
      return true;
×
628
    } else if (line.startsWith("export IDE_ROOT=")) {
4!
629
      return true;
×
630
    } else if (line.equals("ide")) {
4✔
631
      return true;
2✔
632
    } else if (line.equals("ide init")) {
4✔
633
      return true;
2✔
634
    } else if (line.startsWith("source \"$IDE_ROOT/_ide/")) {
4✔
635
      return true;
2✔
636
    }
637
    return false;
2✔
638
  }
639

640
  private boolean addInstallationArtifact(Path cwd, String artifactName, boolean required, List<Path> installationArtifacts) {
641

642
    Path artifactPath = cwd.resolve(artifactName);
4✔
643
    if (Files.exists(artifactPath)) {
5!
644
      installationArtifacts.add(artifactPath);
5✔
645
    } else if (required) {
×
646
      LOG.error("Missing required file {}", artifactName);
×
647
      return false;
×
648
    }
649
    return true;
2✔
650
  }
651

652
  private Path determineIdeRoot(Path cwd) {
653
    Path ideRoot = this.context.getIdeRoot();
4✔
654
    if (ideRoot == null) {
2!
655
      Path home = this.context.getUserHome();
4✔
656
      Path installRoot = home;
2✔
657
      if (this.context.getSystemInfo().isWindows()) {
5✔
658
        if (!cwd.startsWith(home)) {
4!
659
          installRoot = cwd.getRoot();
×
660
        }
661
      }
662
      ideRoot = installRoot.resolve(IdeContext.FOLDER_PROJECTS);
4✔
663
    } else {
1✔
664
      assert (Files.isDirectory(ideRoot)) : "IDE_ROOT directory does not exist!";
×
665
    }
666
    return ideRoot;
2✔
667
  }
668

669
  /**
670
   * Uninstalls IDEasy entirely from the system.
671
   */
672
  public void uninstallIdeasy() {
673

674
    Path ideRoot = this.context.getIdeRoot();
4✔
675
    removeFromShellRc(BASHRC, ideRoot);
4✔
676
    removeFromShellRc(ZSHRC, ideRoot);
4✔
677
    Path idePath = this.context.getIdePath();
4✔
678
    uninstallIdeasyWindowsEnv(ideRoot);
3✔
679
    uninstallIdeasyIdePath(idePath);
3✔
680
    deleteDownloadCache();
2✔
681
    IdeLogLevel.SUCCESS.log(LOG, "IDEasy has been uninstalled from your system.");
4✔
682
    IdeLogLevel.INTERACTION.log(LOG, "ATTENTION:\n"
10✔
683
        + "In order to prevent data-loss, we do not delete your projects and git repositories!\n"
684
        + "To entirely get rid of IDEasy, also check your IDE_ROOT folder at:\n"
685
        + "{}", ideRoot);
686
  }
1✔
687

688
  private void deleteDownloadCache() {
689
    Path downloadPath = this.context.getDownloadPath();
4✔
690
    LOG.info("Deleting download cache from {}", downloadPath);
4✔
691
    this.context.getFileAccess().delete(downloadPath);
5✔
692
  }
1✔
693

694
  private void uninstallIdeasyIdePath(Path idePath) {
695
    if (this.context.getSystemInfo().isWindows()) {
5✔
696
      Path bash = this.context.findBash();
4✔
697
      if (bash == null) {
2!
698
        LOG.warn("Could not find bash for asynchronous deletion of {}. Falling back to direct deletion.", idePath);
×
699
        this.context.getFileAccess().delete(idePath);
×
700
        return;
×
701
      }
702
      this.context.newProcess().executable(bash).addArgs("-c",
17✔
703
          "sleep 10 && rm -rf \"" + WindowsPathSyntax.MSYS.format(idePath) + "\"").run(ProcessMode.BACKGROUND);
5✔
704
      IdeLogLevel.INTERACTION.log(LOG,
10✔
705
          "To prevent windows file locking errors, we perform an asynchronous deletion of {} in background now.\n"
706
              + "Please close all terminals and wait a minute for the deletion to complete before running other commands.", idePath);
707
    } else {
1✔
708
      LOG.info("Finally deleting {}", idePath);
4✔
709
      this.context.getFileAccess().delete(idePath);
5✔
710
    }
711
  }
1✔
712

713
  private void uninstallIdeasyWindowsEnv(Path ideRoot) {
714
    if (!this.context.getSystemInfo().isWindows()) {
5✔
715
      return;
1✔
716
    }
717
    WindowsHelper helper = WindowsHelper.get(this.context);
4✔
718
    helper.removeUserEnvironmentValue(IdeVariables.IDE_ROOT.getName());
4✔
719
    String userPath = helper.getUserEnvironmentValue(IdeVariables.PATH.getName());
5✔
720
    if (userPath == null) {
2!
721
      LOG.error("Could not read user PATH from registry!");
×
722
    } else {
723
      LOG.info("Found user PATH={}", userPath);
4✔
724
      String newUserPath = userPath;
2✔
725
      if (!userPath.isEmpty()) {
3!
726
        SimpleSystemPath path = SimpleSystemPath.of(userPath, ';');
4✔
727
        path.removeEntries(s -> s.endsWith(IDE_BIN) || s.endsWith(IDE_INSTALLATION_BIN));
15!
728
        newUserPath = path.toString();
3✔
729
      }
730
      if (newUserPath.equals(userPath)) {
4!
731
        LOG.error("Could not find IDEasy in PATH:\n{}", userPath);
×
732
      } else {
733
        helper.setUserEnvironmentValue(IdeVariables.PATH.getName(), newUserPath);
5✔
734
      }
735
    }
736
  }
1✔
737
}
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