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

devonfw / IDEasy / 11114187270

30 Sep 2024 09:09PM UTC coverage: 66.525% (+0.4%) from 66.105%
11114187270

push

github

web-flow
#657: fix installation of java 8 (#658)

2328 of 3842 branches covered (60.59%)

Branch coverage included in aggregate %.

6116 of 8851 relevant lines covered (69.1%)

3.05 hits per line

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

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

3
import java.io.BufferedReader;
4
import java.io.InputStreamReader;
5
import java.net.URL;
6
import java.net.URLConnection;
7
import java.nio.file.Files;
8
import java.nio.file.Path;
9
import java.util.HashMap;
10
import java.util.Iterator;
11
import java.util.List;
12
import java.util.Locale;
13
import java.util.Map;
14

15
import com.devonfw.tools.ide.cli.CliAbortException;
16
import com.devonfw.tools.ide.cli.CliArgument;
17
import com.devonfw.tools.ide.cli.CliArguments;
18
import com.devonfw.tools.ide.cli.CliException;
19
import com.devonfw.tools.ide.commandlet.Commandlet;
20
import com.devonfw.tools.ide.commandlet.CommandletManager;
21
import com.devonfw.tools.ide.commandlet.CommandletManagerImpl;
22
import com.devonfw.tools.ide.commandlet.ContextCommandlet;
23
import com.devonfw.tools.ide.commandlet.HelpCommandlet;
24
import com.devonfw.tools.ide.common.SystemPath;
25
import com.devonfw.tools.ide.completion.CompletionCandidate;
26
import com.devonfw.tools.ide.completion.CompletionCandidateCollector;
27
import com.devonfw.tools.ide.completion.CompletionCandidateCollectorDefault;
28
import com.devonfw.tools.ide.environment.AbstractEnvironmentVariables;
29
import com.devonfw.tools.ide.environment.EnvironmentVariables;
30
import com.devonfw.tools.ide.environment.EnvironmentVariablesType;
31
import com.devonfw.tools.ide.io.FileAccess;
32
import com.devonfw.tools.ide.io.FileAccessImpl;
33
import com.devonfw.tools.ide.log.IdeLogLevel;
34
import com.devonfw.tools.ide.log.IdeLogger;
35
import com.devonfw.tools.ide.log.IdeSubLogger;
36
import com.devonfw.tools.ide.merge.DirectoryMerger;
37
import com.devonfw.tools.ide.network.ProxyContext;
38
import com.devonfw.tools.ide.os.SystemInfo;
39
import com.devonfw.tools.ide.os.SystemInfoImpl;
40
import com.devonfw.tools.ide.os.WindowsPathSyntax;
41
import com.devonfw.tools.ide.process.ProcessContext;
42
import com.devonfw.tools.ide.process.ProcessContextImpl;
43
import com.devonfw.tools.ide.process.ProcessResult;
44
import com.devonfw.tools.ide.property.Property;
45
import com.devonfw.tools.ide.repo.CustomToolRepository;
46
import com.devonfw.tools.ide.repo.CustomToolRepositoryImpl;
47
import com.devonfw.tools.ide.repo.DefaultToolRepository;
48
import com.devonfw.tools.ide.repo.ToolRepository;
49
import com.devonfw.tools.ide.step.Step;
50
import com.devonfw.tools.ide.step.StepImpl;
51
import com.devonfw.tools.ide.url.model.UrlMetadata;
52
import com.devonfw.tools.ide.validation.ValidationResult;
53
import com.devonfw.tools.ide.validation.ValidationState;
54
import com.devonfw.tools.ide.variable.IdeVariables;
55

56
/**
57
 * Abstract base implementation of {@link IdeContext}.
58
 */
