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

devonfw / IDEasy / 29107234689

10 Jul 2026 04:23PM UTC coverage: 72.243% (+0.02%) from 72.225%
29107234689

Pull #2037

github

web-flow
Merge accfa9c23 into 365f379a1
Pull Request #2037: #1917: add scripts for gui shortcut launcher windows, linux, macos

4891 of 7476 branches covered (65.42%)

Branch coverage included in aggregate %.

12633 of 16781 relevant lines covered (75.28%)

3.19 hits per line

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

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

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

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

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

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

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

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

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

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

63

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

76
  private final UpgradeMode mode;
77

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

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

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

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

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

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

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

120
  @Override
121
  public VersionIdentifier getInstalledVersion() {
122

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

126
  @Override
127
  public String getInstalledEdition() {
128

129
    return this.tool;
3✔
130
  }
131

132
  @Override
133
  public String getConfiguredEdition() {
134

135
    return this.tool;
3✔
136
  }
137

138
  @Override
139
  public VersionIdentifier getConfiguredVersion() {
140

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

156
  @Override
157
  public Path getToolPath() {
158

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

337
    try {
338
      if (this.context.getSystemInfo().isLinux()) {
5✔
339
        installLinuxDesktopShortcut(installationPath);
4✔
340
      } else if (this.context.getSystemInfo().isMac()) {
5✔
341
        installMacDesktopShortcut(installationPath);
4✔
342
      } else if (this.context.getSystemInfo().isWindows()) {
5!
343
        installWindowsDesktopShortcut(installationPath);
3✔
344
      }
345
    } catch (Exception e) {
×
346
      LOG.warn("Failed to create desktop shortcut.", e);
×
347
    }
1✔
348
  }
1✔
349

350
  private void installLinuxDesktopShortcut(Path installationPath) throws IOException {
351

352
    Path templateFile = installationPath.resolve("gui/linux/ideasy-gui.desktop");
4✔
353
    if (!Files.exists(templateFile)) {
5!
354
      LOG.warn("Desktop file template not found at {}. Skipping desktop shortcut creation.", templateFile);
×
355
      return;
×
356
    }
357
    Path ideasyBin = installationPath.resolve("bin/ideasy");
4✔
358
    Path logoPath = installationPath.resolve("gui/logo.png");
4✔
359
    String content = Files.readString(templateFile)
4✔
360
        .replace("@IDEASY_BIN@", ideasyBin.toString())
4✔
361
        .replace("@IDEASY_ICON@", logoPath.toString());
3✔
362

363
    Path applicationsDir = this.context.getUserHome().resolve(".local/share/applications");
6✔
364
    this.context.getFileAccess().mkdirs(applicationsDir);
5✔
365
    Path desktopFile = applicationsDir.resolve("ideasy-gui.desktop");
4✔
366
    this.context.getFileAccess().writeFileContent(content, desktopFile);
6✔
367
    this.context.getFileAccess().makeExecutable(desktopFile);
5✔
368

369
    // without this, the new entry is only visible in application menus after the next login
370
    try {
371
      this.context.newProcess().executable("update-desktop-database").addArg(applicationsDir.toString())
9✔
372
          .run(ProcessMode.DEFAULT_CAPTURE);
×
373
    } catch (Exception e) {
1✔
374
      LOG.debug("update-desktop-database failed (optional): {}", e.getMessage());
5✔
375
    }
×
376

377
    // Mark as trusted for GNOME 3.28+ so the shortcut is executable without prompting
378
    try {
379
      this.context.newProcess().executable("gio")
14✔
380
          .addArgs("set", desktopFile.toString(), "metadata::trusted", "true")
12✔
381
          .run(ProcessMode.DEFAULT_CAPTURE);
×
382
    } catch (Exception e) {
1✔
383
      LOG.debug("gio set trusted failed (optional): {}", e.getMessage());
5✔
384
    }
×
385

386
    IdeLogLevel.SUCCESS.log(LOG, "Created desktop shortcut at {}", desktopFile);
10✔
387
  }
1✔
388

389
  private void installMacDesktopShortcut(Path installationPath) {
390

391
    Path ideasyBin = installationPath.resolve("bin/ideasy");
4✔
392
    String escapedBin = ideasyBin.toString().replace("\"", "\\\"");
6✔
393
    String content = "#!/bin/bash\n\"" + escapedBin + "\" gui\n";
3✔
394
    Path applicationsDir = this.context.getUserHome().resolve("Applications");
6✔
395
    this.context.getFileAccess().mkdirs(applicationsDir);
5✔
396
    Path commandFile = applicationsDir.resolve("IDEasy GUI.command");
4✔
397
    this.context.getFileAccess().writeFileContent(content, commandFile);
6✔
398
    this.context.getFileAccess().makeExecutable(commandFile);
5✔
399
    IdeLogLevel.SUCCESS.log(LOG, "Created macOS launcher at {}", commandFile);
10✔
400
  }
1✔
401

402
  private void installWindowsDesktopShortcut(Path installationPath) {
403

404
    Path ideasyExe = installationPath.resolve("bin\\ideasy.exe");
4✔
405
    Path icoPath = installationPath.resolve("gui\\logo.ico");
4✔
406
    // Shell Folders contains the already-expanded Desktop path, including OneDrive-redirected locations
407
    WindowsHelper helper = WindowsHelper.get(this.context);
4✔
408
    String desktopStr = helper.getRegistryValue(
5✔
409
        "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders", "Desktop");
410
    Path desktopPath = (desktopStr != null && !desktopStr.isBlank()) ? Path.of(desktopStr) : this.context.getUserHome().resolve("Desktop");
8!
411
    this.context.getFileAccess().mkdirs(desktopPath);
5✔
412
    createWindowsShortcut(desktopPath.resolve("IDEasy GUI.lnk"), ideasyExe, icoPath);
7✔
413
    String startMenuStr = helper.getRegistryValue(
5✔
414
        "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders", "Programs");
415
    Path startMenu = (startMenuStr != null && !startMenuStr.isBlank()) ? Path.of(startMenuStr)
2!
416
        : this.context.getUserHome().resolve("AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs");
6✔
417
    if (Files.isDirectory(startMenu)) {
5!
418
      createWindowsShortcut(startMenu.resolve("IDEasy GUI.lnk"), ideasyExe, icoPath);
×
419
    }
420
  }
1✔
421

422
  private static String psEscapePath(Path path) {
423
    return path.toString().replace("'", "''");
6✔
424
  }
425

426
  private void createWindowsShortcut(Path lnkPath, Path targetExe, Path icoPath) {
427

428
    String ps = "$ws = New-Object -ComObject WScript.Shell; "
1✔
429
        + "$s = $ws.CreateShortcut('" + psEscapePath(lnkPath) + "'); "
2✔
430
        + "$s.TargetPath = '" + psEscapePath(targetExe) + "'; "
2✔
431
        + "$s.Arguments = 'gui'; "
432
        + "$s.IconLocation = '" + psEscapePath(icoPath) + ",0'; "
3✔
433
        + "$s.Save()";
434
    try {
435
      this.context.newProcess().executable("powershell").addArgs("-Command", ps)
17✔
436
          .run(ProcessMode.DEFAULT_CAPTURE);
×
437
      IdeLogLevel.SUCCESS.log(LOG, "Created shortcut at {}", lnkPath);
×
438
    } catch (Exception e) {
1✔
439
      LOG.warn("Failed to create shortcut at {}.", lnkPath, e);
5✔
440
    }
×
441
  }
1✔
442

443
  private void setGitLongpaths() {
444
    this.context.getGitContext().findGitRequired();
5✔
445
    Path configPath = this.context.getUserHome().resolve(".gitconfig");
6✔
446
    FileAccess fileAccess = this.context.getFileAccess();
4✔
447
    IniFile iniFile = fileAccess.readIniFile(configPath);
4✔
448
    IniSection coreSection = iniFile.getOrCreateSection("core");
4✔
449
    coreSection.setProperty("longpaths", "true");
4✔
450
    fileAccess.writeIniFile(iniFile, configPath);
4✔
451
  }
1✔
452

453
  /**
454
   * Sets up Windows Terminal with Git Bash integration.
455
   */
456
  public void setupWindowsTerminal() {
457
    if (!this.context.getSystemInfo().isWindows()) {
×
458
      return;
×
459
    }
460
    if (!isWindowsTerminalInstalled()) {
×
461
      try {
462
        installWindowsTerminal();
×
463
      } catch (Exception e) {
×
464
        LOG.error("Failed to install Windows Terminal!", e);
×
465
      }
×
466
    }
467
    configureWindowsTerminalGitBash();
×
468
  }
×
469

470
  /**
471
   * Checks if Windows Terminal is installed.
472
   *
473
   * @return {@code true} if Windows Terminal is installed, {@code false} otherwise.
474
   */
475
  private boolean isWindowsTerminalInstalled() {
476
    try {
477
      ProcessResult result = this.context.newProcess()
×
478
          .executable("powershell")
×
479
          .addArgs("-Command", "Get-AppxPackage -Name Microsoft.WindowsTerminal")
×
480
          .run(ProcessMode.DEFAULT_CAPTURE);
×
481
      return result.isSuccessful() && !result.getOut().isEmpty();
×
482
    } catch (Exception e) {
×
483
      LOG.debug("Failed to check Windows Terminal installation.", e);
×
484
      return false;
×
485
    }
486
  }
487

488
  /**
489
   * Installs Windows Terminal using winget.
490
   */
491
  private void installWindowsTerminal() {
492
    try {
493
      LOG.info("Installing Windows Terminal...");
×
494
      ProcessResult result = this.context.newProcess()
×
495
          .executable("winget")
×
496
          .addArgs("install", "Microsoft.WindowsTerminal")
×
497
          .run(ProcessMode.DEFAULT);
×
498
      if (result.isSuccessful()) {
×
499
        IdeLogLevel.SUCCESS.log(LOG, "Windows Terminal has been installed successfully.");
×
500
      } else {
501
        LOG.warn("Failed to install Windows Terminal. Please install it manually from Microsoft Store.");
×
502
      }
503
    } catch (Exception e) {
×
504
      LOG.warn("Failed to install Windows Terminal: {}. Please install it manually from Microsoft Store.", e.toString());
×
505
    }
×
506
  }
×
507

508
  /**
509
   * Configures Git Bash integration in Windows Terminal.
510
   */
511
  protected void configureWindowsTerminalGitBash() {
512
    Path settingsPath = getWindowsTerminalSettingsPath();
3✔
513
    if (settingsPath == null || !Files.exists(settingsPath)) {
7!
514
      LOG.warn("Windows Terminal settings file not found. Cannot configure Git Bash integration.");
×
515
      return;
×
516
    }
517

518
    try {
519
      Path bashPath = this.context.findBash();
4✔
520
      if (bashPath == null) {
2!
521
        LOG.warn("Git Bash not found. Cannot configure Windows Terminal integration.");
×
522
        return;
×
523
      }
524

525
      configureGitBashProfile(settingsPath, bashPath.toString());
5✔
526
      IdeLogLevel.SUCCESS.log(LOG, "Git Bash has been configured in Windows Terminal.");
4✔
527
    } catch (Exception e) {
×
528
      LOG.warn("Failed to configure Git Bash in Windows Terminal: {}", e.getMessage());
×
529
    }
1✔
530
  }
1✔
531

532
  /**
533
   * Gets the Windows Terminal settings file path.
534
   *
535
   * @return the {@link Path} to the Windows Terminal settings file, or {@code null} if not found.
536
   */
537
  protected Path getWindowsTerminalSettingsPath() {
538
    Path localAppData = this.context.getUserHome().resolve("AppData").resolve("Local");
8✔
539
    Path packagesPath = localAppData.resolve("Packages");
4✔
540

541
    // Try the new Windows Terminal package first
542
    Path newTerminalPath = packagesPath.resolve("Microsoft.WindowsTerminal_8wekyb3d8bbwe")
4✔
543
        .resolve("LocalState").resolve("settings.json");
4✔
544
    if (Files.exists(newTerminalPath)) {
5!
545
      return newTerminalPath;
2✔
546
    }
547

548
    // Try the old Windows Terminal Preview package
549
    Path previewPath = packagesPath.resolve("Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe")
×
550
        .resolve("LocalState").resolve("settings.json");
×
551
    if (Files.exists(previewPath)) {
×
552
      return previewPath;
×
553
    }
554

555
    return null;
×
556
  }
557

558
  /**
559
   * Configures Git Bash profile in Windows Terminal settings.
560
   *
561
   * @param settingsPath the {@link Path} to the Windows Terminal settings file.
562
   * @param bashPath the path to the Git Bash executable.
563
   */
564
  private void configureGitBashProfile(Path settingsPath, String bashPath) throws Exception {
565

566
    ObjectMapper mapper = new ObjectMapper();
4✔
567
    ObjectNode root;
568
    try (Reader reader = Files.newBufferedReader(settingsPath)) {
3✔
569
      JsonNode rootNode = mapper.readTree(reader);
4✔
570
      root = (ObjectNode) rootNode;
3✔
571
    }
572

573
    // Get or create profiles object
574
    ObjectNode profiles = (ObjectNode) root.get("profiles");
5✔
575
    if (profiles == null) {
2!
576
      profiles = mapper.createObjectNode();
×
577
      root.set("profiles", profiles);
×
578
    }
579

580
    // Get or create list array of profiles object
581
    JsonNode profilesList = profiles.get("list");
4✔
582
    if (profilesList == null || !profilesList.isArray()) {
5!
583
      profilesList = mapper.createArrayNode();
×
584
      profiles.set("list", profilesList);
×
585
    }
586

587
    // Check if Git Bash profile already exists
588
    boolean gitBashProfileExists = false;
2✔
589
    for (JsonNode profile : profilesList) {
10✔
590
      if (profile.has("name") && profile.get("name").asText().equals("Git Bash")) {
11!
591
        gitBashProfileExists = true;
×
592
        break;
×
593
      }
594
    }
1✔
595

596
    // Add Git Bash profile if it doesn't exist
597
    if (gitBashProfileExists) {
2!
598
      LOG.info("Git Bash profile already exists in {}.", settingsPath);
×
599
    } else {
600
      ObjectNode gitBashProfile = mapper.createObjectNode();
3✔
601
      String newGuid = "{2ece5bfe-50ed-5f3a-ab87-5cd4baafed2b}";
2✔
602
      String iconPath = getGitBashIconPath(bashPath);
4✔
603
      Path startingDirectory = Objects.requireNonNullElse(this.context.getIdeRoot(), this.context.getUserHome());
9✔
604

605
      gitBashProfile.put("guid", newGuid);
5✔
606
      gitBashProfile.put("name", "Git Bash");
5✔
607
      gitBashProfile.put("commandline", bashPath);
5✔
608
      gitBashProfile.put("icon", iconPath);
5✔
609
      gitBashProfile.put("startingDirectory", startingDirectory.toString());
6✔
610

611
      ((ArrayNode) profilesList).add(gitBashProfile);
5✔
612

613
      // Set Git Bash as default profile
614
      root.put("defaultProfile", newGuid);
5✔
615

616
      // Write back to file
617
      try (Writer writer = Files.newBufferedWriter(settingsPath)) {
5✔
618
        mapper.writerWithDefaultPrettyPrinter().writeValue(writer, root);
5✔
619
      }
620
    }
621
  }
1✔
622

623
  private String getGitBashIconPath(String bashPathString) {
624
    Path bashPath = Path.of(bashPathString);
5✔
625
    // "C:\\Program Files\\Git\\bin\\bash.exe"
626
    // "C:\\Program Files\\Git\\mingw64\\share\\git\\git-for-windows.ico"
627
    Path parent = bashPath.getParent();
3✔
628
    if (parent != null) {
2!
629
      Path iconPath = parent.resolve("mingw64/share/git/git-for-windows.ico");
4✔
630
      if (Files.exists(iconPath)) {
5!
631
        LOG.debug("Found git-bash icon at {}", iconPath);
×
632
        return iconPath.toString();
×
633
      }
634
      LOG.debug("Git Bash icon not found at {}. Using default icon.", iconPath);
4✔
635
    }
636
    return "ms-appx:///ProfileIcons/{0caa0dad-35be-5f56-a8ff-afceeeaa6101}.png";
2✔
637
  }
638

639
  static String removeObsoleteEntryFromWindowsPath(String userPath) {
640
    return removeEntryFromWindowsPath(userPath, IDE_BIN);
4✔
641
  }
642

643
  static String removeEntryFromWindowsPath(String userPath, String suffix) {
644
    int len = userPath.length();
3✔
645
    int start = 0;
2✔
646
    while ((start >= 0) && (start < len)) {
5!
647
      int end = userPath.indexOf(';', start);
5✔
648
      if (end < 0) {
2✔
649
        end = len;
2✔
650
      }
651
      String entry = userPath.substring(start, end);
5✔
652
      if (entry.endsWith(suffix)) {
4✔
653
        String prefix = "";
2✔
654
        int offset = 1;
2✔
655
        if (start > 0) {
2✔
656
          prefix = userPath.substring(0, start - 1);
7✔
657
          offset = 0;
2✔
658
        }
659
        if (end == len) {
3✔
660
          return prefix;
2✔
661
        } else {
662
          return removeEntryFromWindowsPath(prefix + userPath.substring(end + offset), suffix);
10✔
663
        }
664
      }
665
      start = end + 1;
4✔
666
    }
1✔
667
    return userPath;
2✔
668
  }
669

670
  /**
671
   * Adds ourselves to the shell RC (run-commands) configuration file.
672
   *
673
   * @param filename the name of the RC file.
674
   * @param ideRoot the IDE_ROOT {@link Path}.
675
   */
676
  private void addToShellRc(String filename, Path ideRoot, String extraLine) {
677

678
    modifyShellRc(filename, ideRoot, true, extraLine);
6✔
679
  }
1✔
680

681
  private void removeFromShellRc(String filename, Path ideRoot) {
682

683
    modifyShellRc(filename, ideRoot, false, null);
6✔
684
  }
1✔
685

686
  /**
687
   * Adds ourselves to the shell RC (run-commands) configuration file.
688
   *
689
   * @param filename the name of the RC file.
690
   * @param ideRoot the IDE_ROOT {@link Path}.
691
   */
692
  private void modifyShellRc(String filename, Path ideRoot, boolean add, String extraLine) {
693

694
    if (add) {
2✔
695
      LOG.info("Configuring IDEasy in {}", filename);
5✔
696
    } else {
697
      LOG.info("Removing IDEasy from {}", filename);
4✔
698
    }
699
    Path rcFile = this.context.getUserHome().resolve(filename);
6✔
700
    FileAccess fileAccess = this.context.getFileAccess();
4✔
701
    List<String> lines = fileAccess.readFileLines(rcFile);
4✔
702
    if (lines == null) {
2✔
703
      if (!add) {
2!
704
        return;
×
705
      }
706
      lines = new ArrayList<>();
5✔
707
    } else {
708
      // since it is unspecified if the returned List may be immutable we want to get sure
709
      lines = new ArrayList<>(lines);
5✔
710
    }
711
    Iterator<String> iterator = lines.iterator();
3✔
712
    int removeCount = 0;
2✔
713
    while (iterator.hasNext()) {
3✔
714
      String line = iterator.next();
4✔
715
      line = line.trim();
3✔
716
      if (isObsoleteRcLine(line)) {
3✔
717
        LOG.info("Removing obsolete line from {}: {}", filename, line);
5✔
718
        iterator.remove();
2✔
719
        removeCount++;
2✔
720
      } else if (line.equals(extraLine)) {
4✔
721
        extraLine = null;
2✔
722
      }
723
    }
1✔
724
    if (add) {
2✔
725
      if (extraLine != null) {
2!
726
        lines.add(extraLine);
×
727
      }
728
      if (!this.context.getSystemInfo().isWindows()) {
5✔
729
        lines.add("export IDE_ROOT=\"" + WindowsPathSyntax.MSYS.format(ideRoot) + "\"");
7✔
730
      }
731
      lines.add(BASH_CODE_SOURCE_FUNCTIONS);
4✔
732
    }
733
    fileAccess.writeFileLines(lines, rcFile);
4✔
734
    LOG.debug("Successfully updated {}", filename);
4✔
735
  }
1✔
736

737
  private static boolean isObsoleteRcLine(String line) {
738
    if (line.startsWith("alias ide=")) {
4!
739
      return true;
×
740
    } else if (line.startsWith("export IDE_ROOT=")) {
4!
741
      return true;
×
742
    } else if (line.equals("ide")) {
4✔
743
      return true;
2✔
744
    } else if (line.equals("ide init")) {
4✔
745
      return true;
2✔
746
    } else if (line.startsWith("source \"$IDE_ROOT/_ide/")) {
4✔
747
      return true;
2✔
748
    }
749
    return false;
2✔
750
  }
751

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

754
    Path artifactPath = cwd.resolve(artifactName);
4✔
755
    if (Files.exists(artifactPath)) {
5!
756
      installationArtifacts.add(artifactPath);
5✔
757
    } else if (required) {
×
758
      LOG.error("Missing required file {}", artifactName);
×
759
      return false;
×
760
    }
761
    return true;
2✔
762
  }
763

764
  private Path determineIdeRoot(Path cwd) {
765
    Path ideRoot = this.context.getIdeRoot();
4✔
766
    if (ideRoot == null) {
2!
767
      Path home = this.context.getUserHome();
4✔
768
      Path installRoot = home;
2✔
769
      if (this.context.getSystemInfo().isWindows()) {
5✔
770
        if (!cwd.startsWith(home)) {
4!
771
          installRoot = cwd.getRoot();
×
772
        }
773
      }
774
      ideRoot = installRoot.resolve(IdeContext.FOLDER_PROJECTS);
4✔
775
    } else {
1✔
776
      assert (Files.isDirectory(ideRoot)) : "IDE_ROOT directory does not exist!";
×
777
    }
778
    return ideRoot;
2✔
779
  }
780

781
  /**
782
   * Uninstalls IDEasy entirely from the system.
783
   */
784
  public void uninstallIdeasy() {
785

786
    Path ideRoot = this.context.getIdeRoot();
4✔
787
    removeFromShellRc(BASHRC, ideRoot);
4✔
788
    removeFromShellRc(ZSHRC, ideRoot);
4✔
789
    Path idePath = this.context.getIdePath();
4✔
790
    uninstallIdeasyWindowsEnv(ideRoot);
3✔
791
    uninstallIdeasyIdePath(idePath);
3✔
792
    deleteDownloadCache();
2✔
793
    IdeLogLevel.SUCCESS.log(LOG, "IDEasy has been uninstalled from your system.");
4✔
794
    IdeLogLevel.INTERACTION.log(LOG, "ATTENTION:\n"
10✔
795
        + "In order to prevent data-loss, we do not delete your projects and git repositories!\n"
796
        + "To entirely get rid of IDEasy, also check your IDE_ROOT folder at:\n"
797
        + "{}", ideRoot);
798
  }
1✔
799

800
  private void deleteDownloadCache() {
801
    Path downloadPath = this.context.getDownloadPath();
4✔
802
    LOG.info("Deleting download cache from {}", downloadPath);
4✔
803
    tryDeleteDownloadCache(downloadPath);
3✔
804
    // older versions kept the cache under ~/Downloads/ide - clean that up too if it's still around
805
    Path legacy = this.context.getUserHome().resolve("Downloads/ide");
6✔
806
    if (!legacy.equals(downloadPath) && Files.exists(legacy)) {
4!
807
      LOG.info("Deleting legacy download cache from {}", legacy);
×
808
      tryDeleteDownloadCache(legacy);
×
809
    }
810
  }
1✔
811

812
  private void tryDeleteDownloadCache(Path path) {
813
    try {
814
      this.context.getFileAccess().delete(path);
5✔
815
    } catch (IllegalStateException e) {
×
816
      // best effort - on macOS ~/Downloads can deny access (EPERM), don't fail the whole uninstall over it
817
      String cause = (e.getCause() != null) ? e.getCause().getMessage() : e.getMessage();
×
818
      LOG.warn("Could not delete download cache at {} ({}). The folder will be left in place; you can remove it manually via Finder.", path, cause);
×
819
    }
1✔
820
  }
1✔
821

822
  private void uninstallIdeasyIdePath(Path idePath) {
823
    if (this.context.getSystemInfo().isWindows()) {
5✔
824
      Path bash = this.context.findBash();
4✔
825
      if (bash == null) {
2!
826
        LOG.warn("Could not find bash for asynchronous deletion of {}. Falling back to direct deletion.", idePath);
×
827
        this.context.getFileAccess().delete(idePath);
×
828
        return;
×
829
      }
830
      this.context.newProcess().executable(bash).addArgs("-c",
17✔
831
          "sleep 10 && rm -rf \"" + WindowsPathSyntax.MSYS.format(idePath) + "\"").run(ProcessMode.BACKGROUND);
5✔
832
      IdeLogLevel.INTERACTION.log(LOG,
10✔
833
          "To prevent windows file locking errors, we perform an asynchronous deletion of {} in background now.\n"
834
              + "Please close all terminals and wait a minute for the deletion to complete before running other commands.", idePath);
835
    } else {
1✔
836
      LOG.info("Finally deleting {}", idePath);
4✔
837
      this.context.getFileAccess().delete(idePath);
5✔
838
    }
839
  }
1✔
840

841
  private void uninstallIdeasyWindowsEnv(Path ideRoot) {
842
    if (!this.context.getSystemInfo().isWindows()) {
5✔
843
      return;
1✔
844
    }
845
    WindowsHelper helper = WindowsHelper.get(this.context);
4✔
846
    helper.removeUserEnvironmentValue(IdeVariables.IDE_ROOT.getName());
4✔
847
    String userPath = helper.getUserEnvironmentValue(IdeVariables.PATH.getName());
5✔
848
    if (userPath == null) {
2!
849
      LOG.error("Could not read user PATH from registry!");
×
850
    } else {
851
      LOG.info("Found user PATH={}", userPath);
4✔
852
      String newUserPath = userPath;
2✔
853
      if (!userPath.isEmpty()) {
3!
854
        SimpleSystemPath path = SimpleSystemPath.of(userPath, ';');
4✔
855
        path.removeEntries(s -> s.endsWith(IDE_BIN) || s.endsWith(IDE_INSTALLATION_BIN));
15!
856
        newUserPath = path.toString();
3✔
857
      }
858
      if (newUserPath.equals(userPath)) {
4!
859
        LOG.error("Could not find IDEasy in PATH:\n{}", userPath);
×
860
      } else {
861
        helper.setUserEnvironmentValue(IdeVariables.PATH.getName(), newUserPath);
5✔
862
      }
863
    }
864
  }
1✔
865
}
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