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

devonfw / IDEasy / 23611799227

26 Mar 2026 06:38PM UTC coverage: 70.419% (-0.02%) from 70.437%
23611799227

Pull #1774

github

web-flow
Merge 10a690d9e into 50c288e95
Pull Request #1774: #1770: fix setup hanging due to buffered log output during license prompt

4161 of 6514 branches covered (63.88%)

Branch coverage included in aggregate %.

10782 of 14706 relevant lines covered (73.32%)

3.09 hits per line

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

65.79
cli/src/main/java/com/devonfw/tools/ide/context/AbstractIdeContext.java
1
package com.devonfw.tools.ide.context;
2

3
import static com.devonfw.tools.ide.variable.IdeVariables.IDE_MIN_VERSION;
4

5
import java.io.ByteArrayInputStream;
6
import java.io.ByteArrayOutputStream;
7
import java.io.IOException;
8
import java.nio.file.Files;
9
import java.nio.file.Path;
10
import java.time.LocalDateTime;
11
import java.util.ArrayList;
12
import java.util.HashMap;
13
import java.util.Iterator;
14
import java.util.List;
15
import java.util.Locale;
16
import java.util.Map;
17
import java.util.Map.Entry;
18
import java.util.Objects;
19
import java.util.Properties;
20
import java.util.function.Predicate;
21
import java.util.logging.FileHandler;
22
import java.util.logging.LogManager;
23
import java.util.logging.SimpleFormatter;
24

25
import org.slf4j.Logger;
26
import org.slf4j.LoggerFactory;
27

28
import com.devonfw.tools.ide.cli.CliAbortException;
29
import com.devonfw.tools.ide.cli.CliArgument;
30
import com.devonfw.tools.ide.cli.CliArguments;
31
import com.devonfw.tools.ide.cli.CliException;
32
import com.devonfw.tools.ide.commandlet.Commandlet;
33
import com.devonfw.tools.ide.commandlet.CommandletManager;
34
import com.devonfw.tools.ide.commandlet.CommandletManagerImpl;
35
import com.devonfw.tools.ide.commandlet.ContextCommandlet;
36
import com.devonfw.tools.ide.commandlet.EnvironmentCommandlet;
37
import com.devonfw.tools.ide.common.SystemPath;
38
import com.devonfw.tools.ide.completion.CompletionCandidate;
39
import com.devonfw.tools.ide.completion.CompletionCandidateCollector;
40
import com.devonfw.tools.ide.completion.CompletionCandidateCollectorDefault;
41
import com.devonfw.tools.ide.environment.AbstractEnvironmentVariables;
42
import com.devonfw.tools.ide.environment.EnvironmentVariables;
43
import com.devonfw.tools.ide.environment.EnvironmentVariablesType;
44
import com.devonfw.tools.ide.environment.IdeSystem;
45
import com.devonfw.tools.ide.environment.IdeSystemImpl;
46
import com.devonfw.tools.ide.git.GitContext;
47
import com.devonfw.tools.ide.git.GitContextImpl;
48
import com.devonfw.tools.ide.git.GitUrl;
49
import com.devonfw.tools.ide.io.FileAccess;
50
import com.devonfw.tools.ide.io.FileAccessImpl;
51
import com.devonfw.tools.ide.log.IdeLogArgFormatter;
52
import com.devonfw.tools.ide.log.IdeLogLevel;
53
import com.devonfw.tools.ide.log.IdeLogListener;
54
import com.devonfw.tools.ide.log.JulConsoleHandler;
55
import com.devonfw.tools.ide.merge.DirectoryMerger;
56
import com.devonfw.tools.ide.migration.IdeMigrator;
57
import com.devonfw.tools.ide.network.NetworkStatus;
58
import com.devonfw.tools.ide.network.NetworkStatusImpl;
59
import com.devonfw.tools.ide.os.SystemInfo;
60
import com.devonfw.tools.ide.os.SystemInfoImpl;
61
import com.devonfw.tools.ide.os.WindowsHelper;
62
import com.devonfw.tools.ide.os.WindowsHelperImpl;
63
import com.devonfw.tools.ide.os.WindowsPathSyntax;
64
import com.devonfw.tools.ide.process.ProcessContext;
65
import com.devonfw.tools.ide.process.ProcessContextImpl;
66
import com.devonfw.tools.ide.process.ProcessResult;
67
import com.devonfw.tools.ide.property.Property;
68
import com.devonfw.tools.ide.step.Step;
69
import com.devonfw.tools.ide.step.StepImpl;
70
import com.devonfw.tools.ide.tool.custom.CustomToolRepository;
71
import com.devonfw.tools.ide.tool.custom.CustomToolRepositoryImpl;
72
import com.devonfw.tools.ide.tool.mvn.MvnRepository;
73
import com.devonfw.tools.ide.tool.npm.NpmRepository;
74
import com.devonfw.tools.ide.tool.pip.PipRepository;
75
import com.devonfw.tools.ide.tool.repository.DefaultToolRepository;
76
import com.devonfw.tools.ide.tool.repository.ToolRepository;
77
import com.devonfw.tools.ide.url.model.UrlMetadata;
78
import com.devonfw.tools.ide.util.DateTimeUtil;
79
import com.devonfw.tools.ide.util.PrivacyUtil;
80
import com.devonfw.tools.ide.validation.ValidationResult;
81
import com.devonfw.tools.ide.validation.ValidationResultValid;
82
import com.devonfw.tools.ide.validation.ValidationState;
83
import com.devonfw.tools.ide.variable.IdeVariables;
84
import com.devonfw.tools.ide.version.IdeVersion;
85
import com.devonfw.tools.ide.version.VersionIdentifier;
86

87
/**
88
 * Abstract base implementation of {@link IdeContext}.
89
 */