59
public abstract class AbstractIdeContext implements IdeContext {
1✔
60

61
  private static final String IDE_URLS_GIT = "https://github.com/devonfw/ide-urls.git";
62

63
  private final IdeStartContextImpl startContext;
64

65
  private Path ideHome;
66

67
  private final Path ideRoot;
68

69
  private Path confPath;
70

71
  private Path settingsPath;
72

73
  private Path softwarePath;
74

75
  private Path softwareExtraPath;
76

77
  private Path softwareRepositoryPath;
78

79
  private Path pluginsPath;
80

81
  private Path workspacePath;
82

83
  private String workspaceName;
84

85
  private Path urlsPath;
86

87
  private Path tempPath;
88

89
  private Path tempDownloadPath;
90

91
  private Path cwd;
92

93
  private Path downloadPath;
94

95
  private Path toolRepositoryPath;
96

97
  private Path userHome;
98

99
  private Path userHomeIde;
100

101
  private SystemPath path;
102

103
  private WindowsPathSyntax pathSyntax;
104

105
  private final SystemInfo systemInfo;
106

107
  private EnvironmentVariables variables;
108

109
  private final FileAccess fileAccess;
110

111
  private final CommandletManager commandletManager;
112

113
  private ToolRepository defaultToolRepository;
114

115
  private CustomToolRepository customToolRepository;
116

117
  private DirectoryMerger workspaceMerger;
118

119
  private UrlMetadata urlMetadata;
120

121
  private Path defaultExecutionDirectory;
122

123
  private StepImpl currentStep;
124

125
  private Boolean online;
126

127
  /**
128
   * The constructor.
129
   *
130
   * @param startContext the {@link IdeLogger}.
131
   * @param userDir the optional {@link Path} to current working directory.
132
   */
133
  public AbstractIdeContext(IdeStartContextImpl startContext, Path userDir) {
134

135
    super();
2✔
136
    this.startContext = startContext;
3✔
137
    this.systemInfo = SystemInfoImpl.INSTANCE;
3✔
138
    this.commandletManager = new CommandletManagerImpl(this);
6✔
139
    this.fileAccess = new FileAccessImpl(this);
6✔
140
    String workspace = WORKSPACE_MAIN;
2✔
141
    if (userDir == null) {
2!
142
      userDir = Path.of(System.getProperty("user.dir"));
×
143
    } else {
144
      userDir = userDir.toAbsolutePath();
3✔
145
    }
146
    // detect IDE_HOME and WORKSPACE
147
    Path currentDir = userDir;
2✔
148
    String name1 = "";
2✔
149
    String name2 = "";
2✔
150
    while (currentDir != null) {
2✔
151
      trace("Looking for IDE_HOME in {}", currentDir);
9✔
152
      if (isIdeHome(currentDir)) {
4✔
153
        if (FOLDER_WORKSPACES.equals(name1) && !name2.isEmpty()) {
7✔
154
          workspace = name2;
3✔
155
        }
156
        break;
157
      }
158
      name2 = name1;
2✔
159
      int nameCount = currentDir.getNameCount();
3✔
160
      if (nameCount >= 1) {
3✔
161
        name1 = currentDir.getName(nameCount - 1).toString();
7✔
162
      }
163
      currentDir = currentDir.getParent();
3✔
164
    }
1✔
165

166
    // detection completed, initializing variables
167
    this.ideRoot = findIdeRoot(currentDir);
5✔
168

169
    setCwd(userDir, workspace, currentDir);
5✔
170

171
    if (this.ideRoot == null) {
3✔
172
      this.toolRepositoryPath = null;
3✔
173
      this.urlsPath = null;
3✔
174
      this.tempPath = null;
3✔
175
      this.tempDownloadPath = null;
3✔
176
      this.softwareRepositoryPath = null;
4✔
177
    } else {
178
      Path ideBase = this.ideRoot.resolve(FOLDER_IDE);
5✔
179
      this.toolRepositoryPath = ideBase.resolve("software");
5✔
180
      this.urlsPath = ideBase.resolve("urls");
5✔
181
      this.tempPath = ideBase.resolve("tmp");
5✔
182
      this.tempDownloadPath = this.tempPath.resolve(FOLDER_DOWNLOADS);
6✔
183
      this.softwareRepositoryPath = ideBase.resolve(FOLDER_SOFTWARE);
5✔
184
      if (Files.isDirectory(this.tempPath)) {
7✔
185
        // TODO delete all files older than 1 day here...
186
      } else {
187
        this.fileAccess.mkdirs(this.tempDownloadPath);
5✔
188
      }
189
    }
190

191
    this.defaultToolRepository = new DefaultToolRepository(this);
6✔
192
  }
1✔
193

194
  private Path findIdeRoot(Path ideHomePath) {
195

196
    Path ideRootPath = null;
2✔
197
    if (ideHomePath != null) {
2✔
198
      ideRootPath = ideHomePath.getParent();
4✔
199
    } else if (!isTest()) {
3!
200
      ideRootPath = getIdeRootPathFromEnv();
×
201
    }
202
    return ideRootPath;
2✔
203
  }
204

205
  private static Path getIdeRootPathFromEnv() {
206
    String root = System.getenv(IdeVariables.IDE_ROOT.getName());
×
207
    if (root != null) {
×
208
      Path rootPath = Path.of(root);
×
209
      if (Files.isDirectory(rootPath)) {
×
210
        return rootPath;
×
211
      }
212
    }
213
    return null;
×
214
  }
215

216
  @Override
217
  public void setCwd(Path userDir, String workspace, Path ideHome) {
218

219
    this.cwd = userDir;
3✔
220
    this.workspaceName = workspace;
3✔
221
    this.ideHome = ideHome;
3✔
222
    if (ideHome == null) {
2✔
223
      this.workspacePath = null;
3✔
224
      this.confPath = null;
3✔
225
      this.settingsPath = null;
3✔
226
      this.softwarePath = null;
3✔
227
      this.softwareExtraPath = null;
3✔
228
      this.pluginsPath = null;
4✔
229
    } else {
230
      this.workspacePath = this.ideHome.resolve(FOLDER_WORKSPACES).resolve(this.workspaceName);
9✔
231
      this.confPath = this.ideHome.resolve(FOLDER_CONF);
6✔
232
      this.settingsPath = this.ideHome.resolve(FOLDER_SETTINGS);
6✔
233
      this.softwarePath = this.ideHome.resolve(FOLDER_SOFTWARE);
6✔
234
      this.softwareExtraPath = this.softwarePath.resolve(FOLDER_EXTRA);
6✔
235
      this.pluginsPath = this.ideHome.resolve(FOLDER_PLUGINS);
6✔
236
    }
237
    if (isTest()) {
3!
238
      // only for testing...
239
      if (this.ideHome == null) {
3✔
240
        this.userHome = Path.of("/non-existing-user-home-for-testing");
7✔
241
      } else {
242
        this.userHome = this.ideHome.resolve("home");
7✔
243
      }
244
    } else {
245
      this.userHome = Path.of(System.getProperty("user.home"));
×
246
    }
247
    this.userHomeIde = this.userHome.resolve(".ide");
6✔
248
    this.downloadPath = this.userHome.resolve("Downloads/ide");
6✔
249

250
    this.variables = createVariables();
4✔
251
    this.path = computeSystemPath();
4✔
252
    this.customToolRepository = CustomToolRepositoryImpl.of(this);
4✔
253
    this.workspaceMerger = new DirectoryMerger(this);
6✔
254
  }
1✔
255

256
  private String getMessageIdeHomeFound() {
257

258
    return "IDE environment variables have been set for " + this.ideHome + " in workspace " + this.workspaceName;
6✔
259
  }
260

261
  private String getMessageIdeHomeNotFound() {
262

263
    return "You are not inside an IDE installation: " + this.cwd;
×
264
  }
265

266
  private static String getMessageIdeRootNotFound() {
267
    String root = System.getenv("IDE_ROOT");
×
268
    if (root == null) {
×
269
      return "The environment variable IDE_ROOT is undefined. Please reinstall IDEasy or manually repair IDE_ROOT variable.";
×
270
    } else {
271
      return "The environment variable IDE_ROOT is pointing to an invalid path " + root + ". Please reinstall IDEasy or manually repair IDE_ROOT variable.";
×
272
    }
273
  }
274

275
  /**
276
   * @return the status message about the {@link #getIdeHome() IDE_HOME} detection and environment variable initialization.
277
   */
278
  public String getMessageIdeHome() {
279

280
    if (this.ideHome == null) {
×
281
      return getMessageIdeHomeNotFound();
×
282
    }
283
    return getMessageIdeHomeFound();
×
284
  }
285

286
  /**
287
   * @return {@code true} if this is a test context for JUnits, {@code false} otherwise.
288
   */
289
  public boolean isTest() {
290

291
    return false;
×
292
  }
293

294
  protected SystemPath computeSystemPath() {
295

296
    return new SystemPath(this);
×
297
  }
298

299
  private boolean isIdeHome(Path dir) {
300

301
    if (!Files.isDirectory(dir.resolve("workspaces"))) {
7✔
302
      return false;
2✔
303
    } else if (!Files.isDirectory(dir.resolve("settings"))) {
7!
304
      return false;
×
305
    }
306
    return true;
2✔
307
  }
308

309
  private EnvironmentVariables createVariables() {
310

311
    AbstractEnvironmentVariables system = createSystemVariables();
3✔
312
    AbstractEnvironmentVariables user = extendVariables(system, this.userHomeIde, EnvironmentVariablesType.USER);
7✔
313
    AbstractEnvironmentVariables settings = extendVariables(user, this.settingsPath, EnvironmentVariablesType.SETTINGS);
7✔
314
    // TODO should we keep this workspace properties? Was this feature ever used?
315
    AbstractEnvironmentVariables workspace = extendVariables(settings, this.workspacePath, EnvironmentVariablesType.WORKSPACE);
7✔
316
    AbstractEnvironmentVariables conf = extendVariables(workspace, this.confPath, EnvironmentVariablesType.CONF);
7✔
317
    return conf.resolved();
3✔
318
  }
319

320
  protected AbstractEnvironmentVariables createSystemVariables() {
321

322
    return EnvironmentVariables.ofSystem(this);
3✔
323
  }
324

325
  protected AbstractEnvironmentVariables extendVariables(AbstractEnvironmentVariables envVariables, Path propertiesPath, EnvironmentVariablesType type) {
326

327
    Path propertiesFile = null;
2✔
328
    if (propertiesPath == null) {
2✔
329
      trace("Configuration directory for type {} does not exist.", type);
10✔
330
    } else if (Files.isDirectory(propertiesPath)) {
5✔
331
      propertiesFile = propertiesPath.resolve(EnvironmentVariables.DEFAULT_PROPERTIES);
4✔
332
      boolean legacySupport = (type != EnvironmentVariablesType.USER);
7✔
333
      if (legacySupport && !Files.exists(propertiesFile)) {
7✔
334
        Path legacyFile = propertiesPath.resolve(EnvironmentVariables.LEGACY_PROPERTIES);
4✔
335
        if (Files.exists(legacyFile)) {
5!
336
          propertiesFile = legacyFile;
×
337
        }
338
      }
339
    } else {
1✔
340
      debug("Configuration directory {} does not exist.", propertiesPath);
9✔
341
    }
342
    return envVariables.extend(propertiesFile, type);
5✔
343
  }
344

345
  @Override
346
  public SystemInfo getSystemInfo() {
347

348
    return this.systemInfo;
3✔
349
  }
350

351
  @Override
352
  public FileAccess getFileAccess() {
353

354
    return this.fileAccess;
3✔
355
  }
356

357
  @Override
358
  public CommandletManager getCommandletManager() {
359

360
    return this.commandletManager;
3✔
361
  }
362

363
  @Override
364
  public ToolRepository getDefaultToolRepository() {
365

366
    return this.defaultToolRepository;
3✔
367
  }
368

369
  /**
370
   * @param defaultToolRepository the new value of {@link #getDefaultToolRepository()}.
371
   */
372
  protected void setDefaultToolRepository(ToolRepository defaultToolRepository) {
373

374
    this.defaultToolRepository = defaultToolRepository;
3✔
375
  }
1✔
376

377
  @Override
378
  public CustomToolRepository getCustomToolRepository() {
379

380
    return this.customToolRepository;
3✔
381
  }
382

383
  @Override
384
  public Path getIdeHome() {
385

386
    return this.ideHome;
3✔
387
  }
388

389
  @Override
390
  public String getProjectName() {
391

392
    if (this.ideHome != null) {
3!
393
      return this.ideHome.getFileName().toString();
5✔
394
    }
395
    return "";
×
396
  }
397

398
  @Override
399
  public Path getIdeRoot() {
400

401
    return this.ideRoot;
3✔
402
  }
403

404
  @Override
405
  public Path getCwd() {
406

407
    return this.cwd;
3✔
408
  }
409

410
  @Override
411
  public Path getTempPath() {
412

413
    return this.tempPath;
3✔
414
  }
415

416
  @Override
417
  public Path getTempDownloadPath() {
418

419
    return this.tempDownloadPath;
3✔
420
  }
421

422
  @Override
423
  public Path getUserHome() {
424

425
    return this.userHome;
3✔
426
  }
427

428
  @Override
429
  public Path getUserHomeIde() {
430

431
    return this.userHomeIde;
3✔
432
  }
433

434
  @Override
435
  public Path getSettingsPath() {
436

437
    return this.settingsPath;
3✔
438
  }
439

440
  @Override
441
  public Path getConfPath() {
442

443
    return this.confPath;
3✔
444
  }
445

446
  @Override
447
  public Path getSoftwarePath() {
448

449
    return this.softwarePath;
3✔
450
  }
451

452
  @Override
453
  public Path getSoftwareExtraPath() {
454

455
    return this.softwareExtraPath;
3✔
456
  }
457

458
  @Override
459
  public Path getSoftwareRepositoryPath() {
460

461
    return this.softwareRepositoryPath;
3✔
462
  }
463

464
  @Override
465
  public Path getPluginsPath() {
466

467
    return this.pluginsPath;
3✔
468
  }
469

470
  @Override
471
  public String getWorkspaceName() {
472

473
    return this.workspaceName;
3✔
474
  }
475

476
  @Override
477
  public Path getWorkspacePath() {
478

479
    return this.workspacePath;
3✔
480
  }
481

482
  @Override
483
  public Path getDownloadPath() {
484

485
    return this.downloadPath;
3✔
486
  }
487

488
  @Override
489
  public Path getUrlsPath() {
490

491
    return this.urlsPath;
3✔
492
  }
493

494
  @Override
495
  public Path getToolRepositoryPath() {
496

497
    return this.toolRepositoryPath;
3✔
498
  }
499

500
  @Override
501
  public SystemPath getPath() {
502

503
    return this.path;
3✔
504
  }
505

506
  @Override
507
  public EnvironmentVariables getVariables() {
508

509
    return this.variables;
3✔
510
  }
511

512
  @Override
513
  public UrlMetadata getUrls() {
514

515
    if (this.urlMetadata == null) {
3✔
516
      if (!isTest()) {
3!
517
        getGitContext().pullOrCloneAndResetIfNeeded(IDE_URLS_GIT, this.urlsPath, null);
×
518
      }
519
      this.urlMetadata = new UrlMetadata(this);
6✔
520
    }
521
    return this.urlMetadata;
3✔
522
  }
523

524
  @Override
525
  public boolean isQuietMode() {
526

527
    return this.startContext.isQuietMode();
4✔
528
  }
529

530
  @Override
531
  public boolean isBatchMode() {
532

533
    return this.startContext.isBatchMode();
×
534
  }
535

536
  @Override
537
  public boolean isForceMode() {
538

539
    return this.startContext.isForceMode();
4✔
540
  }
541

542
  @Override
543
  public boolean isOfflineMode() {
544

545
    return this.startContext.isOfflineMode();
4✔
546
  }
547

548
  @Override
549
  public boolean isOnline() {
550

551
    if (this.online == null) {
3!
552
      // we currently assume we have only a CLI process that runs shortly
553
      // therefore we run this check only once to save resources when this method is called many times
554
      try {
555
        int timeout = 1000;
2✔
556
        //open a connection to github.com and try to retrieve data
557
        //getContent fails if there is no connection
558
        URLConnection connection = new URL("https://www.github.com").openConnection();
6✔
559
        connection.setConnectTimeout(timeout);
3✔
560
        connection.getContent();
3✔
561
        this.online = Boolean.TRUE;
3✔
562
      } catch (Exception ignored) {
×
563
        this.online = Boolean.FALSE;
×
564
      }
1✔
565
    }
566
    return this.online.booleanValue();
4✔
567
  }
568

569
  @Override
570
  public Locale getLocale() {
571

572
    Locale locale = this.startContext.getLocale();
4✔
573
    if (locale == null) {
2!
574
      locale = Locale.getDefault();
×
575
    }
576
    return locale;
2✔
577
  }
578

579
  @Override
580
  public DirectoryMerger getWorkspaceMerger() {
581

582
    return this.workspaceMerger;
3✔
583
  }
584

585
  /**
586
   * @return the {@link #getDefaultExecutionDirectory() default execution directory} in which a command process is executed.
587
   */
588
  @Override
589
  public Path getDefaultExecutionDirectory() {
590

591
    return this.defaultExecutionDirectory;
×
592
  }
593

594
  /**
595
   * @param defaultExecutionDirectory new value of {@link #getDefaultExecutionDirectory()}.
596
   */
597
  public void setDefaultExecutionDirectory(Path defaultExecutionDirectory) {
598

599
    if (defaultExecutionDirectory != null) {
×
600
      this.defaultExecutionDirectory = defaultExecutionDirectory;
×
601
    }
602
  }
×
603

604
  @Override
605
  public ProxyContext getProxyContext() {
606

607
    return new ProxyContext(this);
5✔
608
  }
609

610
  @Override
611
  public GitContext getGitContext() {
612

613
    return new GitContextImpl(this);
×
614
  }
615

616
  @Override
617
  public ProcessContext newProcess() {
618

619
    ProcessContext processContext = createProcessContext();
3✔
620
    if (this.defaultExecutionDirectory != null) {
3!
621
      processContext.directory(this.defaultExecutionDirectory);
×
622
    }
623
    return processContext;
2✔
624
  }
625

626
  /**
627
   * @return a new instance of {@link ProcessContext}.
628
   * @see #newProcess()
629
   */
630
  protected ProcessContext createProcessContext() {
631

632
    return new ProcessContextImpl(this);
×
633
  }
634

635
  @Override
636
  public IdeSubLogger level(IdeLogLevel level) {
637

638
    return this.startContext.level(level);
5✔
639
  }
640

641
  @Override
642
  public String askForInput(String message, String defaultValue) {
643

644
    if (!message.isBlank()) {
×
645
      info(message);
×
646
    }
647
    if (isBatchMode()) {
×
648
      if (isForceMode()) {
×
649
        return defaultValue;
×
650
      } else {
651
        throw new CliAbortException();
×
652
      }
653
    }
654
    String input = readLine().trim();
×
655
    return input.isEmpty() ? defaultValue : input;
×
656
  }
657

658
  @Override
659
  public String askForInput(String message) {
660

661
    String input;
662
    do {
663
      info(message);
3✔
664
      input = readLine().trim();
4✔
665
    } while (input.isEmpty());
3!
666

667
    return input;
2✔
668
  }
669

670
  @SuppressWarnings("unchecked")
671
  @Override
672
  public <O> O question(String question, O... options) {
673

674
    assert (options.length >= 2);
×
675
    interaction(question);
×
676
    Map<String, O> mapping = new HashMap<>(options.length);
×
677
    int i = 0;
×
678
    for (O option : options) {
×
679
      i++;
×
680
      String key = "" + option;
×
681
      addMapping(mapping, key, option);
×
682
      String numericKey = Integer.toString(i);
×
683
      if (numericKey.equals(key)) {
×
684
        trace("Options should not be numeric: " + key);
×
685
      } else {
686
        addMapping(mapping, numericKey, option);
×
687
      }
688
      interaction("Option " + numericKey + ": " + key);
×
689
    }
690
    O option = null;
×
691
    if (isBatchMode()) {
×
692
      if (isForceMode()) {
×
693
        option = options[0];
×
694
        interaction("" + option);
×
695
      }
696
    } else {
697
      while (option == null) {
×
698
        String answer = readLine();
×
699
        option = mapping.get(answer);
×
700
        if (option == null) {
×
701
          warning("Invalid answer: '" + answer + "' - please try again.");
×
702
        }
703
      }
×
704
    }
705
    return option;
×
706
  }
707

708
  /**
709
   * @return the input from the end-user (e.g. read from the console).
710
   */
711
  protected abstract String readLine();
712

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

715
    O duplicate = mapping.put(key, option);
×
716
    if (duplicate != null) {
×
717
      throw new IllegalArgumentException("Duplicated option " + key);
×
718
    }
719
  }
