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

devonfw / IDEasy / 15872341858

25 Jun 2025 09:14AM UTC coverage: 67.754% (+0.03%) from 67.727%
15872341858

Pull #1381

github

web-flow
Merge ca90ebf3d into aa2814438
Pull Request #1381: #1346: Fix ide upgrade throwing exception when offline

3185 of 5104 branches covered (62.4%)

Branch coverage included in aggregate %.

8151 of 11627 relevant lines covered (70.1%)

3.07 hits per line

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

82.12
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.nio.file.Files;
5
import java.nio.file.Path;
6
import java.util.ArrayList;
7
import java.util.Iterator;
8
import java.util.LinkedHashMap;
9
import java.util.List;
10
import java.util.Set;
11

12
import com.devonfw.tools.ide.cli.CliException;
13
import com.devonfw.tools.ide.commandlet.UpgradeMode;
14
import com.devonfw.tools.ide.common.SimpleSystemPath;
15
import com.devonfw.tools.ide.common.Tag;
16
import com.devonfw.tools.ide.context.IdeContext;
17
import com.devonfw.tools.ide.git.GitContext;
18
import com.devonfw.tools.ide.git.GitContextImpl;
19
import com.devonfw.tools.ide.io.FileAccess;
20
import com.devonfw.tools.ide.os.WindowsHelper;
21
import com.devonfw.tools.ide.os.WindowsPathSyntax;
22
import com.devonfw.tools.ide.process.ProcessMode;
23
import com.devonfw.tools.ide.tool.mvn.MvnArtifact;
24
import com.devonfw.tools.ide.tool.mvn.MvnBasedLocalToolCommandlet;
25
import com.devonfw.tools.ide.tool.repository.MavenRepository;
26
import com.devonfw.tools.ide.variable.IdeVariables;
27
import com.devonfw.tools.ide.version.IdeVersion;
28
import com.devonfw.tools.ide.version.VersionIdentifier;
29

30
/**
31
 * {@link MvnBasedLocalToolCommandlet} for IDEasy (ide-cli).
32
 */
