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

devonfw / IDEasy / 28829443960

06 Jul 2026 11:07PM UTC coverage: 71.749% (-0.3%) from 72.066%
28829443960

Pull #1957

github

web-flow
Merge 3e5330d28 into ce85d84c3
Pull Request #1957: #1953: Implement base functionality of Cleanup Commandlet

4876 of 7508 branches covered (64.94%)

Branch coverage included in aggregate %.

12536 of 16760 relevant lines covered (74.8%)

3.17 hits per line

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

72.08
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.Objects;
12
import java.util.Set;
13
import java.util.regex.Matcher;
14
import java.util.regex.Pattern;
15

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

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

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

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

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

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

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

62

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

75
  private final UpgradeMode mode;
76

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

81
  /** Pattern for Maven/Nexus SNAPSHOT versions from downloads . */
82
  // .............................................................................1..........................2.......3.......4..........5
83
  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✔
84

85
  // Group numbers for PATTERN_IDEASY_SNAPSHOT_VERSION
86
  private static final int GROUP_IDEASY_BASE = 1;
87
  private static final int GROUP_IDEASY_MONTH = 2;
88
  private static final int GROUP_IDEASY_DAY = 3;
89
  private static final int GROUP_IDEASY_HOUR = 4;
90

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

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

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

115
    super(context, TOOL_NAME, ARTIFACT, Set.of(Tag.PRODUCTIVITY, Tag.IDE));
8✔
116
    this.mode = mode;
3✔
117
  }
1✔
118

119
  @Override
120
  public VersionIdentifier getInstalledVersion() {
121

122
    return IdeVersion.getVersionIdentifier();
2✔
123
  }
124

125
  @Override
126
  public String getInstalledEdition() {
127

128
    return this.tool;
3✔
129
  }
130

131
  @Override
132
  public String getConfiguredEdition() {
133

134
    return this.tool;
3✔
135
  }
136

137
  @Override
138
  public VersionIdentifier getConfiguredVersion() {
139

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

155
  @Override
156
  public Path getToolPath() {
157

158
    return this.context.getIdeInstallationPath();
4✔
159
  }
160

161
  @Override
162
  protected ToolInstallation doInstall(ToolInstallRequest request) {
163

164
    this.context.requireOnline("upgrade of IDEasy", true);
5✔
165

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

174
  /**
175
   * @return the latest released {@link VersionIdentifier version} of IDEasy.
176
   */
177
  public VersionIdentifier getLatestVersion() {
178

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

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

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

232
    Matcher installedMatcher = PATTERN_IDEASY_SNAPSHOT_VERSION.matcher(installed);
4✔
233
    Matcher latestMatcher = PATTERN_MAVEN_SNAPSHOT_VERSION.matcher(latest);
4✔
234

235
    if (!installedMatcher.matches() || !latestMatcher.matches()) {
6!
236
      return false;
2✔
237
    }
238

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

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

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

258
    return keyInstalled.equals(keyLatest);
4✔
259
  }
260

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

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

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

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

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

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

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

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

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

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

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

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

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

446
    return null;
×
447
  }
448

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

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

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

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

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

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

496
      gitBashProfile.put("guid", newGuid);
5✔
497
      gitBashProfile.put("name", "Git Bash");
5✔
498
      gitBashProfile.put("commandline", bashPath);
5✔
499
      gitBashProfile.put("icon", iconPath);
5✔
500
      gitBashProfile.put("startingDirectory", startingDirectory.toString());
6✔
501

502
      ((ArrayNode) profilesList).add(gitBashProfile);
5✔
503

504
      // Set Git Bash as default profile
505
      root.put("defaultProfile", newGuid);
5✔
506

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

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

530
  static String removeObsoleteEntryFromWindowsPath(String userPath) {
531
    return removeEntryFromWindowsPath(userPath, IDE_BIN);
4✔
532
  }
533

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

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

569
    modifyShellRc(filename, ideRoot, true, extraLine);
6✔
570
  }
1✔
571

572
  private void removeFromShellRc(String filename, Path ideRoot) {
573

574
    modifyShellRc(filename, ideRoot, false, null);
6✔
575
  }