×
720

721
  @Override
722
  public Step getCurrentStep() {
723

724
    return this.currentStep;
×
725
  }
726

727
  @Override
728
  public StepImpl newStep(boolean silent, String name, Object... parameters) {
729

730
    this.currentStep = new StepImpl(this, this.currentStep, name, silent, parameters);
11✔
731
    return this.currentStep;
3✔
732
  }
733

734
  /**
735
   * Internal method to end the running {@link Step}.
736
   *
737
   * @param step the current {@link Step} to end.
738
   */
739
  public void endStep(StepImpl step) {
740

741
    if (step == this.currentStep) {
4!
742
      this.currentStep = this.currentStep.getParent();
6✔
743
    } else {
744
      String currentStepName = "null";
×
745
      if (this.currentStep != null) {
×
746
        currentStepName = this.currentStep.getName();
×
747
      }
748
      warning("endStep called with wrong step '{}' but expected '{}'", step.getName(), currentStepName);
×
749
    }
750
  }
1✔
751

752
  /**
753
   * Finds the matching {@link Commandlet} to run, applies {@link CliArguments} to its {@link Commandlet#getProperties() properties} and will execute it.
754
   *
755
   * @param arguments the {@link CliArgument}.
756
   * @return the return code of the execution.
757
   */
758
  public int run(CliArguments arguments) {
759

760
    CliArgument current = arguments.current();
3✔
761
    assert (this.currentStep == null);
4!
762
    boolean supressStepSuccess = false;
2✔
763
    StepImpl step = newStep(true, "ide", (Object[]) current.asArray());
8✔
764
    Commandlet firstCandidate = null;
2✔
765
    try {
766
      if (!current.isEnd()) {
3!
767
        String keyword = current.get();
3✔
768
        firstCandidate = this.commandletManager.getCommandletByFirstKeyword(keyword);
5✔
769
        ValidationResult firstResult = null;
2✔
770
        if (firstCandidate != null) {
2!
771
          firstResult = applyAndRun(arguments.copy(), firstCandidate);
6✔
772
          if (firstResult.isValid()) {
3!
773
            supressStepSuccess = firstCandidate.isSuppressStepSuccess();
3✔
774
            step.success();
2✔
775
            return ProcessResult.SUCCESS;
4✔
776
          }
777
        }
778
        for (Commandlet cmd : this.commandletManager.getCommandlets()) {
×
779
          if (cmd != firstCandidate) {
×
780
            ValidationResult result = applyAndRun(arguments.copy(), cmd);
×
781
            if (result.isValid()) {
×
782
              supressStepSuccess = cmd.isSuppressStepSuccess();
×
783
              step.success();
×
784
              return ProcessResult.SUCCESS;
×
785
            }
786
          }
787
        }
×
788
        if (firstResult != null) {
×
789
          throw new CliException(firstResult.getErrorMessage());
×
790
        }
791
        step.error("Invalid arguments: {}", current.getArgs());
×
792
      }
793

794
      HelpCommandlet help = this.commandletManager.getCommandlet(HelpCommandlet.class);
×
795
      if (firstCandidate != null) {
×
796
        help.commandlet.setValue(firstCandidate);
×
797
      }
798
      help.run();
×
799
      return 1;
×
800
    } catch (Throwable t) {
×
801
      step.error(t, true);
×
802
      throw t;
×
803
    } finally {
804
      step.close();
2✔
805
      assert (this.currentStep == null);
4!
806
      step.logSummary(supressStepSuccess);
3✔
807
    }
808
  }