33
public class IdeasyCommandlet extends MvnBasedLocalToolCommandlet {
34

35
  /** The {@link MvnArtifact} for IDEasy. */
36
  public static final MvnArtifact ARTIFACT = MvnArtifact.ofIdeasyCli("*!", "tar.gz", "${os}-${arch}");
6✔
37

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

40
  /** The {@link #getName() tool name}. */
41
  public static final String TOOL_NAME = "ideasy";
42
  public static final String BASHRC = ".bashrc";
43
  public static final String ZSHRC = ".zshrc";
44
  public static final String IDE_BIN = "\\_ide\\bin";
45
  public static final String IDE_INSTALLATION_BIN = "\\_ide\\installation\\bin";
46

47
  private final UpgradeMode mode;
48

49
  /**
50
   * The constructor.
51
   *
52
   * @param context the {@link IdeContext}.
53
   */
54
  public IdeasyCommandlet(IdeContext context) {
55
    this(context, UpgradeMode.STABLE);
4✔
56
  }
1✔
57

58
  /**
59
   * The constructor.
60
   *
61
   * @param context the {@link IdeContext}.
62
   * @param mode the {@link UpgradeMode}.
63
   */
64
  public IdeasyCommandlet(IdeContext context, UpgradeMode mode) {
65

66
    super(context, TOOL_NAME, ARTIFACT, Set.of(Tag.PRODUCTIVITY, Tag.IDE));
8✔
67
    this.mode = mode;
3✔
68
  }
1✔
69

70
  @Override
71
  public VersionIdentifier getInstalledVersion() {
72

73
    return IdeVersion.getVersionIdentifier();
2✔
74
  }
75

76
  @Override
77
  public String getConfiguredEdition() {
78

79
    return this.tool;
×
80
  }
81

82
  @Override
83
  public VersionIdentifier getConfiguredVersion() {
84

85
    UpgradeMode upgradeMode = this.mode;
×
86
    if (upgradeMode == null) {
×
87
      if (IdeVersion.getVersionString().contains("SNAPSHOT")) {
×
88
        upgradeMode = UpgradeMode.SNAPSHOT;
×
89
      } else {
90
        if (IdeVersion.getVersionIdentifier().getDevelopmentPhase().isStable()) {
×
91
          upgradeMode = UpgradeMode.STABLE;
×
92
        } else {
93
          upgradeMode = UpgradeMode.UNSTABLE;
×
94
        }
95
      }
96
    }
97
    return upgradeMode.getVersion();
×
98
  }
99

100
  @Override
101
  public Path getToolPath() {
102

103
    return this.context.getIdeInstallationPath();
×
104
  }
105

106
  @Override
107
  public boolean install(boolean silent) {
108
    
109
    this.context.requireOnline("upgrade of IDEasy", true);
5✔
110

111
    if (IdeVersion.isUndefined()) {
2!
112
      this.context.warning("You are using IDEasy version {} which indicates local development - skipping upgrade.", IdeVersion.getVersionString());
10✔
113
      return false;
2✔
114
    }
115
    return super.install(silent);
×
116
  }
117

118
  /**
119
   * @return the latest released {@link VersionIdentifier version} of IDEasy.
120
   */
121
  public VersionIdentifier getLatestVersion() {
122

123
    VersionIdentifier currentVersion = IdeVersion.getVersionIdentifier();
2✔
124
    if (IdeVersion.isUndefined()) {
2!
125
      return currentVersion;
2✔
126
    }
127
    VersionIdentifier configuredVersion = getConfiguredVersion();
×
128
    return getToolRepository().resolveVersion(this.tool, getConfiguredEdition(), configuredVersion, this);
×
129
  }
130

131
  /**
132
   * Checks if an update is available and logs according information.
133
   *
134
   * @return {@code true} if an update is available, {@code false} otherwise.
135
   */
136
  public boolean checkIfUpdateIsAvailable() {
137
    VersionIdentifier installedVersion = getInstalledVersion();
3✔
138
    if (!this.context.isOnline()) {
4✔
139
      this.context.success("Your version of IDEasy is {}.", installedVersion);
10✔
140
      this.context.warning("Skipping check for newer version of IDEasy due to lack of network connectivity.");
4✔
141
      return false;
2✔
142
    }
143
    VersionIdentifier latestVersion = getLatestVersion();
3✔
144
    if (installedVersion.equals(latestVersion)) {
4!
145
      this.context.success("Your version of IDEasy is {} which is the latest released version.", installedVersion);
10✔
146
      return false;
2✔
147
    } else {
148
      this.context.interaction("Your version of IDEasy is {} but version {} is available. Please run the following command to upgrade to the latest version:\n"
×
149
          + "ide upgrade", installedVersion, latestVersion);
150
      return true;
×
151
    }
152
  }
153

154
  /**
155
   * Initial installation of IDEasy.
156
   *
157
   * @param cwd the {@link Path} to the current working directory.
158
   * @see com.devonfw.tools.ide.commandlet.InstallCommandlet
159
   */
160
  public void installIdeasy(Path cwd) {
161
    Path ideRoot = determineIdeRoot(cwd);
4✔
162
    Path idePath = ideRoot.resolve(IdeContext.FOLDER_UNDERSCORE_IDE);
4✔
163
    Path installationPath = idePath.resolve(IdeContext.FOLDER_INSTALLATION);
4✔
164
    Path ideasySoftwarePath = idePath.resolve(IdeContext.FOLDER_SOFTWARE).resolve(MavenRepository.ID).resolve(IdeasyCommandlet.TOOL_NAME)
8✔
165
        .resolve(IdeasyCommandlet.TOOL_NAME);
2✔
166
    Path ideasyVersionPath = ideasySoftwarePath.resolve(IdeVersion.getVersionString());
4✔
167
    if (Files.isDirectory(ideasyVersionPath)) {
5!
168
      throw new CliException("IDEasy is already installed at " + ideasyVersionPath + " - if your installation is broken, delete it manually and rerun setup!");
×
169
    }
170
    FileAccess fileAccess = this.context.getFileAccess();
4✔
171
    List<Path> installationArtifacts = new ArrayList<>();
4✔
172
    boolean success = true;
2✔
173
    success &= addInstallationArtifact(cwd, "bin", true, installationArtifacts);
9✔
174
    success &= addInstallationArtifact(cwd, "functions", true, installationArtifacts);
9✔
175
    success &= addInstallationArtifact(cwd, "internal", true, installationArtifacts);
9✔
176
    success &= addInstallationArtifact(cwd, "system", true, installationArtifacts);
9✔
177
    success &= addInstallationArtifact(cwd, "IDEasy.pdf", true, installationArtifacts);
9✔
178
    success &= addInstallationArtifact(cwd, "setup", true, installationArtifacts);
9✔
179
    success &= addInstallationArtifact(cwd, "setup.bat", false, installationArtifacts);
9✔
180
    if (!success) {
2!
181
      throw new CliException("IDEasy release is inconsistent at " + cwd);
×
182
    }
183
    fileAccess.mkdirs(ideasyVersionPath);
3✔
184
    for (Path installationArtifact : installationArtifacts) {
10✔
185
      fileAccess.copy(installationArtifact, ideasyVersionPath);
4✔
186
    }
1✔
187
    this.context.writeVersionFile(IdeVersion.getVersionIdentifier(), ideasyVersionPath);
5✔
188
    fileAccess.symlink(ideasyVersionPath, installationPath);
4✔
189
    addToShellRc(BASHRC, ideRoot, null);
5✔
190
    addToShellRc(ZSHRC, ideRoot, "autoload -U +X bashcompinit && bashcompinit");
5✔
191
    installIdeasyWindowsEnv(ideRoot, installationPath);
4✔
192
    this.context.success("IDEasy has been installed successfully on your system.");
4✔
193
    this.context.warning("IDEasy has been setup for new shells but it cannot work in your current shell(s).\n"
4✔
194
        + "Reboot or open a new terminal to make it work.");
195
  }
1✔
196

197
  private void installIdeasyWindowsEnv(Path ideRoot, Path installationPath) {
198
    if (!this.context.getSystemInfo().isWindows()) {
5✔
199
      return;
1✔
200
    }
201
    WindowsHelper helper = WindowsHelper.get(this.context);
4✔
202
    helper.setUserEnvironmentValue(IdeVariables.IDE_ROOT.getName(), ideRoot.toString());
6✔
203
    String userPath = helper.getUserEnvironmentValue(IdeVariables.PATH.getName());
5✔
204
    if (userPath == null) {
2!
205
      this.context.error("Could not read user PATH from registry!");
×
206
    } else {
207
      this.context.info("Found user PATH={}", userPath);
10✔
208
      Path ideasyBinPath = installationPath.resolve("bin");
4✔
209
      SimpleSystemPath path = SimpleSystemPath.of(userPath, ';');
4✔
210
      if (path.getEntries().isEmpty()) {
4!
211
        this.context.warning("ATTENTION:\n"
×
212
            + "Your user specific PATH variable seems to be empty.\n"
213
            + "You can double check this by pressing [Windows][r] and launch the program SystemPropertiesAdvanced.\n"
214
            + "Then click on 'Environment variables' and check if 'PATH' is set in the 'user variables' from the upper list.\n"
215
            + "In case 'PATH' is defined there non-empty and you get this message, please abort and give us feedback:\n"
216
            + "https://github.com/devonfw/IDEasy/issues\n"
217
            + "Otherwise all is correct and you can continue.");
218
        this.context.askToContinue("Are you sure you want to override your PATH?");
×
219
      } else {
220
        path.removeEntries(s -> s.endsWith(IDE_BIN));
7✔
221
      }
222
      path.getEntries().add(ideasyBinPath.toString());
6✔
223
      helper.setUserEnvironmentValue(IdeVariables.PATH.getName(), path.toString());
6✔
224
      setGitLongpaths();
2✔
225
    }
226
  }
1✔
227

228
  private void setGitLongpaths() {
229
    GitContext gitContext = new GitContextImpl(this.context);
6✔
230
    gitContext.verifyGitInstalled();
2✔
231
    setGitConfigProperty("core", "longpaths", "true", this.context.getUserHome().resolve(".gitconfig"));
10✔
232
  }
1✔
233

234
  /**
235
   * @param section the section to modify
236
   * @param property the property to set
237
   * @param value the value to set
238
   * @param configPath the path of the config file
239
   */
240
  public void setGitConfigProperty(String section, String property, String value, Path configPath) {
241
    String gitconfig;
242
    // read files
243
    FileAccess fileAccess = this.context.getFileAccess();
4✔
244
    gitconfig = fileAccess.readFileContent(configPath);
4✔
245
    if (gitconfig == null) {
2✔
246
      gitconfig = "";
2✔
247
    }
248

249
    LinkedHashMap<String, LinkedHashMap<String, String>> iniMap = parseIniFile(gitconfig);
4✔
250

251
    // check if section exists
252
    if (!iniMap.containsKey(section)) {
4✔
253
      iniMap.put(section, new LinkedHashMap<>());
7✔
254
    }
255

256
    // set property
257
    iniMap.get(section).put(property, value);
8✔
258

259
    // write out new file
260
    StringBuilder newConfig = new StringBuilder();
4✔
261
    for (String configSection : iniMap.keySet()) {
11✔
262
      newConfig.append(String.format("[%s]\n", configSection));
11✔
263
      LinkedHashMap<String, String> properties = iniMap.get(configSection);
5✔
264
      for (String sectionProperty : properties.keySet()) {
11✔
265
        String propertyValue = properties.get(sectionProperty);
5✔
266
        newConfig.append(String.format("\t%s = %s\n", sectionProperty, propertyValue));
15✔
267
      }
1✔
268
    }
1✔
269

270
    try {
271
      Files.writeString(configPath, newConfig.toString());
7✔
272
    } catch (IOException e) {
×
273
      this.context.error("could not write git config file at %s", configPath);
×
274
    }
1✔
275
  }
1✔
276

277
  private LinkedHashMap<String, LinkedHashMap<String, String>> parseIniFile(String iniFile) {
278
    List<String> iniLines = iniFile.lines().toList();
4✔
279
    LinkedHashMap<String, LinkedHashMap<String, String>> iniMap = new LinkedHashMap<>();
4✔
280
    String currentSection = "";
2✔
281
    for (String line : iniLines) {
10✔
282
      if (line.isEmpty()) {
3!
283
        continue;
×
284
      }
285
      if (line.startsWith("[")) {
4✔
286
        currentSection = line.replace("[", "").replace("]", "");
8✔
287
        iniMap.put(currentSection, new LinkedHashMap<>());
8✔
288
      } else {
289
        String[] parts = line.split("=");
4✔
290
        String propertyName = parts[0].trim();
5✔
291
        String propertyValue = parts[1].trim();
5✔
292
        iniMap.get(currentSection).put(propertyName, propertyValue);
8✔
293
      }
294
    }
1✔
295
    return iniMap;
2✔
296
  }
297

298
  static String removeObsoleteEntryFromWindowsPath(String userPath) {
299
    return removeEntryFromWindowsPath(userPath, IDE_BIN);
4✔
300
  }
301

302
  static String removeEntryFromWindowsPath(String userPath, String suffix) {
303
    int len = userPath.length();
3✔
304
    int start = 0;
2✔
305
    while ((start >= 0) && (start < len)) {
5!
306
      int end = userPath.indexOf(';', start);
5✔
307
      if (end < 0) {
2✔
308
        end = len;
2✔
309
      }
310
      String entry = userPath.substring(start, end);
5✔
311
      if (entry.endsWith(suffix)) {
4✔
312
        String prefix = "";
2✔
313
        int offset = 1;
2✔
314
        if (start > 0) {
2✔
315
          prefix = userPath.substring(0, start - 1);
7✔
316
          offset = 0;
2✔
317
        }
318
        if (end == len) {
3✔
319
          return prefix;
2✔
320
        } else {
321
          return removeEntryFromWindowsPath(prefix + userPath.substring(end + offset), suffix);
10✔
322
        }
323
      }
324
      start = end + 1;
4✔
325
    }
1✔
326
    return userPath;
2✔
327
  }
328

329
  /**
330
   * Adds ourselves to the shell RC (run-commands) configuration file.
331
   *
332
   * @param filename the name of the RC file.
333
   * @param ideRoot the IDE_ROOT {@link Path}.
334
   */
335
  private void addToShellRc(String filename, Path ideRoot, String extraLine) {
336

337
    modifyShellRc(filename, ideRoot, true, extraLine);
6✔
338
  }
1✔
339

340
  private void removeFromShellRc(String filename, Path ideRoot) {
341

342
    modifyShellRc(filename, ideRoot, false, null);
6✔
343
  }
1✔
344

345
  /**
346
   * Adds ourselves to the shell RC (run-commands) configuration file.
347
   *
348
   * @param filename the name of the RC file.
349
   * @param ideRoot the IDE_ROOT {@link Path}.
350
   */
351
  private void modifyShellRc(String filename, Path ideRoot, boolean add, String extraLine) {
352

353
    if (add) {
2✔
354
      this.context.info("Configuring IDEasy in {}", filename);
11✔
355
    } else {
356
      this.context.info("Removing IDEasy from {}", filename);
10✔
357
    }
358
    Path rcFile = this.context.getUserHome().resolve(filename);
6✔
359
    FileAccess fileAccess = this.context.getFileAccess();
4✔
360
    List<String> lines = fileAccess.readFileLines(rcFile);
4✔
361
    if (lines == null) {
2✔
362
      if (!add) {
2!
363
        return;
×
364
      }
365
      lines = new ArrayList<>();
5✔
366
    } else {
367
      // since it is unspecified if the returned List may be immutable we want to get sure
368
      lines = new ArrayList<>(lines);
5✔
369
    }
370
    Iterator<String> iterator = lines.iterator();
3✔
371
    int removeCount = 0;
2✔
372
    while (iterator.hasNext()) {
3✔
373
      String line = iterator.next();
4✔
374
      line = line.trim();
3✔
375
      if (isObsoleteRcLine(line)) {
3✔
376
        this.context.info("Removing obsolete line from {}: {}", filename, line);
14✔
377
        iterator.remove();
2✔
378
        removeCount++;
2✔
379
      } else if (line.equals(extraLine)) {
4✔
380
        extraLine = null;
2✔
381
      }
382
    }
1✔
383
    if (add) {
2✔
384
      if (extraLine != null) {
2!
385
        lines.add(extraLine);
×
386
      }
387
      if (!this.context.getSystemInfo().isWindows()) {
5✔
388
        lines.add("export IDE_ROOT=\"" + WindowsPathSyntax.MSYS.format(ideRoot) + "\"");
7✔
389
      }
390
      lines.add(BASH_CODE_SOURCE_FUNCTIONS);
4✔
391
    }
392
    fileAccess.writeFileLines(lines, rcFile);
4✔
393
    this.context.debug("Successfully updated {}", filename);
10✔
394
  }
1✔
395

396
  private static boolean isObsoleteRcLine(String line) {
397
    if (line.startsWith("alias ide=")) {
4!
398
      return true;
×
399
    } else if (line.startsWith("export IDE_ROOT=")) {
4!
400
      return true;
×
401
    } else if (line.equals("ide")) {
4✔
402
      return true;
2✔
403
    } else if (line.equals("ide init")) {
4✔
404
      return true;
2✔
405
    } else if (line.startsWith("source \"$IDE_ROOT/_ide/")) {
4✔
406
      return true;
2✔
407
    }
408
    return false;
2✔
409
  }
410

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

413
    Path artifactPath = cwd.resolve(artifactName);
4✔
414
    if (Files.exists(artifactPath)) {
5!
415
      installationArtifacts.add(artifactPath);
5✔
416
    } else if (required) {
×
417
      this.context.error("Missing required file {}", artifactName);
×
418
      return false;
×
419
    }
420
    return true;
2✔
421
  }