1✔
576

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

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

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

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

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

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

672
  /**
673
   * Uninstalls IDEasy entirely from the system.
674
   */
675
  public void uninstallIdeasy() {
676

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

691
  private void deleteDownloadCache() {
692
    Path downloadPath = this.context.getDownloadPath();
4✔
693
    LOG.info("Deleting download cache from {}", downloadPath);
4✔
694
    tryDeleteDownloadCache(downloadPath);
3✔
695
    // older versions kept the cache under ~/Downloads/ide - clean that up too if it's still around
696
    Path legacy = this.context.getUserHome().resolve("Downloads/ide");
6✔
697
    if (!legacy.equals(downloadPath) && Files.exists(legacy)) {
4!
698
      LOG.info("Deleting legacy download cache from {}", legacy);
×
699
      tryDeleteDownloadCache(legacy);
×
700
    }
701
  }
1✔
702

703
  private void tryDeleteDownloadCache(Path path) {
704
    try {
705
      this.context.getFileAccess().delete(path);
5✔
706
    } catch (IllegalStateException e) {
×
707
      // best effort - on macOS ~/Downloads can deny access (EPERM), don't fail the whole uninstall over it
708
      String cause = (e.getCause() != null) ? e.getCause().getMessage() : e.getMessage();
×
709
      LOG.warn("Could not delete download cache at {} ({}). The folder will be left in place; you can remove it manually via Finder.", path, cause);
×
710
    }
1✔
711
  }
1✔
712

713
  private void uninstallIdeasyIdePath(Path idePath) {
714
    if (this.context.getSystemInfo().isWindows()) {
5✔
715
      Path bash = this.context.findBash();
4✔
716
      if (bash == null) {
2!
717
        LOG.warn("Could not find bash for asynchronous deletion of {}. Falling back to direct deletion.", idePath);
×
718
        this.context.getFileAccess().delete(idePath);
×
719
        return;
×
720
      }
721
      this.context.newProcess().executable(bash).addArgs("-c",
17✔
722
          "sleep 10 && rm -rf \"" + WindowsPathSyntax.MSYS.format(idePath) + "\"").run(ProcessMode.BACKGROUND);
5✔
723
      IdeLogLevel.INTERACTION.log(LOG,
10✔
724
          "To prevent windows file locking errors, we perform an asynchronous deletion of {} in background now.\n"
725
              + "Please close all terminals and wait a minute for the deletion to complete before running other commands.", idePath);
726
    } else {
1✔
727
      LOG.info("Finally deleting {}", idePath);
4✔
728
      this.context.getFileAccess().delete(idePath);
5✔
729
    }
730
  }
1✔
731

732
  private void uninstallIdeasyWindowsEnv(Path ideRoot) {
733
    if (!this.context.getSystemInfo().isWindows()) {
5✔
734
      return;
1✔
735
    }
736
    WindowsHelper helper = WindowsHelper.get(this.context);
4✔
737
    helper.removeUserEnvironmentValue(IdeVariables.IDE_ROOT.getName());
4✔
738
    String userPath = helper.getUserEnvironmentValue(IdeVariables.PATH.getName());
5✔
739
    if (userPath == null) {
2!
740
      LOG.error("Could not read user PATH from registry!");
×
741
    } else {
742
      LOG.info("Found user PATH={}", userPath);
4✔
743
      String newUserPath = userPath;
2✔
744
      if (!userPath.isEmpty()) {
3!
745
        SimpleSystemPath path = SimpleSystemPath.of(userPath, ';');
4✔
746
        path.removeEntries(s -> s.endsWith(IDE_BIN) || s.endsWith(IDE_INSTALLATION_BIN));
15!
747
        newUserPath = path.toString();
3✔
748
      }
749
      if (newUserPath.equals(userPath)) {
4!
750
        LOG.error("Could not find IDEasy in PATH:\n{}", userPath);
×
751
      } else {
752
        helper.setUserEnvironmentValue(IdeVariables.PATH.getName(), newUserPath);
5✔
753
      }
754
    }
755
  }
1✔
756
}
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