809

810
  /**
811
   * @param cmd the potential {@link Commandlet} to {@link #apply(CliArguments, Commandlet, CompletionCandidateCollector) apply} and
812
   *     {@link Commandlet#run() run}.
813
   * @return {@code true} if the given {@link Commandlet} matched and did {@link Commandlet#run() run} successfully, {@code false} otherwise (the
814
   *     {@link Commandlet} did not match and we have to try a different candidate).
815
   */
816
  private ValidationResult applyAndRun(CliArguments arguments, Commandlet cmd) {
817

818
    cmd.clearProperties();
2✔
819

820
    ValidationResult result = apply(arguments, cmd, null);
6✔
821
    if (result.isValid()) {
3!
822
      result = cmd.validate();
3✔
823
    }
824
    if (result.isValid()) {
3!
825
      debug("Running commandlet {}", cmd);
9✔
826
      if (cmd.isIdeHomeRequired() && (this.ideHome == null)) {
6!
827
        throw new CliException(getMessageIdeHomeNotFound(), ProcessResult.NO_IDE_HOME);
×
828
      } else if (cmd.isIdeRootRequired() && (this.ideRoot == null)) {
6!
829
        throw new CliException(getMessageIdeRootNotFound(), ProcessResult.NO_IDE_ROOT);
×
830
      }
831
      if (cmd.isProcessableOutput()) {
3!
832
        if (!debug().isEnabled()) {
×
833
          // unless --debug or --trace was supplied, processable output commandlets will disable all log-levels except INFO to prevent other logs interfere
834
          for (IdeLogLevel level : IdeLogLevel.values()) {
×
835
            if (level != IdeLogLevel.INFO) {
×
836
              this.startContext.setLogLevel(level, false);
×
837
            }
838
          }
839
        }
840
      } else {
841
        if (!isTest()) {
3!
842
          if (this.ideRoot == null) {
×
843
            warning("Variable IDE_ROOT is undefined. Please check your installation or run setup script again.");
×
844
          } else if (this.ideHome != null) {
×
845
            Path ideRootPath = getIdeRootPathFromEnv();
×
846
            if (!this.ideRoot.equals(ideRootPath)) {
×
847
              warning("Variable IDE_ROOT is set to '{}' but for your project '{}' the path '{}' would have been expected.", ideRootPath,
×
848
                  this.ideHome.getFileName(), this.ideRoot);
×
849
            }
850
          }
851
        }
852
        if (cmd.isIdeHomeRequired()) {
3!
853
          debug(getMessageIdeHomeFound());
4✔
854
        }
855
      }
856
      if (this.settingsPath != null) {
3!
857
        if (getGitContext().isRepositoryUpdateAvailable(this.settingsPath) ||
7!
858
            (getGitContext().fetchIfNeeded(this.settingsPath) && getGitContext().isRepositoryUpdateAvailable(this.settingsPath))) {
5!
859
          interaction("Updates are available for the settings repository. If you want to pull the latest changes, call ide update.");
×
860
        }
861
      }
862
      cmd.run();
3✔
863
    } else {
864
      trace("Commandlet did not match");
×
865
    }
866
    return result;
2✔
867
  }
868

869
  /**
870
   * @param arguments the {@link CliArguments#ofCompletion(String...) completion arguments}.
871
   * @param includeContextOptions to include the options of {@link ContextCommandlet}.
872
   * @return the {@link List} of {@link CompletionCandidate}s to suggest.
873
   */
874
  public List<CompletionCandidate> complete(CliArguments arguments, boolean includeContextOptions) {
875

876
    CompletionCandidateCollector collector = new CompletionCandidateCollectorDefault(this);
5✔
877
    if (arguments.current().isStart()) {
4✔
878
      arguments.next();
3✔
879
    }
880
    if (includeContextOptions) {
2✔
881
      ContextCommandlet cc = new ContextCommandlet();
4✔
882
      for (Property<?> property : cc.getProperties()) {
11✔
883
        assert (property.isOption());
4!
884
        property.apply(arguments, this, cc, collector);
7✔
885
      }
1✔
886
    }
887
    CliArgument current = arguments.current();
3✔
888
    if (!current.isEnd()) {
3!
889
      String keyword = current.get();
3✔
890
      Commandlet firstCandidate = this.commandletManager.getCommandletByFirstKeyword(keyword);
5✔
891
      boolean matches = false;
2✔
892
      if (firstCandidate != null) {
2✔
893
        matches = completeCommandlet(arguments, firstCandidate, collector);
7✔
894
      } else if (current.isCombinedShortOption()) {
3✔
895
        collector.add(keyword, null, null, null);
6✔
896
      }
897
      if (!matches) {
2!
898
        for (Commandlet cmd : this.commandletManager.getCommandlets()) {
12✔
899
          if (cmd != firstCandidate) {
3✔
900
            completeCommandlet(arguments, cmd, collector);
6✔
901
          }
902
        }
1✔
903
      }
904
    }
905
    return collector.getSortedCandidates();
3✔
906
  }