422

423
  private Path determineIdeRoot(Path cwd) {
424
    Path ideRoot = this.context.getIdeRoot();
4✔
425
    if (ideRoot == null) {
2!
426
      Path home = this.context.getUserHome();
4✔
427
      Path installRoot = home;
2✔
428
      if (this.context.getSystemInfo().isWindows()) {
5✔
429
        if (!cwd.startsWith(home)) {
4!
430
          installRoot = cwd.getRoot();
×
431
        }
432
      }
433
      ideRoot = installRoot.resolve(IdeContext.FOLDER_PROJECTS);
4✔
434
    } else {
1✔
435
      assert (Files.isDirectory(ideRoot)) : "IDE_ROOT directory does not exist!";
×
436
    }
437
    return ideRoot;
2✔
438
  }
439

440
  /**
441
   * Uninstalls IDEasy entirely from the system.
442
   */
443
  public void uninstallIdeasy() {
444

445
    Path ideRoot = this.context.getIdeRoot();
4✔
446
    removeFromShellRc(BASHRC, ideRoot);
4✔
447
    removeFromShellRc(ZSHRC, ideRoot);
4✔
448
    Path idePath = this.context.getIdePath();
4✔
449
    uninstallIdeasyWindowsEnv(ideRoot);
3✔
450
    uninstallIdeasyIdePath(idePath);
3✔
451
    deleteDownloadCache();
2✔
452
    this.context.success("IDEasy has been uninstalled from your system.");
4✔
453
    this.context.interaction("ATTENTION:\n"
10✔
454
        + "In order to prevent data-loss, we do not delete your projects and git repositories!\n"
455
        + "To entirely get rid of IDEasy, also check your IDE_ROOT folder at:\n"
456
        + "{}", ideRoot);
457
  }