90
public abstract class AbstractIdeContext implements IdeContext, IdeLogArgFormatter {
91

92
  static final Logger LOG = LoggerFactory.getLogger(AbstractIdeContext.class);
3✔
93

94
  /** The default shell bash (Bourne Again SHell). */
95
  public static final String BASH = "bash";
96

97
  private static final GitUrl IDE_URLS_GIT = new GitUrl("https://github.com/devonfw/ide-urls.git", null);
7✔
98

99
  private static final String LICENSE_URL = "https://github.com/devonfw/IDEasy/blob/main/documentation/LICENSE.adoc";
100

101
  private static final String DEFAULT_WINDOWS_GIT_PATH = "C:\\Program Files\\Git\\bin\\bash.exe";
102

103
  private static final String OPTION_DETAILS_START = "([";
104

105
  private final IdeStartContextImpl startContext;
106

107
  private Path ideHome;
108

109
  private final Path ideRoot;
110

111
  private Path confPath;
112

113
  protected Path settingsPath;
114

115
  private Path settingsCommitIdPath;
116

117
  protected Path pluginsPath;
118

119
  private Path workspacePath;
120

121
  private Path workspacesBasePath;
122

123
  private String workspaceName;
124

125
  private Path cwd;
126

127
  private Path downloadPath;
128

129
  private Path userHome;
130

131
  private Path userHomeIde;
132

133
  private SystemPath path;
134

135
  private WindowsPathSyntax pathSyntax;
136

137
  private final SystemInfo systemInfo;
138

139
  private EnvironmentVariables variables;
140

141
  private final FileAccess fileAccess;
142

143
  protected CommandletManager commandletManager;
144

145
  protected ToolRepository defaultToolRepository;
146

147
  private CustomToolRepository customToolRepository;
148

149
  private MvnRepository mvnRepository;
150

151
  private NpmRepository npmRepository;
152

153
  private PipRepository pipRepository;
154

155
  private DirectoryMerger workspaceMerger;
156

157
  protected UrlMetadata urlMetadata;
158

159
  protected Path defaultExecutionDirectory;
160

161
  private StepImpl currentStep;
162

163
  private NetworkStatus networkStatus;
164

165
  protected IdeSystem system;
166

167
  private WindowsHelper windowsHelper;
168

169
  private final Map<String, String> privacyMap;
170

171
  private Path bash;
172

173
  private boolean julConfigured;
174

175
  private Path logfile;
176

177
  /**
178
   * The constructor.
179
   *
180
   * @param startContext the {@link IdeStartContextImpl}.
181
   * @param workingDirectory the optional {@link Path} to current working directory.
182
   */
183
  public AbstractIdeContext(IdeStartContextImpl startContext, Path workingDirectory) {
184

185
    super();
2✔
186
    this.startContext = startContext;
3✔
187
    this.startContext.setArgFormatter(this);
4✔
188
    this.privacyMap = new HashMap<>();
5✔
189
    this.systemInfo = SystemInfoImpl.INSTANCE;
3✔
190
    if (isTest()) {
3!
191
      configureJavaUtilLogging(null);
3✔
192
    }
193
    this.commandletManager = new CommandletManagerImpl(this);
6✔
194
    this.fileAccess = new FileAccessImpl(this);
6✔
195
    String userHomeProperty = getSystem().getProperty("user.home");
5✔
196
    if (userHomeProperty != null) {
2!
197
      this.userHome = Path.of(userHomeProperty);
×
198
    }
199
    if (workingDirectory == null) {
2!
200
      workingDirectory = Path.of(System.getProperty("user.dir"));
×
201
    }
202
    workingDirectory = workingDirectory.toAbsolutePath();
3✔
203
    if (Files.isDirectory(workingDirectory)) {
5✔
204
      workingDirectory = this.fileAccess.toCanonicalPath(workingDirectory);
6✔
205
    } else {
206
      LOG.warn("Current working directory does not exist: {}", workingDirectory);
4✔
207
    }
208
    this.cwd = workingDirectory;
3✔
209
    // detect IDE_HOME and WORKSPACE
210
    String workspace = null;
2✔
211
    Path ideHomeDir = null;
2✔
212
    IdeHomeAndWorkspace ideHomeAndWorkspace = findIdeHome(workingDirectory);
4✔
213
    if (ideHomeAndWorkspace != null) {
2!
214
      ideHomeDir = ideHomeAndWorkspace.home();
3✔
215
      workspace = ideHomeAndWorkspace.workspace();
3✔
216
    }
217

218
    // detection completed, initializing variables
219
    this.ideRoot = findIdeRoot(ideHomeDir);
5✔
220

221
    setCwd(workingDirectory, workspace, ideHomeDir);
5✔
222

223
    if (this.ideRoot != null) {
3✔
224
      Path tempDownloadPath = getTempDownloadPath();
3✔
225
      if (Files.isDirectory(tempDownloadPath)) {
6✔
226
        // TODO delete all files older than 1 day here...
227
      } else {
228
        this.fileAccess.mkdirs(tempDownloadPath);
4✔
229
      }
230
    }
231
    this.defaultToolRepository = new DefaultToolRepository(this);
6✔
232
  }
1✔
233

234
  /**
235
   * Searches for the IDE home directory by traversing up the directory tree from the given working directory. This method can be overridden in test contexts to
236
   * add additional validation or boundary checks.
237
   *
238
   * @param workingDirectory the starting directory for the search.
239
   * @return an instance of {@link IdeHomeAndWorkspace} where the IDE_HOME was found or {@code null} if not found.
240
   */
241
  protected IdeHomeAndWorkspace findIdeHome(Path workingDirectory) {
242

243
    Path currentDir = workingDirectory;
2✔
244
    String name1 = "";
2✔
245
    String name2 = "";
2✔
246
    String workspace = WORKSPACE_MAIN;
2✔
247
    Path ideRootPath = getIdeRootPathFromEnv(false);
4✔
248

249
    while (currentDir != null) {
2✔
250
      LOG.trace("Looking for IDE_HOME in {}", currentDir);
4✔
251
      if (isIdeHome(currentDir)) {
4✔
252
        if (FOLDER_WORKSPACES.equals(name1) && !name2.isEmpty()) {
7✔
253
          workspace = name2;
3✔
254
        }
255
        break;
256
      }
257
      name2 = name1;
2✔
258
      int nameCount = currentDir.getNameCount();
3✔
259
      if (nameCount >= 1) {
3✔
260
        name1 = currentDir.getName(nameCount - 1).toString();
7✔
261
      }
262
      currentDir = currentDir.getParent();
3✔
263
      if ((ideRootPath != null) && (ideRootPath.equals(currentDir))) {
2!
264
        // prevent that during tests we traverse to the real IDE project of IDEasy developer
265
        currentDir = null;
×
266
      }
267
    }
1✔
268

269
    return new IdeHomeAndWorkspace(currentDir, workspace);
6✔
270
  }
271

272
  /**
273
   * @return a new {@link MvnRepository}
274
   */
275
  protected MvnRepository createMvnRepository() {
276
    return new MvnRepository(this);
5✔
277
  }
278

279
  /**
280
   * @return a new {@link NpmRepository}
281
   */
282
  protected NpmRepository createNpmRepository() {
283
    return new NpmRepository(this);
×
284
  }
285

286
  /**
287
   * @return a new {@link PipRepository}
288
   */
289
  protected PipRepository createPipRepository() {
290
    return new PipRepository(this);
×
291
  }
292

293
  private Path findIdeRoot(Path ideHomePath) {
294

295
    Path ideRootPath = null;
2✔
296
    if (ideHomePath != null) {
2✔
297
      Path ideRootPathFromEnv = getIdeRootPathFromEnv(true);
4✔
298
      ideRootPath = ideHomePath.getParent();
3✔
299
      if ((ideRootPathFromEnv != null) && !ideRootPath.toString().equals(ideRootPathFromEnv.toString())) {
2!
300
        LOG.warn(
×
301
            "Variable IDE_ROOT is set to '{}' but for your project '{}' the path '{}' would have been expected.\n"
302
                + "Please check your 'user.dir' or working directory setting and make sure that it matches your IDE_ROOT variable.",
303
            ideRootPathFromEnv,
304
            ideHomePath.getFileName(), ideRootPath);
×
305
      }
306
    } else if (!isTest()) {
4!
307
      ideRootPath = getIdeRootPathFromEnv(true);
×
308
    }
309
    return ideRootPath;
2✔
310
  }
311

312
  /**
313
   * @return the {@link #getIdeRoot() IDE_ROOT} from the system environment.
314
   */
315
  protected Path getIdeRootPathFromEnv(boolean withSanityCheck) {
316

317
    String root = getSystem().getEnv(IdeVariables.IDE_ROOT.getName());
×
318
    if (root != null) {
×
319
      Path rootPath = Path.of(root);
×
320
      if (Files.isDirectory(rootPath)) {
×
321
        Path absoluteRootPath = getFileAccess().toCanonicalPath(rootPath);
×
322
        if (withSanityCheck) {
×
323
          int nameCount = rootPath.getNameCount();
×
324
          int absoluteNameCount = absoluteRootPath.getNameCount();
×
325
          int delta = absoluteNameCount - nameCount;
×
326
          if (delta >= 0) {
×
327
            for (int nameIndex = 0; nameIndex < nameCount; nameIndex++) {
×
328
              String rootName = rootPath.getName(nameIndex).toString();
×
329
              String absoluteRootName = absoluteRootPath.getName(nameIndex + delta).toString();
×
330
              if (!rootName.equals(absoluteRootName)) {
×
331
                LOG.warn("IDE_ROOT is set to {} but was expanded to absolute path {} and does not match for segment {} and {} - fix your IDEasy installation!",
×
332
                    rootPath, absoluteRootPath, rootName, absoluteRootName);
333
                break;
×
334
              }
335
            }
336
          } else {
337
            LOG.warn("IDE_ROOT is set to {} but was expanded to a shorter absolute path {}", rootPath,
×
338
                absoluteRootPath);
339
          }
340
        }
341
        return absoluteRootPath;
×
342
      } else if (withSanityCheck) {
×
343
        LOG.warn("IDE_ROOT is set to {} that is not an existing directory - fix your IDEasy installation!", rootPath);
×
344
      }
345
    }
346
    return null;
×
347
  }
348

349
  @Override
350
  public void setCwd(Path userDir, String workspace, Path ideHome) {
351

352
    this.cwd = userDir;
3✔
353
    this.workspaceName = workspace;
3✔
354
    this.ideHome = ideHome;
3✔
355
    if (ideHome == null) {
2✔
356
      this.workspacesBasePath = null;
3✔
357
      this.workspacePath = null;
3✔
358
      this.confPath = null;
3✔
359
      this.settingsPath = null;
3✔
360
      this.pluginsPath = null;
4✔
361
    } else {
362
      this.workspacesBasePath = this.ideHome.resolve(FOLDER_WORKSPACES);
6✔
363
      this.workspacePath = this.workspacesBasePath.resolve(this.workspaceName);
7✔
364
      this.confPath = this.ideHome.resolve(FOLDER_CONF);
6✔
365
      this.settingsPath = this.ideHome.resolve(FOLDER_SETTINGS);
6✔
366
      this.settingsCommitIdPath = this.ideHome.resolve(IdeContext.SETTINGS_COMMIT_ID);
6✔
367
      this.pluginsPath = this.ideHome.resolve(FOLDER_PLUGINS);
6✔
368
    }
369
    if (isTest()) {
3!
370
      // only for testing...
371
      if (this.ideHome == null) {
3✔
372
        this.userHome = Path.of("/non-existing-user-home-for-testing");
7✔
373
      } else {
374
        this.userHome = this.ideHome.resolve("home");
6✔
375
      }
376
    }
377
    this.userHomeIde = this.userHome.resolve(FOLDER_DOT_IDE);
6✔
378
    this.downloadPath = this.userHome.resolve("Downloads/ide");
6✔
379
    resetPrivacyMap();
2✔
380
    this.path = computeSystemPath();
4✔
381
  }
1✔
382

383
  private String getMessageIdeHomeFound() {
384

385
    String wks = this.workspaceName;
3✔
386
    if (isPrivacyMode() && !WORKSPACE_MAIN.equals(wks)) {
3!
387
      wks = "*".repeat(wks.length());
×
388
    }
389
    return "IDE environment variables have been set for " + formatArgument(this.ideHome) + " in workspace " + wks;
7✔
390
  }
391

392
  private String getMessageNotInsideIdeProject() {
393

394
    return "You are not inside an IDE project: " + formatArgument(this.cwd);
6✔
395
  }
396

397
  private String getMessageIdeRootNotFound() {
398

399
    String root = getSystem().getEnv("IDE_ROOT");
5✔
400
    if (root == null) {
2!
401
      return "The environment variable IDE_ROOT is undefined. Please reinstall IDEasy or manually repair IDE_ROOT variable.";
2✔
402
    } else {
403
      return "The environment variable IDE_ROOT is pointing to an invalid path " + formatArgument(root)
×
404
          + ". Please reinstall IDEasy or manually repair IDE_ROOT variable.";
405
    }
406
  }
407

408
  /**
409
   * @return {@code true} if this is a test context for JUnits, {@code false} otherwise.
410
   */
411
  public boolean isTest() {
412

413
    return false;
×
414
  }
415

416
  protected SystemPath computeSystemPath() {
417

418
    return new SystemPath(this);
×
419
  }
420

421
  /**
422
   * Checks if the given directory is a valid IDE home by verifying it contains both 'workspaces' and 'settings' directories.
423
   *
424
   * @param dir the directory to check.
425
   * @return {@code true} if the directory is a valid IDE home, {@code false} otherwise.
426
   */
427
  protected boolean isIdeHome(Path dir) {
428

429
    if (!Files.isDirectory(dir.resolve("workspaces"))) {
7✔
430
      return false;
2✔
431
    } else if (!Files.isDirectory(dir.resolve("settings"))) {
7!
432
      return false;
×
433
    }
434
    return true;
2✔
435
  }
436

437
  private EnvironmentVariables createVariables() {
438

439
    AbstractEnvironmentVariables system = createSystemVariables();
3✔
440
    AbstractEnvironmentVariables user = system.extend(this.userHomeIde, EnvironmentVariablesType.USER);
6✔
441
    AbstractEnvironmentVariables settings = user.extend(this.settingsPath, EnvironmentVariablesType.SETTINGS);
6✔
442
    AbstractEnvironmentVariables workspace = settings.extend(this.workspacePath, EnvironmentVariablesType.WORKSPACE);
6✔
443
    AbstractEnvironmentVariables conf = workspace.extend(this.confPath, EnvironmentVariablesType.CONF);
6✔
444
    return conf.resolved();
3✔
445
  }
446

447
  protected AbstractEnvironmentVariables createSystemVariables() {
448

449
    return EnvironmentVariables.ofSystem(this);
3✔
450
  }
451

452
  @Override
453
  public SystemInfo getSystemInfo() {
454

455
    return this.systemInfo;
3✔
456
  }
457

458
  @Override
459
  public FileAccess getFileAccess() {
460

461
    return this.fileAccess;
3✔
462
  }
463

464
  @Override
465
  public CommandletManager getCommandletManager() {
466

467
    return this.commandletManager;
3✔
468
  }
469

470
  @Override
471
  public ToolRepository getDefaultToolRepository() {
472

473
    return this.defaultToolRepository;
3✔
474
  }
475

476
  @Override
477
  public MvnRepository getMvnRepository() {
478
    if (this.mvnRepository == null) {
3✔
479
      this.mvnRepository = createMvnRepository();
4✔
480
    }
481
    return this.mvnRepository;
3✔
482
  }
483

484
  @Override
485
  public NpmRepository getNpmRepository() {
486
    if (this.npmRepository == null) {
3✔
487
      this.npmRepository = createNpmRepository();
4✔
488
    }
489
    return this.npmRepository;
3✔
490
  }
491

492
  @Override
493
  public PipRepository getPipRepository() {
494
    if (this.pipRepository == null) {
3✔
495
      this.pipRepository = createPipRepository();
4✔
496
    }
497
    return this.pipRepository;
3✔
498
  }
499

500
  @Override
501
  public CustomToolRepository getCustomToolRepository() {
502

503
    if (this.customToolRepository == null) {
3!
504
      this.customToolRepository = CustomToolRepositoryImpl.of(this);
4✔
505
    }
506
    return this.customToolRepository;
3✔
507
  }
508

509
  @Override
510
  public Path getIdeHome() {
511

512
    return this.ideHome;
3✔
513
  }
514

515
  @Override
516
  public String getProjectName() {
517

518
    if (this.ideHome != null) {
3!
519
      return this.ideHome.getFileName().toString();
5✔
520
    }
521
    return "";
×
522
  }
523

524
  @Override
525
  public VersionIdentifier getProjectVersion() {
526

527
    if (this.ideHome != null) {
3!
528
      Path versionFile = this.ideHome.resolve(IdeContext.FILE_SOFTWARE_VERSION);
5✔
529
      if (Files.exists(versionFile)) {
5✔
530
        String version = this.fileAccess.readFileContent(versionFile).trim();
6✔
531
        return VersionIdentifier.of(version);
3✔
532
      }
533
    }
534
    return IdeMigrator.START_VERSION;
2✔
535
  }
536

537
  @Override
538
  public void setProjectVersion(VersionIdentifier version) {
539

540
    if (this.ideHome == null) {
3!
541
      throw new IllegalStateException("IDE_HOME not available!");
×
542
    }
543
    Objects.requireNonNull(version);
3✔
544
    Path versionFile = this.ideHome.resolve(IdeContext.FILE_SOFTWARE_VERSION);
5✔
545
    this.fileAccess.writeFileContent(version.toString(), versionFile);
6✔
546
  }
1✔
547

548
  @Override
549
  public Path getIdeRoot() {
550

551
    return this.ideRoot;
3✔
552
  }
553

554
  @Override
555
  public Path getIdePath() {
556

557
    Path myIdeRoot = getIdeRoot();
3✔
558
    if (myIdeRoot == null) {
2✔
559
      return null;
2✔
560
    }
561
    return myIdeRoot.resolve(FOLDER_UNDERSCORE_IDE);
4✔
562
  }
563

564
  @Override
565
  public Path getCwd() {
566

567
    return this.cwd;
3✔
568
  }
569

570
  @Override
571
  public Path getTempPath() {
572

573
    Path idePath = getIdePath();
3✔
574
    if (idePath == null) {
2!
575
      return null;
×
576
    }
577
    return idePath.resolve("tmp");
4✔
578
  }
579

580
  @Override
581
  public Path getTempDownloadPath() {
582

583
    Path tmp = getTempPath();
3✔
584
    if (tmp == null) {
2!
585
      return null;
×
586
    }
587
    return tmp.resolve(FOLDER_DOWNLOADS);
4✔
588
  }
589

590
  @Override
591
  public Path getUserHome() {
592

593
    return this.userHome;
3✔
594
  }
595

596
  /**
597
   * This method should only be used for tests to mock user home.
598
   *
599
   * @param userHome the new value of {@link #getUserHome()}.
600
   */
601
  protected void setUserHome(Path userHome) {
602

603
    this.userHome = userHome;
3✔
604
    resetPrivacyMap();
2✔
605
  }
1✔
606

607
  @Override
608
  public Path getUserHomeIde() {
609

610
    return this.userHomeIde;
3✔
611
  }
612

613
  @Override
614
  public Path getSettingsPath() {
615

616
    return this.settingsPath;
3✔
617
  }
618

619
  @Override
620
  public Path getSettingsGitRepository() {
621

622
    Path settingsPath = getSettingsPath();
3✔
623
    // check whether the settings path has a .git folder only if its not a symbolic link or junction
624
    if ((settingsPath != null) && !Files.exists(settingsPath.resolve(".git")) && !isSettingsRepositorySymlinkOrJunction()) {
12!
625
      LOG.error("Settings repository exists but is not a git repository.");
3✔
626
      return null;
2✔
627
    }
628
    return settingsPath;
2✔
629
  }
630

631
  @Override
632
  public boolean isSettingsRepositorySymlinkOrJunction() {
633

634
    Path settingsPath = getSettingsPath();
3✔
635
    if (settingsPath == null) {
2!
636
      return false;
×
637
    }
638
    return Files.isSymbolicLink(settingsPath) || getFileAccess().isJunction(settingsPath);
10!
639
  }
640

641
  @Override
642
  public Path getSettingsCommitIdPath() {
643

644
    return this.settingsCommitIdPath;
3✔
645
  }
646

647
  @Override
648
  public Path getConfPath() {
649

650
    return this.confPath;
3✔
651
  }
652

653
  @Override
654
  public Path getSoftwarePath() {
655

656
    if (this.ideHome == null) {
3✔
657
      return null;
2✔
658
    }
659
    return this.ideHome.resolve(FOLDER_SOFTWARE);
5✔
660
  }
661

662
  @Override
663
  public Path getSoftwareExtraPath() {
664

665
    Path softwarePath = getSoftwarePath();
3✔
666
    if (softwarePath == null) {
2!
667
      return null;
×
668
    }
669
    return softwarePath.resolve(FOLDER_EXTRA);
4✔
670
  }
671

672
  @Override
673
  public Path getSoftwareRepositoryPath() {
674

675
    Path idePath = getIdePath();
3✔
676
    if (idePath == null) {
2!
677
      return null;
×
678
    }
679
    return idePath.resolve(FOLDER_SOFTWARE);
4✔
680
  }
681

682
  @Override
683
  public Path getPluginsPath() {
684

685
    return this.pluginsPath;
3✔
686
  }
687

688
  @Override
689
  public String getWorkspaceName() {
690

691
    return this.workspaceName;
3✔
692
  }
693

694
  @Override
695
  public Path getWorkspacesBasePath() {
696

697
    return this.workspacesBasePath;
3✔
698
  }
699

700
  @Override
701
  public Path getWorkspacePath() {
702

703
    return this.workspacePath;
3✔
704
  }
705

706
  @Override
707
  public Path getWorkspacePath(String workspace) {
708

709
    if (this.workspacesBasePath == null) {
3!
710
      throw new IllegalStateException("Failed to access workspace " + workspace + " without IDE_HOME in " + this.cwd);
×
711
    }
712
    return this.workspacesBasePath.resolve(workspace);
5✔
713
  }
714

715
  @Override
716
  public Path getDownloadPath() {
717

718
    return this.downloadPath;
3✔
719
  }
720

721
  @Override
722
  public Path getUrlsPath() {
723

724
    Path idePath = getIdePath();
3✔
725
    if (idePath == null) {
2!
726
      return null;
×
727
    }
728
    return idePath.resolve(FOLDER_URLS);
4✔
729
  }
730

731
  @Override
732
  public Path getToolRepositoryPath() {
733

734
    Path idePath = getIdePath();
3✔
735
    if (idePath == null) {
2!
736
      return null;
×
737
    }
738
    return idePath.resolve(FOLDER_SOFTWARE);
4✔
739
  }
740

741
  @Override
742
  public SystemPath getPath() {
743

744
    return this.path;
3✔
745
  }
746

747
  @Override
748
  public EnvironmentVariables getVariables() {
749

750
    if (this.variables == null) {
3✔
751
      this.variables = createVariables();
4✔
752
    }
753
    return this.variables;
3✔
754
  }
755

756
  @Override
757
  public UrlMetadata getUrls() {
758

759
    if (this.urlMetadata == null) {
3✔
760
      if (!isTest()) {
3!
761
        getGitContext().pullOrCloneAndResetIfNeeded(IDE_URLS_GIT, getUrlsPath(), null);
×
762
      }
763
      this.urlMetadata = new UrlMetadata(this);
6✔
764
    }
765
    return this.urlMetadata;
3✔
766
  }
767

768
  @Override
769
  public boolean isQuietMode() {
770

771
    return this.startContext.isQuietMode();
4✔
772
  }
773

774
  @Override
775
  public boolean isBatchMode() {
776

777
    return this.startContext.isBatchMode();
4✔
778
  }
779

780
  @Override
781
  public boolean isForceMode() {
782

783
    return this.startContext.isForceMode();
4✔
784
  }
785

786
  @Override
787
  public boolean isForcePull() {
788

789
    return this.startContext.isForcePull();
4✔
790
  }
791

792
  @Override
793
  public boolean isForcePlugins() {
794

795
    return this.startContext.isForcePlugins();
4✔
796
  }
797

798
  @Override
799
  public boolean isForceRepositories() {
800

801
    return this.startContext.isForceRepositories();
4✔
802
  }
803

804
  @Override
805
  public boolean isOfflineMode() {
806

807
    return this.startContext.isOfflineMode();
4✔
808
  }
809

810
  @Override
811
  public boolean isPrivacyMode() {
812
    return this.startContext.isPrivacyMode();
4✔
813
  }
814

815
  @Override
816
  public boolean isSkipUpdatesMode() {
817

818
    return this.startContext.isSkipUpdatesMode();
4✔
819
  }
820

821
  @Override
822
  public boolean isNoColorsMode() {
823

824
    return this.startContext.isNoColorsMode();
×
825
  }
826

827
  @Override
828
  public NetworkStatus getNetworkStatus() {
829

830
    if (this.networkStatus == null) {
×
831
      this.networkStatus = new NetworkStatusImpl(this);
×
832
    }
833
    return this.networkStatus;
×
834
  }
835

836
  @Override
837
  public Locale getLocale() {
838

839
    Locale locale = this.startContext.getLocale();
4✔
840
    if (locale == null) {
2✔
841
      locale = Locale.getDefault();
2✔
842
    }
843
    return locale;
2✔
844
  }
845

846
  @Override
847
  public DirectoryMerger getWorkspaceMerger() {
848

849
    if (this.workspaceMerger == null) {
3✔
850
      this.workspaceMerger = new DirectoryMerger(this);
6✔
851
    }
852
    return this.workspaceMerger;
3✔
853
  }
854

855
  /**
856
   * @return the default execution directory in which a command process is executed.
857
   */
858
  @Override
859
  public Path getDefaultExecutionDirectory() {
860

861
    return this.defaultExecutionDirectory;
×
862
  }
863

864
  /**
865
   * @param defaultExecutionDirectory new value of {@link #getDefaultExecutionDirectory()}.
866
   */
867
  public void setDefaultExecutionDirectory(Path defaultExecutionDirectory) {
868

869
    if (defaultExecutionDirectory != null) {
×
870
      this.defaultExecutionDirectory = defaultExecutionDirectory;
×
871
    }
872
  }
×
873

874
  @Override
875
  public GitContext getGitContext() {
876

877
    return new GitContextImpl(this);
×
878
  }
879

880
  @Override
881
  public ProcessContext newProcess() {
882

883
    ProcessContext processContext = createProcessContext();
3✔
884
    if (this.defaultExecutionDirectory != null) {
3!
885
      processContext.directory(this.defaultExecutionDirectory);
×
886
    }
887
    return processContext;
2✔
888
  }
889

890
  @Override
891
  public IdeSystem getSystem() {
892

893
    if (this.system == null) {
×
894
      this.system = new IdeSystemImpl();
×
895
    }
896
    return this.system;
×
897
  }
898

899
  /**
900
   * @return a new instance of {@link ProcessContext}.
901
   * @see #newProcess()
902
   */
903
  protected ProcessContext createProcessContext() {
904

905
    return new ProcessContextImpl(this);
×
906
  }
907

908
  @Override
909
  public IdeLogLevel getLogLevelConsole() {
910

911
    return this.startContext.getLogLevelConsole();
×
912
  }
913

914
  @Override
915
  public IdeLogLevel getLogLevelLogger() {
916

917
    return this.startContext.getLogLevelLogger();
×
918
  }
919

920
  @Override
921
  public IdeLogListener getLogListener() {
922

923
    return this.startContext.getLogListener();
×
924
  }
925

926
  @Override
927
  public void logIdeHomeAndRootStatus() {
928
    if (this.ideRoot != null) {
3!
929
      IdeLogLevel.SUCCESS.log(LOG, "IDE_ROOT is set to {}", this.ideRoot);
×
930
    }
931
    if (this.ideHome == null) {
3✔
932
      LOG.warn(getMessageNotInsideIdeProject());
5✔
933
    } else {
934
      IdeLogLevel.SUCCESS.log(LOG, "IDE_HOME is set to {}", this.ideHome);
11✔
935
    }
936
  }
1✔
937

938
  @Override
939
  public String formatArgument(Object argument) {
940

941
    if (argument == null) {
2✔
942
      return null;
2✔
943
    }
944
    String result = argument.toString();
3✔
945
    if (isPrivacyMode()) {
3✔
946
      if ((this.ideRoot != null) && this.privacyMap.isEmpty()) {
3!
947
        initializePrivacyMap(this.userHome, "~");
×
948
        String projectName = getProjectName();
×
949
        if (!projectName.isEmpty()) {
×
950
          this.privacyMap.put(projectName, "project");
×
951
        }
952
      }
953
      for (Entry<String, String> entry : this.privacyMap.entrySet()) {
8!
954
        result = result.replace(entry.getKey(), entry.getValue());
×
955
      }
×
956
      result = PrivacyUtil.removeSensitivePathInformation(result);
3✔
957
    }
958
    return result;
2✔
959
  }
960

961
  /**
962
   * @param path the sensitive {@link Path} to
963
   * @param replacement the replacement to mask the {@link Path} in log output.
964
   */
965
  protected void initializePrivacyMap(Path path, String replacement) {
966

967
    if (path == null) {
×
968
      return;
×
969
    }
970
    if (this.systemInfo.isWindows()) {
×
971
      this.privacyMap.put(WindowsPathSyntax.WINDOWS.format(path), replacement);
×
972
      this.privacyMap.put(WindowsPathSyntax.MSYS.format(path), replacement);
×
973
    } else {
974
      this.privacyMap.put(path.toString(), replacement);
×
975
    }
976
  }
×
977

978
  /**
979
   * Resets the privacy map in case fundamental values have changed.
980
   */
981
  private void resetPrivacyMap() {
982

983
    this.privacyMap.clear();
3✔
984
  }
1✔
985

986

987
  @Override
988
  public String askForInput(String message, String defaultValue) {
989

990
    while (true) {
991
      if (!message.isBlank()) {
3!
992
        IdeLogLevel.INTERACTION.log(LOG, message);
4✔
993
      }
994
      if (isBatchMode()) {
3!
995
        if (isForceMode()) {
×
996
          return defaultValue;
×
997
        } else {
998
          throw new CliAbortException();
×
999
        }
1000
      }
1001
      String input = readLine().trim();
4✔
1002
      if (!input.isEmpty()) {
3!
1003
        return input;
2✔
1004
      } else {
1005
        if (defaultValue != null) {
×
1006
          return defaultValue;
×
1007
        }
1008
      }
1009
    }
×
1010
  }
1011

1012
  @Override
1013
  public <O> O question(O[] options, String question, Object... args) {
1014

1015
    assert (options.length > 0);
4!
1016
    IdeLogLevel.INTERACTION.log(LOG, question, args);
5✔
1017
    return displayOptionsAndGetAnswer(options);
4✔
1018
  }
1019

1020
  private <O> O displayOptionsAndGetAnswer(O[] options) {
1021
    Map<String, O> mapping = new HashMap<>(options.length);
6✔
1022
    int i = 0;
2✔
1023
    for (O option : options) {
16✔
1024
      i++;
1✔
1025
      String title = "" + option;
4✔
1026
      String key = computeOptionKey(title);
3✔
1027
      addMapping(mapping, key, option);
4✔
1028
      String numericKey = Integer.toString(i);
3✔
1029
      if (numericKey.equals(key)) {
4!
1030
        LOG.trace("Options should not be numeric: {}", key);
×
1031
      } else {
1032
        addMapping(mapping, numericKey, option);
4✔
1033
      }
1034
      IdeLogLevel.INTERACTION.log(LOG, "Option {}: {}", numericKey, title);
14✔
1035
    }
1036
    O option = null;
2✔
1037
    if (isBatchMode()) {
3!
1038
      if (isForceMode()) {
×
1039
        option = options[0];
×
1040
        IdeLogLevel.INTERACTION.log(LOG, "" + option);
×
1041
      }
1042
    } else {
1043
      while (option == null) {
2✔
1044
        String answer = readLine();
3✔
1045
        option = mapping.get(answer);
4✔
1046
        if (option == null) {
2!
1047
          LOG.warn("Invalid answer: '{}' - please try again.", answer);
×
1048
        }
1049
      }
1✔
1050
    }
1051
    return option;
2✔
1052
  }
1053

1054
  private static String computeOptionKey(String option) {
1055
    String key = option;
2✔
1056
    int index = -1;
2✔
1057
    for (char c : OPTION_DETAILS_START.toCharArray()) {
17✔
1058
      int currentIndex = key.indexOf(c);
4✔
1059
      if (currentIndex != -1) {
3✔
1060
        if ((index == -1) || (currentIndex < index)) {
3!
1061
          index = currentIndex;
2✔
1062
        }
1063
      }
1064
    }
1065
    if (index > 0) {
2✔
1066
      key = key.substring(0, index).trim();
6✔
1067
    }
1068
    return key;
2✔
1069
  }
1070

1071
  /**
1072
   * @return the input from the end-user (e.g. read from the console).
1073
   */
1074
  protected abstract String readLine();
1075

1076
  private static <O> void addMapping(Map<String, O> mapping, String key, O option) {
1077

1078
    O duplicate = mapping.put(key, option);
5✔
1079
    if (duplicate != null) {
2!
1080
      throw new IllegalArgumentException("Duplicated option " + key);
×
1081
    }
1082
  }
1✔
1083

1084
  @Override
1085
  public Step getCurrentStep() {
1086

1087
    return this.currentStep;
×
1088
  }
1089

1090
  @Override
1091
  public StepImpl newStep(boolean silent, String name, Object... parameters) {
1092

1093
    this.currentStep = new StepImpl(this, this.currentStep, name, silent, parameters);
11✔
1094
    return this.currentStep;
3✔
1095
  }
1096

1097
  /**
1098
   * Internal method to end the running {@link Step}.
1099
   *
1100
   * @param step the current {@link Step} to end.
1101
   */
1102
  public void endStep(StepImpl step) {
1103

1104
    if (step == this.currentStep) {
4!
1105
      this.currentStep = this.currentStep.getParent();
6✔
1106
    } else {
1107
      String currentStepName = "null";
×
1108
      if (this.currentStep != null) {
×
1109
        currentStepName = this.currentStep.getName();
×
1110
      }
1111
      LOG.warn("endStep called with wrong step '{}' but expected '{}'", step.getName(), currentStepName);
×
1112
    }
1113
  }
1✔
1114

1115
  /**
1116
   * Finds the matching {@link Commandlet} to run, applies {@link CliArguments} to its {@link Commandlet#getProperties() properties} and will execute it.
1117
   *
1118
   * @param arguments the {@link CliArgument}.
1119
   * @return the return code of the execution.
1120
   */
1121
  public int run(CliArguments arguments) {
1122

1123
    CliArgument current = arguments.current();
3✔
1124
    assert (this.currentStep == null);
4!
1125
    boolean supressStepSuccess = false;
2✔
1126
    StepImpl step = newStep(true, "ide", (Object[]) current.asArray());
8✔
1127
    Iterator<Commandlet> commandletIterator = this.commandletManager.findCommandlet(arguments, null);
6✔
1128
    Commandlet cmd = null;
2✔
1129
    ValidationResult result = null;
2✔
1130
    try {
1131
      while (commandletIterator.hasNext()) {
3✔
1132
        cmd = commandletIterator.next();
4✔
1133
        result = applyAndRun(arguments.copy(), cmd);
6✔
1134
        if (result.isValid()) {
3!
1135
          supressStepSuccess = cmd.isSuppressStepSuccess();
3✔
1136
          step.success();
2✔
1137
          return ProcessResult.SUCCESS;
4✔
1138
        }
1139
      }
1140
      activateLogging(cmd);
3✔
1141
      verifyIdeMinVersion(false);
3✔
1142
      if (result != null) {
2!
1143
        LOG.error(result.getErrorMessage());
×
1144
      }
1145
      step.error("Invalid arguments: {}", current.getArgs());
10✔
1146
      IdeLogLevel.INTERACTION.log(LOG, "For additional details run ide help {}", cmd == null ? "" : cmd.getName());
13!
1147
      return 1;
4✔
1148
    } catch (Throwable t) {
1✔
1149
      activateLogging(cmd);
3✔
1150
      step.error(t, true);
4✔
1151
      if (this.logfile != null) {
3!
1152
        System.err.println("Logfile can be found at " + this.logfile); // do not use logger
×
1153
      }
1154
      throw t;
2✔
1155
    } finally {
1156
      step.close();
2✔
1157
      assert (this.currentStep == null);
4!
1158
      step.logSummary(supressStepSuccess);
3✔
1159
    }
1160
  }
1161

1162
  /**
1163
   * Ensure the logging system is initialized.
1164
   */
1165
  private void activateLogging(Commandlet cmd) {
1166

1167
    configureJavaUtilLogging(cmd);
3✔
1168
    this.startContext.activateLogging();
3✔
1169
  }
1✔
1170

1171
  /**
1172
   * Configures the logging system (JUL).
1173
   *
1174
   * @param cmd the {@link Commandlet} to be called. May be {@code null}.
1175
   */
1176
  public void configureJavaUtilLogging(Commandlet cmd) {
1177

1178
    if (this.julConfigured) {
3✔
1179
      return;
1✔
1180
    }
1181
    boolean writeLogfile = isWriteLogfile(cmd);
4✔
1182
    this.startContext.setWriteLogfile(writeLogfile);
4✔
1183
    Properties properties = createJavaUtilLoggingProperties(writeLogfile, cmd);
5✔
1184
    try {
1185
      ByteArrayOutputStream out = new ByteArrayOutputStream(512);
5✔
1186
      properties.store(out, null);
4✔
1187
      out.flush();
2✔
1188
      ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
6✔
1189
      LogManager.getLogManager().readConfiguration(in);
3✔
1190
      this.julConfigured = true;
3✔
1191
      this.startContext.activateLogging();
3✔
1192
    } catch (IOException e) {
×
1193
      LOG.error("Failed to configure logging: {}", e.toString(), e);
×
1194
    }
1✔
1195
  }
1✔
1196

1197
  protected boolean isWriteLogfile(Commandlet cmd) {
1198
    if ((cmd == null) || !cmd.isWriteLogFile()) {
×
1199
      return false;
×
1200
    }
1201
    Boolean writeLogfile = IdeVariables.IDE_WRITE_LOGFILE.get(this);
×
1202
    return Boolean.TRUE.equals(writeLogfile);
×
1203
  }
1204

1205
  private Properties createJavaUtilLoggingProperties(boolean writeLogfile, Commandlet cmd) {
1206

1207
    Path idePath = getIdePath();
3✔
1208
    if (writeLogfile && (idePath == null)) {
2!
1209
      writeLogfile = false;
×
1210
      LOG.error("Cannot enable log-file since IDE_ROOT is undefined.");
×
1211
    }
1212
    Properties properties = new Properties();
4✔
1213
    // prevent 3rd party (e.g. java.lang.ProcessBuilder) logging into our console via JUL
1214
    // see JulLogLevel for the trick we did to workaround JUL flaws
1215
    properties.setProperty(".level", "SEVERE");
5✔
1216
    if (writeLogfile) {
2!
1217
      this.startContext.setLogLevelLogger(IdeLogLevel.TRACE);
×
1218
      String fileHandlerName = FileHandler.class.getName();
×
1219
      properties.setProperty("handlers", JulConsoleHandler.class.getName() + "," + fileHandlerName);
×
1220
      properties.setProperty(fileHandlerName + ".formatter", SimpleFormatter.class.getName());
×
1221
      properties.setProperty(fileHandlerName + ".encoding", "UTF-8");
×
1222
      this.logfile = createLogfilePath(idePath, cmd);
×
1223
      getFileAccess().mkdirs(this.logfile.getParent());
×
1224
      properties.setProperty(fileHandlerName + ".pattern", this.logfile.toString());
×
1225
    } else {
×
1226
      properties.setProperty("handlers", JulConsoleHandler.class.getName());
6✔
1227
    }
1228
    properties.setProperty(SimpleFormatter.class.getName() + ".format", "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS.%1$tL [%4$s] [%3$s] %5$s%6$s%n");
7✔
1229
    return properties;
2✔
1230
  }
1231

1232
  private Path createLogfilePath(Path idePath, Commandlet cmd) {
1233
    LocalDateTime now = LocalDateTime.now();
×
1234
    Path logsPath = idePath.resolve(FOLDER_LOGS).resolve(DateTimeUtil.formatDate(now, true));
×
1235
    StringBuilder sb = new StringBuilder(32);
×
1236
    if (this.ideHome == null || ((cmd != null) && !cmd.isIdeHomeRequired())) {
×
1237
      sb.append("_ide-");
×
1238
    } else {
1239
      sb.append(this.ideHome.getFileName().toString());
×
1240
      sb.append('-');
×
1241
    }
1242
    sb.append("ide-");
×
1243
    if (cmd != null) {
×
1244
      sb.append(cmd.getName());
×
1245
      sb.append('-');
×
1246
    }
1247
    sb.append(DateTimeUtil.formatTime(now));
×
1248
    sb.append(".log");
×
1249
    return logsPath.resolve(sb.toString());
×
1250
  }
1251

1252
  @Override
1253
  public void runWithoutLogging(Runnable lambda, IdeLogLevel threshold) {
1254

1255
    this.startContext.deactivateLogging(threshold);
4✔
1256
    lambda.run();
2✔
1257
    this.startContext.activateLogging();
3✔
1258
  }
1✔
1259

1260
  /**
1261
   * @param cmd the potential {@link Commandlet} to {@link #apply(CliArguments, Commandlet) apply} and {@link Commandlet#run() run}.
1262
   * @return {@code true} if the given {@link Commandlet} matched and did {@link Commandlet#run() run} successfully, {@code false} otherwise (the
1263
   *     {@link Commandlet} did not match and we have to try a different candidate).
1264
   */
1265
  private ValidationResult applyAndRun(CliArguments arguments, Commandlet cmd) {
1266

1267
    IdeLogLevel previousLogLevel = null;
2✔
1268
    cmd.reset();
2✔
1269
    ValidationResult result = apply(arguments, cmd);
5✔
1270
    if (result.isValid()) {
3!
1271
      result = cmd.validate();
3✔
1272
    }
1273
    if (result.isValid()) {
3!
1274
      LOG.debug("Running commandlet {}", cmd);
4✔
1275
      if (cmd.isIdeHomeRequired() && (this.ideHome == null)) {
6!
1276
        throw new CliException(getMessageNotInsideIdeProject(), ProcessResult.NO_IDE_HOME);
×
1277
      } else if (cmd.isIdeRootRequired() && (this.ideRoot == null)) {
6!
1278
        throw new CliException(getMessageIdeRootNotFound(), ProcessResult.NO_IDE_ROOT);
7✔
1279
      }
1280
      try {
1281
        if (cmd.isProcessableOutput()) {
3!
1282
          if (!LOG.isDebugEnabled()) {
×
1283
            // unless --debug or --trace was supplied, processable output commandlets will disable all log-levels except INFO to prevent other logs interfere
1284
            previousLogLevel = this.startContext.setLogLevelConsole(IdeLogLevel.PROCESSABLE);
×
1285
          }
1286
        } else {
1287
          if (cmd.isIdeHomeRequired()) {
3!
1288
            LOG.debug(getMessageIdeHomeFound());
4✔
1289
          }
1290
          Path settingsRepository = getSettingsGitRepository();
3✔
1291
          if (settingsRepository != null) {
2!
1292
            if (getGitContext().isRepositoryUpdateAvailable(settingsRepository, getSettingsCommitIdPath()) || (
×
1293
                getGitContext().fetchIfNeeded(settingsRepository) && getGitContext().isRepositoryUpdateAvailable(
×
1294
                    settingsRepository, getSettingsCommitIdPath()))) {
×
1295
              String msg;
1296
              if (isSettingsRepositorySymlinkOrJunction()) {
×
1297
                msg = "Updates are available for the settings repository. Please pull the latest changes by yourself or by calling \"ide -f update\" to apply them.";
×
1298
              } else {
1299
                msg = "Updates are available for the settings repository. If you want to apply the latest changes, call \"ide update\"";
×
1300
              }
1301
              IdeLogLevel.INTERACTION.log(LOG, msg);
×
1302
            }
1303
          }
1304
        }
1305
        boolean success = ensureLicenseAgreement(cmd);
4✔
1306
        if (!success) {
2!
1307
          return ValidationResultValid.get();
×
1308
        }
1309
        cmd.run();
2✔
1310
      } finally {
1311
        if (previousLogLevel != null) {
2!
1312
          this.startContext.setLogLevelConsole(previousLogLevel);
×
1313
        }
1314
      }
1✔
1315
    } else {
1316
      LOG.trace("Commandlet did not match");
×
1317
    }
1318
    return result;
2✔
1319
  }
1320

1321
  private boolean ensureLicenseAgreement(Commandlet cmd) {
1322

1323
    if (isTest()) {
3!
1324
      return true; // ignore for tests
2✔
1325
    }
1326
    getFileAccess().mkdirs(this.userHomeIde);
×
1327
    Path licenseAgreement = this.userHomeIde.resolve(FILE_LICENSE_AGREEMENT);
×
1328
    if (Files.isRegularFile(licenseAgreement)) {
×
1329
      return true; // success, license already accepted
×
1330
    }
1331
    if (cmd instanceof EnvironmentCommandlet) {
×
1332
      // if the license was not accepted, "$(ideasy env --bash)" that is written into a variable prevents the user from seeing the question he is asked
1333
      // in such situation the user could not open a bash terminal anymore and gets blocked what would really annoy the user so we exit here without doing or
1334
      // printing anything anymore in such case.
1335
      return false;
×
1336
    }
1337
    activateLogging(cmd);
×
1338
    IdeLogLevel oldLogLevel = this.startContext.getLogLevelConsole();
×
1339
    IdeLogLevel newLogLevel = oldLogLevel;
×
1340
    if (oldLogLevel.ordinal() > IdeLogLevel.INFO.ordinal()) {
×
1341
      newLogLevel = IdeLogLevel.INFO;
×
1342
      this.startContext.setLogLevelConsole(newLogLevel);
×
1343
    }
1344
    StringBuilder sb = new StringBuilder(1180);
×
1345
    sb.append(LOGO).append("""
×
1346
        Welcome to IDEasy!
1347
        This product (with its included 3rd party components) is open-source software and can be used free (also commercially).
1348
        It supports automatic download and installation of arbitrary 3rd party tools.
1349
        By default only open-source 3rd party tools are used (downloaded, installed, executed).
1350
        But if explicitly configured, also commercial software that requires an additional license may be used.
1351
        This happens e.g. if you configure "ultimate" edition of IntelliJ or "docker" edition of Docker (Docker Desktop).
1352
        You are solely responsible for all risks implied by using this software.
1353
        Before using IDEasy you need to read and accept the license agreement with all involved licenses.
1354
        You will be able to find it online under the following URL:
1355
        """).append(LICENSE_URL);
×
1356
    if (this.ideRoot != null) {
×
1357
      sb.append("\n\nAlso it is included in the documentation that you can find here:\n").
×
1358
          append(getIdePath().resolve("IDEasy.pdf").toString()).append("\n");
×
1359
    }
1360
    LOG.info(sb.toString());
×
1361
    askToContinue("Do you accept these terms of use and all license agreements?");
×
1362

1363
    sb.setLength(0);
×
1364
    LocalDateTime now = LocalDateTime.now();
×
1365
    sb.append("On ").append(DateTimeUtil.formatDate(now, false)).append(" at ").append(DateTimeUtil.formatTime(now))
×
1366
        .append(" you accepted the IDEasy license.\n").append(LICENSE_URL);
×
1367
    try {
1368
      Files.writeString(licenseAgreement, sb);
×
1369
    } catch (Exception e) {
×
1370
      throw new RuntimeException("Failed to save license agreement!", e);
×
1371
    }
×
1372
    if (oldLogLevel != newLogLevel) {
×
1373
      this.startContext.setLogLevelConsole(oldLogLevel);
×
1374
    }
1375
    return true;
×
1376
  }
1377

1378
  @Override
1379
  public void verifyIdeMinVersion(boolean throwException) {
1380
    VersionIdentifier minVersion = IDE_MIN_VERSION.get(this);
5✔
1381
    if (minVersion == null) {
2✔
1382
      return;
1✔
1383
    }
1384
    VersionIdentifier versionIdentifier = IdeVersion.getVersionIdentifier();
2✔
1385
    if (versionIdentifier.compareVersion(minVersion).isLess() && !IdeVersion.isUndefined()) {
7!
1386
      String message = String.format("Your version of IDEasy is currently %s\n"
13✔
1387
          + "However, this is too old as your project requires at latest version %s\n"
1388
          + "Please run the following command to update to the latest version of IDEasy and fix the problem:\n"
1389
          + "ide upgrade", versionIdentifier, minVersion);
1390
      if (throwException) {
2✔
1391
        throw new CliException(message);
5✔
1392
      } else {
1393
        LOG.warn(message);
3✔
1394
      }
1395
    }
1396
  }
1✔
1397

1398
  /**
1399
   * @param arguments the {@link CliArguments#ofCompletion(String...) completion arguments}.
1400
   * @param includeContextOptions to include the options of {@link ContextCommandlet}.
1401
   * @return the {@link List} of {@link CompletionCandidate}s to suggest.
1402
   */
1403
  public List<CompletionCandidate> complete(CliArguments arguments, boolean includeContextOptions) {
1404

1405
    CompletionCandidateCollector collector = new CompletionCandidateCollectorDefault(this);
5✔
1406
    if (arguments.current().isStart()) {
4✔
1407
      arguments.next();
3✔
1408
    }
1409
    if (includeContextOptions) {
2✔
1410
      ContextCommandlet cc = new ContextCommandlet();
4✔
1411
      for (Property<?> property : cc.getProperties()) {
11✔
1412
        assert (property.isOption());
4!
1413
        property.apply(arguments, this, cc, collector);
7✔
1414
      }
1✔
1415
    }
1416
    Iterator<Commandlet> commandletIterator = this.commandletManager.findCommandlet(arguments, collector);
6✔
1417
    CliArgument current = arguments.current();
3✔
1418
    if (current.isCompletion() && current.isCombinedShortOption()) {
6✔
1419
      collector.add(current.get(), null, null, null);
7✔
1420
    }
1421
    arguments.next();
3✔
1422
    while (commandletIterator.hasNext()) {
3✔
1423
      Commandlet cmd = commandletIterator.next();
4✔
1424
      if (!arguments.current().isEnd()) {
4✔
1425
        completeCommandlet(arguments.copy(), cmd, collector);
6✔
1426
      }
1427
    }
1✔
1428
    return collector.getSortedCandidates();
3✔
1429
  }
1430

1431
  private void completeCommandlet(CliArguments arguments, Commandlet cmd, CompletionCandidateCollector collector) {
1432

1433
    LOG.trace("Trying to match arguments for auto-completion for commandlet {}", cmd.getName());
5✔
1434
    Iterator<Property<?>> valueIterator = cmd.getValues().iterator();
4✔
1435
    valueIterator.next(); // skip first property since this is the keyword property that already matched to find the commandlet
3✔
1436
    List<Property<?>> properties = cmd.getProperties();
3✔
1437
    // we are creating our own list of options and remove them when matched to avoid duplicate suggestions
1438
    List<Property<?>> optionProperties = new ArrayList<>(properties.size());
6✔
1439
    for (Property<?> property : properties) {
10✔
1440
      if (property.isOption()) {
3✔
1441
        optionProperties.add(property);
4✔
1442
      }
1443
    }
1✔
1444
    CliArgument currentArgument = arguments.current();
3✔
1445
    while (!currentArgument.isEnd()) {
3✔
1446
      LOG.trace("Trying to match argument '{}'", currentArgument);
4✔
1447
      if (currentArgument.isOption() && !arguments.isEndOptions()) {
6!
1448
        if (currentArgument.isCompletion()) {
3✔
1449
          Iterator<Property<?>> optionIterator = optionProperties.iterator();
3✔
1450
          while (optionIterator.hasNext()) {
3✔
1451
            Property<?> option = optionIterator.next();
4✔
1452
            boolean success = option.apply(arguments, this, cmd, collector);
7✔
1453
            if (success) {
2✔
1454
              optionIterator.remove();
2✔
1455
              arguments.next();
3✔
1456
            }
1457
          }
1✔
1458
        } else {
1✔
1459
          Property<?> option = cmd.getOption(currentArgument.get());
5✔
1460
          if (option != null) {
2✔
1461
            arguments.next();
3✔
1462
            boolean removed = optionProperties.remove(option);
4✔
1463
            if (!removed) {
2!
1464
              option = null;
×
1465
            }
1466
          }
1467
          if (option == null) {
2✔
1468
            LOG.trace("No such option was found.");
3✔
1469
            return;
1✔
1470
          }
1471
        }
1✔
1472
      } else {
1473
        if (valueIterator.hasNext()) {
3✔
1474
          Property<?> valueProperty = valueIterator.next();
4✔
1475
          boolean success = valueProperty.apply(arguments, this, cmd, collector);
7✔
1476
          if (!success) {
2✔
1477
            LOG.trace("Completion cannot match any further.");
3✔
1478
            return;
1✔
1479
          }
1480
        } else {
1✔
1481
          LOG.trace("No value left for completion.");
3✔
1482
          return;
1✔
1483
        }
1484
      }
1485
      currentArgument = arguments.current();
4✔
1486
    }
1487
  }
1✔
1488

1489
  /**
1490
   * @param arguments the {@link CliArguments} to apply. Will be {@link CliArguments#next() consumed} as they are matched. Consider passing a
1491
   *     {@link CliArguments#copy() copy} as needed.
1492
   * @param cmd the potential {@link Commandlet} to match.
1493
   * @return the {@link ValidationResult} telling if the {@link CliArguments} can be applied successfully or if validation errors ocurred.
1494
   */
1495
  public ValidationResult apply(CliArguments arguments, Commandlet cmd) {
1496

1497
    LOG.trace("Trying to match arguments to commandlet {}", cmd.getName());
5✔
1498
    CliArgument currentArgument = arguments.current();
3✔
1499
    Iterator<Property<?>> propertyIterator = cmd.getValues().iterator();
4✔
1500
    Property<?> property = null;
2✔
1501
    if (propertyIterator.hasNext()) {
3!
1502
      property = propertyIterator.next();
4✔
1503
    }
1504
    while (!currentArgument.isEnd()) {
3✔
1505
      LOG.trace("Trying to match argument '{}'", currentArgument);
4✔
1506
      Property<?> currentProperty = property;
2✔
1507
      if (!arguments.isEndOptions()) {
3!
1508
        Property<?> option = cmd.getOption(currentArgument.getKey());
5✔
1509
        if (option != null) {
2!
1510
          currentProperty = option;
×
1511
        }
1512
      }
1513
      if (currentProperty == null) {
2!
1514
        LOG.trace("No option or next value found");
×
1515
        ValidationState state = new ValidationState(null);
×
1516
        state.addErrorMessage("No matching property found");
×
1517
        return state;
×
1518
      }
1519
      LOG.trace("Next property candidate to match argument is {}", currentProperty);
4✔
1520
      if (currentProperty == property) {
3!
1521
        if (!property.isMultiValued()) {
3✔
1522
          if (propertyIterator.hasNext()) {
3✔
1523
            property = propertyIterator.next();
5✔
1524
          } else {
1525
            property = null;
2✔
1526
          }
1527
        }
1528
        if ((property != null) && property.isValue() && property.isMultiValued()) {
8!
1529
          arguments.stopSplitShortOptions();
2✔
1530
        }
1531
      }
1532
      boolean matches = currentProperty.apply(arguments, this, cmd, null);
7✔
1533
      if (!matches) {
2!
1534
        ValidationState state = new ValidationState(null);
×
1535
        state.addErrorMessage("No matching property found");
×
1536
        return state;
×
1537
      }
1538
      currentArgument = arguments.current();
3✔
1539
    }
1✔
1540
    return ValidationResultValid.get();
2✔
1541
  }
1542

1543
  @Override
1544
  public Path findBash() {
1545
    if (this.bash != null) {
3✔
1546
      return this.bash;
3✔
1547
    }
1548
    Path bashPath = findBashOnBashPath();
3✔
1549
    if (bashPath == null) {
2✔
1550
      bashPath = findBashInPath();
3✔
1551
      if (bashPath == null && (getSystemInfo().isWindows() || SystemInfoImpl.INSTANCE.isWindows())) {
6!
1552
        bashPath = findBashOnWindowsDefaultGitPath();
3✔
1553
        if (bashPath == null) {
2!
1554
          bashPath = findBashInWindowsRegistry();
3✔
1555
        }
1556
      }
1557
    }
1558
    if (bashPath == null) {
2✔
1559
      LOG.error("No bash executable could be found on your system.");
4✔
1560
    } else {
1561
      this.bash = bashPath;
3✔
1562
    }
1563
    return bashPath;
2✔
1564
  }
1565

1566
  private Path findBashOnBashPath() {
1567
    LOG.trace("Trying to find BASH_PATH environment variable.");
3✔
1568
    Path bash;
1569
    String bashPathVariableName = IdeVariables.BASH_PATH.getName();
3✔
1570
    String bashVariable = getVariables().get(bashPathVariableName);
5✔
1571
    if (bashVariable != null) {
2✔
1572
      bash = Path.of(bashVariable);
5✔
1573
      if (Files.exists(bash)) {
5✔
1574
        LOG.debug("{} environment variable was found and points to: {}", bashPathVariableName, bash);
5✔
1575
        return bash;
2✔
1576
      } else {
1577
        LOG.error("The environment variable {} points to a non existing file: {}", bashPathVariableName, bash);
5✔
1578
        return null;
2✔
1579
      }
1580
    } else {
1581
      LOG.debug("{} environment variable was not found", bashPathVariableName);
4✔
1582
      return null;
2✔
1583
    }
1584
  }
1585

1586
  /**
1587
   * @param path the path to check.
1588
   * @param toIgnore the String sequence which needs to be checked and ignored.
1589
   * @return {@code true} if the sequence to ignore was not found, {@code false} if the path contained the sequence to ignore.
1590
   */
1591
  private boolean checkPathToIgnoreLowercase(Path path, String toIgnore) {
1592
    String s = path.toAbsolutePath().toString().toLowerCase(Locale.ROOT);
6✔
1593
    return !s.contains(toIgnore);
7!
1594
  }
1595

1596
  /**
1597
   * Tries to find the bash.exe within the PATH environment variable.
1598
   *
1599
   * @return Path to bash.exe if found in PATH environment variable, {@code null} if bash.exe was not found.
1600
   */
1601
  private Path findBashInPath() {
1602
    LOG.trace("Trying to find bash in PATH environment variable.");
3✔
1603
    Path bash;
1604
    String pathVariableName = IdeVariables.PATH.getName();
3✔
1605
    if (pathVariableName != null) {
2!
1606
      Path plainBash = Path.of(BASH);
5✔
1607
      Predicate<Path> pathsToIgnore = p -> checkPathToIgnoreLowercase(p, "\\appdata\\local\\microsoft\\windowsapps") && checkPathToIgnoreLowercase(p,
16!
1608
          "\\windows\\system32");
1609
      Path bashPath = getPath().findBinary(plainBash, pathsToIgnore);
6✔
1610
      bash = bashPath.toAbsolutePath();
3✔
1611
      if (bashPath.equals(plainBash)) {
4✔
1612
        LOG.warn("No usable bash executable was found in your PATH environment variable!");
3✔
1613
        bash = null;
3✔
1614
      } else {
1615
        if (Files.exists(bashPath)) {
5!
1616
          LOG.debug("A proper bash executable was found in your PATH environment variable at: {}", bash);
5✔
1617
        } else {
1618
          bash = null;
×
1619
          LOG.error("A path to a bash executable was found in your PATH environment variable at: {} but the file is not existing.", bash);
×
1620
        }
1621
      }
1622
    } else {
1✔
1623
      bash = null;
×
1624
      // this should never happen...
1625
      LOG.error("PATH environment variable was not found");
×
1626
    }
1627
    return bash;
2✔
1628
  }
1629

1630
  /**
1631
   * Tries to find the bash.exe within the Windows registry.
1632
   *
1633
   * @return Path to bash.exe if found in registry, {@code null} if bash.exe was found.
1634
   */
1635
  protected Path findBashInWindowsRegistry() {
1636
    LOG.trace("Trying to find bash in Windows registry");
×
1637
    // If not found in the default location, try the registry query
1638
    String[] bashVariants = { "GitForWindows", "Cygwin\\setup" };
×
1639
    String[] registryKeys = { "HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER" };
×
1640
    for (String bashVariant : bashVariants) {
×
1641
      LOG.trace("Trying to find bash variant: {}", bashVariant);
×
1642
      for (String registryKey : registryKeys) {
×
1643
        LOG.trace("Trying to find bash from registry key: {}", registryKey);
×
1644
        String toolValueName = ("GitForWindows".equals(bashVariant)) ? "InstallPath" : "rootdir";
×
1645
        String registryPath = registryKey + "\\Software\\" + bashVariant;
×
1646

1647
        String path = getWindowsHelper().getRegistryValue(registryPath, toolValueName);
×
1648
        if (path != null) {
×
1649
          Path bashPath = Path.of(path + "\\bin\\bash.exe");
×
1650
          if (Files.exists(bashPath)) {
×
1651
            LOG.debug("Found bash at: {}", bashPath);
×
1652
            return bashPath;
×
1653
          } else {
1654
            LOG.error("Found bash at: {} but it is not pointing to an existing file", bashPath);
×
1655
            return null;
×
1656
          }
1657
        } else {
1658
          LOG.info("No bash executable could be found in the Windows registry.");
×
1659
        }
1660
      }
1661
    }
1662
    // no bash found
1663
    return null;
×
1664
  }
1665

1666
  private Path findBashOnWindowsDefaultGitPath() {
1667
    // Check if Git Bash exists in the default location
1668
    LOG.trace("Trying to find bash on the Windows default git path.");
3✔
1669
    Path defaultPath = Path.of(getDefaultWindowsGitPath());
6✔
1670
    if (!defaultPath.toString().isEmpty() && Files.exists(defaultPath)) {
4!
1671
      LOG.trace("Found default path to git bash on Windows at: {}", getDefaultWindowsGitPath());
×
1672
      return defaultPath;
×
1673
    }
1674
    LOG.debug("No bash was found on the Windows default git path.");
3✔
1675
    return null;
2✔
1676
  }
1677

1678
  @Override
1679
  public WindowsPathSyntax getPathSyntax() {
1680

1681
    return this.pathSyntax;
3✔
1682
  }
1683

1684
  /**
1685
   * @param pathSyntax new value of {@link #getPathSyntax()}.
1686
   */
1687
  public void setPathSyntax(WindowsPathSyntax pathSyntax) {
1688

1689
    this.pathSyntax = pathSyntax;
3✔
1690
  }
1✔
1691

1692
  /**
1693
   * @return the {@link IdeStartContextImpl}.
1694
   */
1695
  public IdeStartContextImpl getStartContext() {
1696

1697
    return startContext;
3✔
1698
  }
1699

1700
  /**
1701
   * @return the {@link WindowsHelper}.
1702
   */
1703
  public final WindowsHelper getWindowsHelper() {
1704

1705
    if (this.windowsHelper == null) {
3✔
1706
      this.windowsHelper = createWindowsHelper();
4✔
1707
    }
1708
    return this.windowsHelper;
3✔
1709
  }
1710

1711
  /**
1712
   * @return the new {@link WindowsHelper} instance.
1713
   */
1714
  protected WindowsHelper createWindowsHelper() {
1715

1716
    return new WindowsHelperImpl(this);
×
1717
  }
1718

1719
  /**
1720
   * Reloads this context and re-initializes the {@link #getVariables() variables}.
1721
   */
1722
  public void reload() {
1723

1724
    this.variables = null;
3✔
1725
    this.customToolRepository = null;
3✔
1726
  }
1✔
1727

1728
  @Override
1729
  public void writeVersionFile(VersionIdentifier version, Path installationPath) {
1730

1731
    assert (Files.isDirectory(installationPath));
6!
1732
    Path versionFile = installationPath.resolve(FILE_SOFTWARE_VERSION);
4✔
1733
    getFileAccess().writeFileContent(version.toString(), versionFile);
6✔
1734
  }
1✔
1735

1736
  /*
1737
   * @param home the IDE_HOME directory.
1738
   * @param workspace the name of the active workspace folder.
1739
   */
1740
  protected static record IdeHomeAndWorkspace(Path home, String workspace) {
9✔
1741

1742
  }
1743

1744
  /**
1745
   * Returns the default git path on Windows. Required to be overwritten in tests.
1746
   *
1747
   * @return default path to git on Windows.
1748
   */
1749
  public String getDefaultWindowsGitPath() {
1750
    return DEFAULT_WINDOWS_GIT_PATH;
×
1751
  }
1752

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