907

908
  private boolean completeCommandlet(CliArguments arguments, Commandlet cmd, CompletionCandidateCollector collector) {
909
    if (cmd.isIdeHomeRequired() && (this.ideHome == null)) {
6!
910
      return false;
×
911
    } else {
912
      return apply(arguments.copy(), cmd, collector).isValid();
8✔
913
    }
914
  }
915

916

917
  /**
918
   * @param arguments the {@link CliArguments} to apply. Will be {@link CliArguments#next() consumed} as they are matched. Consider passing a
919
   *     {@link CliArguments#copy() copy} as needed.
920
   * @param cmd the potential {@link Commandlet} to match.
921
   * @param collector the {@link CompletionCandidateCollector}.
922
   * @return {@code true} if the given {@link Commandlet} matches to the given {@link CliArgument}(s) and those have been applied (set in the {@link Commandlet}
923
   *     and {@link Commandlet#validate() validated}), {@code false} otherwise (the {@link Commandlet} did not match and we have to try a different candidate).
924
   */
925
  public ValidationResult apply(CliArguments arguments, Commandlet cmd, CompletionCandidateCollector collector) {
926

927
    trace("Trying to match arguments to commandlet {}", cmd.getName());
10✔
928
    CliArgument currentArgument = arguments.current();
3✔
929
    Iterator<Property<?>> propertyIterator;
930
    if (currentArgument.isCompletion()) {
3✔
931
      propertyIterator = cmd.getProperties().iterator();
5✔
932
    } else {
933
      propertyIterator = cmd.getValues().iterator();
4✔
934
    }
935
    Property<?> property = null;
2✔
936
    if (propertyIterator.hasNext()) {
3✔
937
      property = propertyIterator.next();
4✔
938
    }
939
    while (!currentArgument.isEnd()) {
3✔
940
      trace("Trying to match argument '{}'", currentArgument);
9✔
941
      Property<?> currentProperty = property;
2✔
942
      if (!arguments.isEndOptions()) {
3✔
943
        Property<?> option = cmd.getOption(currentArgument.getKey());
5✔
944
        if (option != null) {
2✔
945
          currentProperty = option;
2✔
946
        }
947
      }
948
      if (currentProperty == null) {
2✔
949
        trace("No option or next value found");
3✔
950
        ValidationState state = new ValidationState(null);
5✔
951
        state.addErrorMessage("No matching property found");
3✔
952
        return state;
2✔
953
      }
954
      trace("Next property candidate to match argument is {}", currentProperty);
9✔
955
      if (currentProperty == property) {
3✔
956
        if (!property.isMultiValued()) {
3✔
957
          if (propertyIterator.hasNext()) {
3✔
958
            property = propertyIterator.next();
5✔
959
          } else {
960
            property = null;
2✔
961
          }
962
        }
963
        if ((property != null) && property.isValue() && property.isMultiValued()) {
8✔
964
          arguments.endOptions();
2✔
965
        }
966
      }
967
      boolean matches = currentProperty.apply(arguments, this, cmd, collector);
7✔
968
      if (!matches || currentArgument.isCompletion()) {
5✔
969
        ValidationState state = new ValidationState(null);
5✔
970
        state.addErrorMessage("No matching property found");
3✔
971
        return state;
2✔
972
      }
973
      currentArgument = arguments.current();
3✔
974
    }
1✔
975
    return new ValidationState(null);
5✔
976
  }
977

978
  @Override
979
  public String findBash() {
980

981
    String bash = "bash";
2✔
982
    if (SystemInfoImpl.INSTANCE.isWindows()) {
3!
983
      bash = findBashOnWindows();
×
984
    }
985

986
    return bash;
2✔
987
  }
988

989
  private String findBashOnWindows() {
990

991
    // Check if Git Bash exists in the default location
992
    Path defaultPath = Path.of("C:\\Program Files\\Git\\bin\\bash.exe");
×
993
    if (Files.exists(defaultPath)) {
×
994
      return defaultPath.toString();
×
995
    }
996

997
    // If not found in the default location, try the registry query
998
    String[] bashVariants = { "GitForWindows", "Cygwin\\setup" };
×
999
    String[] registryKeys = { "HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER" };
×
1000
    String regQueryResult;
1001
    for (String bashVariant : bashVariants) {
×
1002
      for (String registryKey : registryKeys) {
×
1003
        String toolValueName = ("GitForWindows".equals(bashVariant)) ? "InstallPath" : "rootdir";
×
1004
        String command = "reg query " + registryKey + "\\Software\\" + bashVariant + "  /v " + toolValueName + " 2>nul";
×
1005

1006
        try {
1007
          Process process = new ProcessBuilder("cmd.exe", "/c", command).start();
×
1008
          try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
×
1009
            StringBuilder output = new StringBuilder();
×
1010
            String line;
1011

1012
            while ((line = reader.readLine()) != null) {
×
1013
              output.append(line);
×
1014
            }
1015

1016
            int exitCode = process.waitFor();
×
1017
            if (exitCode != 0) {
×
1018
              return null;
×
1019
            }
1020

1021
            regQueryResult = output.toString();
×
1022
            if (regQueryResult != null) {
×
1023
              int index = regQueryResult.indexOf("REG_SZ");
×
1024
              if (index != -1) {
×
1025
                String path = regQueryResult.substring(index + "REG_SZ".length()).trim();
×
1026
                return path + "\\bin\\bash.exe";
×
1027
              }
1028
            }
1029

1030
          }
×
1031
        } catch (Exception e) {
×
1032
          return null;
×
1033
        }
×
1034
      }
1035
    }
1036
    // no bash found
1037
    return null;
×
1038
  }
1039

1040
  @Override
1041
  public WindowsPathSyntax getPathSyntax() {
1042
    return this.pathSyntax;
3✔
1043
  }
1044

1045
  /**
1046
   * @param pathSyntax new value of {@link #getPathSyntax()}.
1047
   */
1048
  public void setPathSyntax(WindowsPathSyntax pathSyntax) {
1049

1050
    this.pathSyntax = pathSyntax;
3✔
1051
  }
1✔
1052

1053
  /**
1054
   * @return the {@link IdeStartContextImpl}.
1055
   */
1056
  public IdeStartContextImpl getStartContext() {
1057

1058
    return startContext;
3✔
1059
  }
1060

1061
  /**
1062
   * Reloads this context and re-initializes the {@link #getVariables() variables}.
1063
   */
1064
  public void reload() {
1065
    this.variables = createVariables();
4✔
1066
  }
1✔
1067
}
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