1✔
458

459
  private void deleteDownloadCache() {
460
    Path downloadPath = this.context.getDownloadPath();
4✔
461
    this.context.info("Deleting download cache from {}", downloadPath);
10✔
462
    this.context.getFileAccess().delete(downloadPath);
5✔
463
  }
1✔
464

465
  private void uninstallIdeasyIdePath(Path idePath) {
466
    if (this.context.getSystemInfo().isWindows()) {
5✔
467
      this.context.newProcess().executable("bash").addArgs("-c",
17✔
468
          "sleep 10 && rm -rf \"" + WindowsPathSyntax.MSYS.format(idePath) + "\"").run(ProcessMode.BACKGROUND);
5✔
469
      this.context.interaction("To prevent windows file locking errors, we perform an asynchronous deletion of {} in background now.\n"
11✔
470
          + "Please close all terminals and wait a minute for the deletion to complete before running other commands.", idePath);
471
    } else {
472
      this.context.info("Finally deleting {}", idePath);
10✔
473
      this.context.getFileAccess().delete(idePath);
5✔
474
    }
475
  }
1✔
476

477
  private void uninstallIdeasyWindowsEnv(Path ideRoot) {
478
    if (!this.context.getSystemInfo().isWindows()) {
5✔
479
      return;
1✔
480
    }
481
    WindowsHelper helper = WindowsHelper.get(this.context);
4✔
482
    helper.removeUserEnvironmentValue(IdeVariables.IDE_ROOT.getName());
4✔
483
    String userPath = helper.getUserEnvironmentValue(IdeVariables.PATH.getName());
5✔
484
    if (userPath == null) {
2!
485
      this.context.error("Could not read user PATH from registry!");
×
486
    } else {
487
      this.context.info("Found user PATH={}", userPath);
10✔
488
      String newUserPath = userPath;
2✔
489
      if (!userPath.isEmpty()) {
3!
490
        SimpleSystemPath path = SimpleSystemPath.of(userPath, ';');
4✔
491
        path.removeEntries(s -> s.endsWith(IDE_BIN) || s.endsWith(IDE_INSTALLATION_BIN));
15!
492
        newUserPath = path.toString();
3✔
493
      }
494
      if (newUserPath.equals(userPath)) {
4!
495
        this.context.error("Could not find IDEasy in PATH:\n{}", userPath);
×
496
      } else {
497
        helper.setUserEnvironmentValue(IdeVariables.PATH.getName(), newUserPath);
5✔
498
      }
499
    }
500
  }
1✔
501
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc