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

devonfw / IDEasy / 12808103722

16 Jan 2025 11:40AM UTC coverage: 68.152% (+0.3%) from 67.826%
12808103722

Pull #912

github

web-flow
Merge eb3a1052d into 93247a4dd
Pull Request #912: #498: resolve variables on load #691: solve sub-node merging

2709 of 4345 branches covered (62.35%)

Branch coverage included in aggregate %.

7021 of 9932 relevant lines covered (70.69%)

3.09 hits per line

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

62.19
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.ArrayList;
10
import java.util.HashMap;
11
import java.util.Iterator;
12
import java.util.List;
13
import java.util.Locale;
14
import java.util.Map;
15

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

63
/**
64
 * Abstract base implementation of {@link IdeContext}.
65
 */
66
public abstract class AbstractIdeContext implements IdeContext {
67

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

70
  private final IdeStartContextImpl startContext;
71

72
  private Path ideHome;
73

74
  private final Path ideRoot;
75

76
  private Path confPath;
77

78
  protected Path settingsPath;
79

80
  private Path settingsCommitIdPath;
81

82
  private Path softwarePath;
83

84
  private Path softwareExtraPath;
85

86
  private final Path softwareRepositoryPath;
87

88
  protected Path pluginsPath;
89

90
  private Path workspacePath;
91

92
  private String workspaceName;
93

94
  protected Path urlsPath;
95

96
  private final Path tempPath;
97

98
  private final Path tempDownloadPath;
99

100
  private Path cwd;
101

102
  private Path downloadPath;
103

104
  private final Path toolRepositoryPath;
105

106
  protected Path userHome;
107

108
  private Path userHomeIde;
109

110
  private SystemPath path;
111

112
  private WindowsPathSyntax pathSyntax;
113

114
  private final SystemInfo systemInfo;
115

116
  private EnvironmentVariables variables;
117

118
  private final FileAccess fileAccess;
119

120
  protected CommandletManager commandletManager;
121

122
  protected ToolRepository defaultToolRepository;
123

124
  private CustomToolRepository customToolRepository;
125

126
  private DirectoryMerger workspaceMerger;
127

128
  protected UrlMetadata urlMetadata;
129

130
  protected Path defaultExecutionDirectory;
131

132
  private StepImpl currentStep;
133

134
  protected Boolean online;
135

136
  protected IdeSystem system;
137

138
  private NetworkProxy networkProxy;
139

140
  /**
141
   * The constructor.
142
   *
143
   * @param startContext the {@link IdeLogger}.
144
   * @param workingDirectory the optional {@link Path} to current working directory.
145
   */
146
  public AbstractIdeContext(IdeStartContextImpl startContext, Path workingDirectory) {
147

148
    super();
2✔
149
    this.startContext = startContext;
3✔
150
    this.systemInfo = SystemInfoImpl.INSTANCE;
3✔
151
    this.commandletManager = new CommandletManagerImpl(this);
6✔
152
    this.fileAccess = new FileAccessImpl(this);
6✔
153
    String workspace = WORKSPACE_MAIN;
2✔
154
    if (workingDirectory == null) {
2!
155
      workingDirectory = Path.of(System.getProperty("user.dir"));
×
156
    } else {
157
      workingDirectory = workingDirectory.toAbsolutePath();
3✔
158
    }
159
    // detect IDE_HOME and WORKSPACE
160
    Path currentDir = workingDirectory;
2✔
161
    String name1 = "";
2✔
162
    String name2 = "";
2✔
163
    while (currentDir != null) {
2✔
164
      trace("Looking for IDE_HOME in {}", currentDir);
9✔
165
      if (isIdeHome(currentDir)) {
4✔
166
        if (FOLDER_WORKSPACES.equals(name1) && !name2.isEmpty()) {
7✔
167
          workspace = name2;
3✔
168
        }
169
        break;
170
      }
171
      name2 = name1;
2✔
172
      int nameCount = currentDir.getNameCount();
3✔
173
      if (nameCount >= 1) {
3✔
174
        name1 = currentDir.getName(nameCount - 1).toString();
7✔
175
      }
176
      currentDir = currentDir.getParent();
3✔
177
    }
1✔
178

179
    // detection completed, initializing variables
180
    this.ideRoot = findIdeRoot(currentDir);
5✔
181

182
    setCwd(workingDirectory, workspace, currentDir);
5✔
183

184
    if (this.ideRoot == null) {
3✔
185
      this.toolRepositoryPath = null;
3✔
186
      this.urlsPath = null;
3✔
187
      this.tempPath = null;
3✔
188
      this.tempDownloadPath = null;
3✔
189
      this.softwareRepositoryPath = null;
4✔
190
    } else {
191
      Path ideBase = this.ideRoot.resolve(FOLDER_IDE);
5✔
192
      this.toolRepositoryPath = ideBase.resolve("software");
5✔
193
      this.urlsPath = ideBase.resolve("urls");
5✔
194
      this.tempPath = ideBase.resolve("tmp");
5✔
195
      this.tempDownloadPath = this.tempPath.resolve(FOLDER_DOWNLOADS);
6✔
196
      this.softwareRepositoryPath = ideBase.resolve(FOLDER_SOFTWARE);
5✔
197
      if (Files.isDirectory(this.tempPath)) {
7✔
198
        // TODO delete all files older than 1 day here...
199
      } else {
200
        this.fileAccess.mkdirs(this.tempDownloadPath);
5✔
201
      }
202
    }
203

204
    this.defaultToolRepository = new DefaultToolRepository(this);
6✔
205
  }
1✔
206

207
  private Path findIdeRoot(Path ideHomePath) {
208

209
    Path ideRootPath = null;
2✔
210
    if (ideHomePath != null) {
2✔
211
      ideRootPath = ideHomePath.getParent();
4✔
212
    } else if (!isTest()) {
3!
213
      ideRootPath = getIdeRootPathFromEnv();
×
214
    }
215
    return ideRootPath;
2✔
216
  }
217

218
  private Path getIdeRootPathFromEnv() {
219
    String root = getSystem().getEnv(IdeVariables.IDE_ROOT.getName());
×
220
    if (root != null) {
×
221
      Path rootPath = Path.of(root);
×
222
      if (Files.isDirectory(rootPath)) {
×
223
        return rootPath;
×
224
      }
225
    }
226
    return null;
×
227
  }
228

229
  @Override
230
  public void setCwd(Path userDir, String workspace, Path ideHome) {
231

232
    this.cwd = userDir;
3✔
233
    this.workspaceName = workspace;
3✔
234
    this.ideHome = ideHome;
3✔
235
    if (ideHome == null) {
2✔
236
      this.workspacePath = null;
3✔
237
      this.confPath = null;
3✔
238
      this.settingsPath = null;
3✔
239
      this.softwarePath = null;
3✔
240
      this.softwareExtraPath = null;
3✔
241
      this.pluginsPath = null;
4✔
242
    } else {
243
      this.workspacePath = this.ideHome.resolve(FOLDER_WORKSPACES).resolve(this.workspaceName);
9✔
244
      this.confPath = this.ideHome.resolve(FOLDER_CONF);
6✔
245
      this.settingsPath = this.ideHome.resolve(FOLDER_SETTINGS);
6✔
246
      this.settingsCommitIdPath = this.ideHome.resolve(IdeContext.SETTINGS_COMMIT_ID);
6✔
247
      this.softwarePath = this.ideHome.resolve(FOLDER_SOFTWARE);
6✔
248
      this.softwareExtraPath = this.softwarePath.resolve(FOLDER_EXTRA);
6✔
249
      this.pluginsPath = this.ideHome.resolve(FOLDER_PLUGINS);
6✔
250
    }
251
    if (isTest()) {
3!
252
      // only for testing...
253
      if (this.ideHome == null) {
3✔
254
        this.userHome = Path.of("/non-existing-user-home-for-testing");
7✔
255
      } else {
256
        this.userHome = this.ideHome.resolve("home");
7✔
257
      }
258
    } else {
259
      this.userHome = Path.of(getSystem().getProperty("user.home"));
×
260
    }
261
    this.userHomeIde = this.userHome.resolve(".ide");
6✔
262
    this.downloadPath = this.userHome.resolve("Downloads/ide");
6✔
263

264
    this.path = computeSystemPath();
4✔
265
  }
1✔
266

267
  private String getMessageIdeHomeFound() {
268

269
    return "IDE environment variables have been set for " + this.ideHome + " in workspace " + this.workspaceName;
6✔
270
  }
271

272
  private String getMessageIdeHomeNotFound() {
273

274
    return "You are not inside an IDE installation: " + this.cwd;
4✔
275
  }
276

277
  private String getMessageIdeRootNotFound() {
278
    String root = getSystem().getEnv("IDE_ROOT");
×
279
    if (root == null) {
×
280
      return "The environment variable IDE_ROOT is undefined. Please reinstall IDEasy or manually repair IDE_ROOT variable.";
×
281
    } else {
282
      return "The environment variable IDE_ROOT is pointing to an invalid path " + root + ". Please reinstall IDEasy or manually repair IDE_ROOT variable.";
×
283
    }
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

300
  private boolean isIdeHome(Path dir) {
301

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

310
  private EnvironmentVariables createVariables() {
311

312
    AbstractEnvironmentVariables system = createSystemVariables();
3✔
313
    AbstractEnvironmentVariables user = system.extend(this.userHomeIde, EnvironmentVariablesType.USER);
6✔
314
    AbstractEnvironmentVariables settings = user.extend(this.settingsPath, EnvironmentVariablesType.SETTINGS);
6✔
315
    AbstractEnvironmentVariables workspace = settings.extend(this.workspacePath, EnvironmentVariablesType.WORKSPACE);
6✔
316
    AbstractEnvironmentVariables conf = workspace.extend(this.confPath, EnvironmentVariablesType.CONF);
6✔
317
    return conf.resolved();
3✔
318
  }
319

320
  protected AbstractEnvironmentVariables createSystemVariables() {
321

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

325
  @Override
326
  public SystemInfo getSystemInfo() {
327

328
    return this.systemInfo;
3✔
329
  }
330

331
  @Override
332
  public FileAccess getFileAccess() {
333

334
    // currently FileAccess contains download method and requires network proxy to be configured. Maybe download should be moved to its own interface/class
335
    configureNetworkProxy();
2✔
336
    return this.fileAccess;
3✔
337
  }
338

339
  @Override
340
  public CommandletManager getCommandletManager() {
341

342
    return this.commandletManager;
3✔
343
  }
344

345
  @Override
346
  public ToolRepository getDefaultToolRepository() {
347

348
    return this.defaultToolRepository;
3✔
349
  }
350

351
  @Override
352
  public CustomToolRepository getCustomToolRepository() {
353

354
    if (this.customToolRepository == null) {
3!
355
      this.customToolRepository = CustomToolRepositoryImpl.of(this);
4✔
356
    }
357
    return this.customToolRepository;
3✔
358
  }
359

360
  @Override
361
  public Path getIdeHome() {
362

363
    return this.ideHome;
3✔
364
  }
365

366
  @Override
367
  public String getProjectName() {
368

369
    if (this.ideHome != null) {
3!
370
      return this.ideHome.getFileName().toString();
5✔
371
    }
372
    return "";
×
373
  }
374

375
  @Override
376
  public Path getIdeRoot() {
377

378
    return this.ideRoot;
3✔
379
  }
380

381
  @Override
382
  public Path getCwd() {
383

384
    return this.cwd;
3✔
385
  }
386

387
  @Override
388
  public Path getTempPath() {
389

390
    return this.tempPath;
3✔
391
  }
392

393
  @Override
394
  public Path getTempDownloadPath() {
395

396
    return this.tempDownloadPath;
3✔
397
  }
398

399
  @Override
400
  public Path getUserHome() {
401

402
    return this.userHome;
3✔
403
  }
404

405
  @Override
406
  public Path getUserHomeIde() {
407

408
    return this.userHomeIde;
3✔
409
  }
410

411
  @Override
412
  public Path getSettingsPath() {
413

414
    return this.settingsPath;
3✔
415
  }
416

417
  @Override
418
  public Path getSettingsGitRepository() {
419

420
    Path settingsPath = getSettingsPath();
3✔
421

422
    if (settingsPath == null) {
2✔
423
      error("No settings repository was found.");
3✔
424
      return null;
2✔
425
    }
426

427
    // check whether the settings path has a .git folder only if its not a symbolic link
428
    if (!Files.exists(settingsPath.resolve(".git")) && !Files.isSymbolicLink(settingsPath)) {
10!
429
      error("Settings repository exists but is not a git repository.");
3✔
430
      return null;
2✔
431
    }
432

433
    return settingsPath;
×
434
  }
435

436
  @Override
437
  public Path getSettingsCommitIdPath() {
438

439
    return this.settingsCommitIdPath;
3✔
440
  }
441

442
  @Override
443
  public Path getConfPath() {
444

445
    return this.confPath;
3✔
446
  }
447

448
  @Override
449
  public Path getSoftwarePath() {
450

451
    return this.softwarePath;
3✔
452
  }
453

454
  @Override
455
  public Path getSoftwareExtraPath() {
456

457
    return this.softwareExtraPath;
3✔
458
  }
459

460
  @Override
461
  public Path getSoftwareRepositoryPath() {
462

463
    return this.softwareRepositoryPath;
3✔
464
  }
465

466
  @Override
467
  public Path getPluginsPath() {
468

469
    return this.pluginsPath;
3✔
470
  }
471

472
  @Override
473
  public String getWorkspaceName() {
474

475
    return this.workspaceName;
3✔
476
  }
477

478
  @Override
479
  public Path getWorkspacePath() {
480

481
    return this.workspacePath;
3✔
482
  }
483

484
  @Override
485
  public Path getDownloadPath() {
486

487
    return this.downloadPath;
3✔
488
  }
489

490
  @Override
491
  public Path getUrlsPath() {
492

493
    return this.urlsPath;
3✔
494
  }
495

496
  @Override
497
  public Path getToolRepositoryPath() {
498

499
    return this.toolRepositoryPath;
3✔
500
  }
501

502
  @Override
503
  public SystemPath getPath() {
504

505
    return this.path;
3✔
506
  }
507

508
  @Override
509
  public EnvironmentVariables getVariables() {
510

511
    if (this.variables == null) {
3✔
512
      this.variables = createVariables();
4✔
513
    }
514
    return this.variables;
3✔
515
  }
516

517
  @Override
518
  public UrlMetadata getUrls() {
519

520
    if (this.urlMetadata == null) {
3✔
521
      if (!isTest()) {
3!
522
        getGitContext().pullOrCloneAndResetIfNeeded(IDE_URLS_GIT, this.urlsPath, null);
×
523
      }
524
      this.urlMetadata = new UrlMetadata(this);
6✔
525
    }
526
    return this.urlMetadata;
3✔
527
  }
528

529
  @Override
530
  public boolean isQuietMode() {
531

532
    return this.startContext.isQuietMode();
4✔
533
  }
534

535
  @Override
536
  public boolean isBatchMode() {
537

538
    return this.startContext.isBatchMode();
×
539
  }
540

541
  @Override
542
  public boolean isForceMode() {
543

544
    return this.startContext.isForceMode();
4✔
545
  }
546

547
  @Override
548
  public boolean isOfflineMode() {
549

550
    return this.startContext.isOfflineMode();
4✔
551
  }
552

553
  @Override
554
  public boolean isSkipUpdatesMode() {
555
    return this.startContext.isSkipUpdatesMode();
×
556
  }
557

558
  @Override
559
  public boolean isOnline() {
560

561
    if (this.online == null) {
3✔
562
      configureNetworkProxy();
2✔
563
      // we currently assume we have only a CLI process that runs shortly
564
      // therefore we run this check only once to save resources when this method is called many times
565
      try {
566
        int timeout = 1000;
2✔
567
        //open a connection to github.com and try to retrieve data
568
        //getContent fails if there is no connection
569
        URLConnection connection = new URL("https://www.github.com").openConnection();
6✔
570
        connection.setConnectTimeout(timeout);
3✔
571
        connection.getContent();
3✔
572
        this.online = Boolean.TRUE;
3✔
573
      } catch (Exception ignored) {
×
574
        this.online = Boolean.FALSE;
×
575
      }
1✔
576
    }
577
    return this.online.booleanValue();
4✔
578
  }
579

580
  private void configureNetworkProxy() {
581
    if (this.networkProxy == null) {
3✔
582
      this.networkProxy = new NetworkProxy(this);
6✔
583
      this.networkProxy.configure();
3✔
584
    }
585
  }
1✔
586

587
  @Override
588
  public Locale getLocale() {
589

590
    Locale locale = this.startContext.getLocale();
4✔
591
    if (locale == null) {
2!
592
      locale = Locale.getDefault();
×
593
    }
594
    return locale;
2✔
595
  }
596

597
  @Override
598
  public DirectoryMerger getWorkspaceMerger() {
599

600
    if (this.workspaceMerger == null) {
3✔
601
      this.workspaceMerger = new DirectoryMerger(this);
6✔
602
    }
603
    return this.workspaceMerger;
3✔
604
  }
605

606
  /**
607
   * @return the {@link #getDefaultExecutionDirectory() default execution directory} in which a command process is executed.
608
   */
609
  @Override
610
  public Path getDefaultExecutionDirectory() {
611

612
    return this.defaultExecutionDirectory;
×
613
  }
614

615
  /**
616
   * @param defaultExecutionDirectory new value of {@link #getDefaultExecutionDirectory()}.
617
   */
618
  public void setDefaultExecutionDirectory(Path defaultExecutionDirectory) {
619

620
    if (defaultExecutionDirectory != null) {
×
621
      this.defaultExecutionDirectory = defaultExecutionDirectory;
×
622
    }
623
  }
×
624

625
  @Override
626
  public GitContext getGitContext() {
627

628
    return new GitContextImpl(this);
×
629
  }
630

631
  @Override
632
  public ProcessContext newProcess() {
633

634
    ProcessContext processContext = createProcessContext();
3✔
635
    if (this.defaultExecutionDirectory != null) {
3!
636
      processContext.directory(this.defaultExecutionDirectory);
×
637
    }
638
    return processContext;
2✔
639
  }
640

641
  @Override
642
  public IdeSystem getSystem() {
643

644
    if (this.system == null) {
×
645
      this.system = new IdeSystemImpl(this);
×
646
    }
647
    return this.system;
×
648
  }
649

650
  /**
651
   * @return a new instance of {@link ProcessContext}.
652
   * @see #newProcess()
653
   */
654
  protected ProcessContext createProcessContext() {
655

656
    return new ProcessContextImpl(this);
×
657
  }
658

659
  @Override
660
  public IdeSubLogger level(IdeLogLevel level) {
661

662
    return this.startContext.level(level);
5✔
663
  }
664

665
  @Override
666
  public void logIdeHomeAndRootStatus() {
667

668
    if (this.ideRoot != null) {
3!
669
      success("IDE_ROOT is set to {}", this.ideRoot);
×
670
    }
671
    if (this.ideHome == null) {
3!
672
      warning(getMessageIdeHomeNotFound());
5✔
673
    } else {
674
      success("IDE_HOME is set to {}", this.ideHome);
×
675
    }
676
  }
1✔
677

678
  @Override
679
  public String askForInput(String message, String defaultValue) {
680

681
    if (!message.isBlank()) {
×
682
      info(message);
×
683
    }
684
    if (isBatchMode()) {
×
685
      if (isForceMode()) {
×
686
        return defaultValue;
×
687
      } else {
688
        throw new CliAbortException();
×
689
      }
690
    }
691
    String input = readLine().trim();
×
692
    return input.isEmpty() ? defaultValue : input;
×
693
  }
694

695
  @Override
696
  public String askForInput(String message) {
697

698
    String input;
699
    do {
700
      info(message);
3✔
701
      input = readLine().trim();
4✔
702
    } while (input.isEmpty());
3!
703

704
    return input;
2✔
705
  }
706

707
  @SuppressWarnings("unchecked")
708
  @Override
709
  public <O> O question(String question, O... options) {
710

711
    assert (options.length >= 2);
×
712
    interaction(question);
×
713
    Map<String, O> mapping = new HashMap<>(options.length);
×
714
    int i = 0;
×
715
    for (O option : options) {
×
716
      i++;
×
717
      String key = "" + option;
×
718
      addMapping(mapping, key, option);
×
719
      String numericKey = Integer.toString(i);
×
720
      if (numericKey.equals(key)) {
×
721
        trace("Options should not be numeric: " + key);
×
722
      } else {
723
        addMapping(mapping, numericKey, option);
×
724
      }
725
      interaction("Option " + numericKey + ": " + key);
×
726
    }
727
    O option = null;
×
728
    if (isBatchMode()) {
×
729
      if (isForceMode()) {
×
730
        option = options[0];
×
731
        interaction("" + option);
×
732
      }
733
    } else {
734
      while (option == null) {
×
735
        String answer = readLine();
×
736
        option = mapping.get(answer);
×
737
        if (option == null) {
×
738
          warning("Invalid answer: '" + answer + "' - please try again.");
×
739
        }
740
      }
×
741
    }
742
    return option;
×
743
  }
744

745
  /**
746
   * @return the input from the end-user (e.g. read from the console).
747
   */
748
  protected abstract String readLine();
749

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

752
    O duplicate = mapping.put(key, option);
×
753
    if (duplicate != null) {
×
754
      throw new IllegalArgumentException("Duplicated option " + key);
×
755
    }
756
  }
×
757

758
  @Override
759
  public Step getCurrentStep() {
760

761
    return this.currentStep;
×
762
  }
763

764
  @Override
765
  public StepImpl newStep(boolean silent, String name, Object... parameters) {
766

767
    this.currentStep = new StepImpl(this, this.currentStep, name, silent, parameters);
11✔
768
    return this.currentStep;
3✔
769
  }
770

771
  /**
772
   * Internal method to end the running {@link Step}.
773
   *
774
   * @param step the current {@link Step} to end.
775
   */
776
  public void endStep(StepImpl step) {
777

778
    if (step == this.currentStep) {
4!
779
      this.currentStep = this.currentStep.getParent();
6✔
780
    } else {
781
      String currentStepName = "null";
×
782
      if (this.currentStep != null) {
×
783
        currentStepName = this.currentStep.getName();
×
784
      }
785
      warning("endStep called with wrong step '{}' but expected '{}'", step.getName(), currentStepName);
×
786
    }
787
  }
1✔
788

789
  /**
790
   * Finds the matching {@link Commandlet} to run, applies {@link CliArguments} to its {@link Commandlet#getProperties() properties} and will execute it.
791
   *
792
   * @param arguments the {@link CliArgument}.
793
   * @return the return code of the execution.
794
   */
795
  public int run(CliArguments arguments) {
796

797
    CliArgument current = arguments.current();
3✔
798
    assert (this.currentStep == null);
4!
799
    boolean supressStepSuccess = false;
2✔
800
    StepImpl step = newStep(true, "ide", (Object[]) current.asArray());
8✔
801
    Iterator<Commandlet> commandletIterator = this.commandletManager.findCommandlet(arguments, null);
6✔
802
    Commandlet cmd = null;
2✔
803
    ValidationResult result = null;
2✔
804
    try {
805
      while (commandletIterator.hasNext()) {
3!
806
        cmd = commandletIterator.next();
4✔
807
        result = applyAndRun(arguments.copy(), cmd);
6✔
808
        if (result.isValid()) {
3!
809
          supressStepSuccess = cmd.isSuppressStepSuccess();
3✔
810
          step.success();
2✔
811
          return ProcessResult.SUCCESS;
4✔
812
        }
813
      }
814
      this.startContext.activateLogging();
×
815
      if (result != null) {
×
816
        error(result.getErrorMessage());
×
817
      }
818
      step.error("Invalid arguments: {}", current.getArgs());
×
819
      HelpCommandlet help = this.commandletManager.getCommandlet(HelpCommandlet.class);
×
820
      if (cmd != null) {
×
821
        help.commandlet.setValue(cmd);
×
822
      }
823
      help.run();
×
824
      return 1;
×
825
    } catch (Throwable t) {
×
826
      this.startContext.activateLogging();
×
827
      step.error(t, true);
×
828
      throw t;
×
829
    } finally {
830
      step.close();
2✔
831
      assert (this.currentStep == null);
4!
832
      step.logSummary(supressStepSuccess);
3✔
833
    }
834
  }
835

836
  /**
837
   * @param cmd the potential {@link Commandlet} to {@link #apply(CliArguments, Commandlet) apply} and {@link Commandlet#run() run}.
838
   * @return {@code true} if the given {@link Commandlet} matched and did {@link Commandlet#run() run} successfully, {@code false} otherwise (the
839
   *     {@link Commandlet} did not match and we have to try a different candidate).
840
   */
841
  private ValidationResult applyAndRun(CliArguments arguments, Commandlet cmd) {
842

843
    IdeLogLevel previousLogLevel = null;
2✔
844
    cmd.reset();
2✔
845
    ValidationResult result = apply(arguments, cmd);
5✔
846
    if (result.isValid()) {
3!
847
      result = cmd.validate();
3✔
848
    }
849
    if (result.isValid()) {
3!
850
      debug("Running commandlet {}", cmd);
9✔
851
      if (cmd.isIdeHomeRequired() && (this.ideHome == null)) {
6!
852
        throw new CliException(getMessageIdeHomeNotFound(), ProcessResult.NO_IDE_HOME);
×
853
      } else if (cmd.isIdeRootRequired() && (this.ideRoot == null)) {
6!
854
        throw new CliException(getMessageIdeRootNotFound(), ProcessResult.NO_IDE_ROOT);
×
855
      }
856
      try {
857
        if (cmd.isProcessableOutput()) {
3!
858
          if (!debug().isEnabled()) {
×
859
            // unless --debug or --trace was supplied, processable output commandlets will disable all log-levels except INFO to prevent other logs interfere
860
            previousLogLevel = this.startContext.setLogLevel(IdeLogLevel.PROCESSABLE);
×
861
          }
862
          this.startContext.activateLogging();
×
863
        } else {
864
          this.startContext.activateLogging();
3✔
865
          verifyIdeRoot();
2✔
866
          if (cmd.isIdeHomeRequired()) {
3✔
867
            debug(getMessageIdeHomeFound());
4✔
868
          }
869
          Path settingsRepository = getSettingsGitRepository();
3✔
870
          if (settingsRepository != null) {
2!
871
            if (getGitContext().isRepositoryUpdateAvailable(settingsRepository, getSettingsCommitIdPath()) ||
×
872
                (getGitContext().fetchIfNeeded(settingsRepository) && getGitContext().isRepositoryUpdateAvailable(settingsRepository, getSettingsCommitIdPath()))) {
×
873
              interaction("Updates are available for the settings repository. If you want to apply the latest changes, call \"ide update\"");
×
874
            }
875
          }
876
        }
877
        cmd.run();
2✔
878
      } finally {
879
        if (previousLogLevel != null) {
2!
880
          this.startContext.setLogLevel(previousLogLevel);
×
881
        }
882
      }
1✔
883
    } else {
884
      trace("Commandlet did not match");
×
885
    }
886
    return result;
2✔
887
  }
888

889
  private void verifyIdeRoot() {
890
    if (!isTest()) {
3!
891
      if (this.ideRoot == null) {
×
892
        warning("Variable IDE_ROOT is undefined. Please check your installation or run setup script again.");
×
893
      } else if (this.ideHome != null) {
×
894
        Path ideRootPath = getIdeRootPathFromEnv();
×
895
        if (!this.ideRoot.equals(ideRootPath)) {
×
896
          warning("Variable IDE_ROOT is set to '{}' but for your project '{}' the path '{}' would have been expected.", ideRootPath,
×
897
              this.ideHome.getFileName(), this.ideRoot);
×
898
        }
899
      }
900
    }
901
  }
1✔
902

903
  /**
904
   * @param arguments the {@link CliArguments#ofCompletion(String...) completion arguments}.
905
   * @param includeContextOptions to include the options of {@link ContextCommandlet}.
906
   * @return the {@link List} of {@link CompletionCandidate}s to suggest.
907
   */
908
  public List<CompletionCandidate> complete(CliArguments arguments, boolean includeContextOptions) {
909
    CompletionCandidateCollector collector = new CompletionCandidateCollectorDefault(this);
5✔
910
    if (arguments.current().isStart()) {
4✔
911
      arguments.next();
3✔
912
    }
913
    if (includeContextOptions) {
2✔
914
      ContextCommandlet cc = new ContextCommandlet();
4✔
915
      for (Property<?> property : cc.getProperties()) {
11✔
916
        assert (property.isOption());
4!
917
        property.apply(arguments, this, cc, collector);
7✔
918
      }
1✔
919
    }
920
    Iterator<Commandlet> commandletIterator = this.commandletManager.findCommandlet(arguments, collector);
6✔
921
    CliArgument current = arguments.current();
3✔
922
    if (current.isCompletion() && current.isCombinedShortOption()) {
6✔
923
      collector.add(current.get(), null, null, null);
7✔
924
    }
925
    arguments.next();
3✔
926
    while (commandletIterator.hasNext()) {
3✔
927
      Commandlet cmd = commandletIterator.next();
4✔
928
      if (!arguments.current().isEnd()) {
4✔
929
        completeCommandlet(arguments.copy(), cmd, collector);
6✔
930
      }
931
    }
1✔
932
    return collector.getSortedCandidates();
3✔
933
  }
934

935
  private void completeCommandlet(CliArguments arguments, Commandlet cmd, CompletionCandidateCollector collector) {
936
    trace("Trying to match arguments for auto-completion for commandlet {}", cmd.getName());
10✔
937
    Iterator<Property<?>> valueIterator = cmd.getValues().iterator();
4✔
938
    valueIterator.next(); // skip first property since this is the keyword property that already matched to find the commandlet
3✔
939
    List<Property<?>> properties = cmd.getProperties();
3✔
940
    // we are creating our own list of options and remove them when matched to avoid duplicate suggestions
941
    List<Property<?>> optionProperties = new ArrayList<>(properties.size());
6✔
942
    for (Property<?> property : properties) {
10✔
943
      if (property.isOption()) {
3✔
944
        optionProperties.add(property);
4✔
945
      }
946
    }
1✔
947
    CliArgument currentArgument = arguments.current();
3✔
948
    while (!currentArgument.isEnd()) {
3✔
949
      trace("Trying to match argument '{}'", currentArgument);
9✔
950
      if (currentArgument.isOption() && !arguments.isEndOptions()) {
6!
951
        if (currentArgument.isCompletion()) {
3✔
952
          Iterator<Property<?>> optionIterator = optionProperties.iterator();
3✔
953
          while (optionIterator.hasNext()) {
3✔
954
            Property<?> option = optionIterator.next();
4✔
955
            boolean success = option.apply(arguments, this, cmd, collector);
7✔
956
            if (success) {
2✔
957
              optionIterator.remove();
2✔
958
              arguments.next();
3✔
959
            }
960
          }
1✔
961
        } else {
1✔
962
          Property<?> option = cmd.getOption(currentArgument.get());
5✔
963
          if (option != null) {
2✔
964
            arguments.next();
3✔
965
            boolean removed = optionProperties.remove(option);
4✔
966
            if (!removed) {
2!
967
              option = null;
×
968
            }
969
          }
970
          if (option == null) {
2✔
971
            trace("No such option was found.");
3✔
972
            return;
1✔
973
          }
974
        }
1✔
975
      } else {
976
        if (valueIterator.hasNext()) {
3✔
977
          Property<?> valueProperty = valueIterator.next();
4✔
978
          boolean success = valueProperty.apply(arguments, this, cmd, collector);
7✔
979
          if (!success) {
2!
980
            trace("Completion cannot match any further.");
×
981
            return;
×
982
          }
983
        } else {
1✔
984
          trace("No value left for completion.");
3✔
985
          return;
1✔
986
        }
987
      }
988
      currentArgument = arguments.current();
4✔
989
    }
990
  }
1✔
991

992

993
  /**
994
   * @param arguments the {@link CliArguments} to apply. Will be {@link CliArguments#next() consumed} as they are matched. Consider passing a
995
   *     {@link CliArguments#copy() copy} as needed.
996
   * @param cmd the potential {@link Commandlet} to match.
997
   * @return the {@link ValidationResult} telling if the {@link CliArguments} can be applied successfully or if validation errors ocurred.
998
   */
999
  public ValidationResult apply(CliArguments arguments, Commandlet cmd) {
1000

1001
    trace("Trying to match arguments to commandlet {}", cmd.getName());
10✔
1002
    CliArgument currentArgument = arguments.current();
3✔
1003
    Iterator<Property<?>> propertyIterator = cmd.getValues().iterator();
4✔
1004
    Property<?> property = null;
2✔
1005
    if (propertyIterator.hasNext()) {
3!
1006
      property = propertyIterator.next();
4✔
1007
    }
1008
    while (!currentArgument.isEnd()) {
3✔
1009
      trace("Trying to match argument '{}'", currentArgument);
9✔
1010
      Property<?> currentProperty = property;
2✔
1011
      if (!arguments.isEndOptions()) {
3!
1012
        Property<?> option = cmd.getOption(currentArgument.getKey());
5✔
1013
        if (option != null) {
2!
1014
          currentProperty = option;
×
1015
        }
1016
      }
1017
      if (currentProperty == null) {
2!
1018
        trace("No option or next value found");
×
1019
        ValidationState state = new ValidationState(null);
×
1020
        state.addErrorMessage("No matching property found");
×
1021
        return state;
×
1022
      }
1023
      trace("Next property candidate to match argument is {}", currentProperty);
9✔
1024
      if (currentProperty == property) {
3!
1025
        if (!property.isMultiValued()) {
3✔
1026
          if (propertyIterator.hasNext()) {
3✔
1027
            property = propertyIterator.next();
5✔
1028
          } else {
1029
            property = null;
2✔
1030
          }
1031
        }
1032
        if ((property != null) && property.isValue() && property.isMultiValued()) {
8!
1033
          arguments.stopSplitShortOptions();
2✔
1034
        }
1035
      }
1036
      boolean matches = currentProperty.apply(arguments, this, cmd, null);
7✔
1037
      if (!matches && currentArgument.isCompletion()) {
2!
1038
        ValidationState state = new ValidationState(null);
×
1039
        state.addErrorMessage("No matching property found");
×
1040
        return state;
×
1041
      }
1042
      currentArgument = arguments.current();
3✔
1043
    }
1✔
1044
    return ValidationResultValid.get();
2✔
1045
  }
1046

1047
  @Override
1048
  public String findBash() {
1049

1050
    String bash = "bash";
2✔
1051
    if (SystemInfoImpl.INSTANCE.isWindows()) {
3!
1052
      bash = findBashOnWindows();
×
1053
    }
1054

1055
    return bash;
2✔
1056
  }
1057

1058
  private String findBashOnWindows() {
1059

1060
    // Check if Git Bash exists in the default location
1061
    Path defaultPath = Path.of("C:\\Program Files\\Git\\bin\\bash.exe");
×
1062
    if (Files.exists(defaultPath)) {
×
1063
      return defaultPath.toString();
×
1064
    }
1065

1066
    // If not found in the default location, try the registry query
1067
    String[] bashVariants = { "GitForWindows", "Cygwin\\setup" };
×
1068
    String[] registryKeys = { "HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER" };
×
1069
    String regQueryResult;
1070
    for (String bashVariant : bashVariants) {
×
1071
      for (String registryKey : registryKeys) {
×
1072
        String toolValueName = ("GitForWindows".equals(bashVariant)) ? "InstallPath" : "rootdir";
×
1073
        String command = "reg query " + registryKey + "\\Software\\" + bashVariant + "  /v " + toolValueName + " 2>nul";
×
1074

1075
        try {
1076
          Process process = new ProcessBuilder("cmd.exe", "/c", command).start();
×
1077
          try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
×
1078
            StringBuilder output = new StringBuilder();
×
1079
            String line;
1080

1081
            while ((line = reader.readLine()) != null) {
×
1082
              output.append(line);
×
1083
            }
1084

1085
            int exitCode = process.waitFor();
×
1086
            if (exitCode != 0) {
×
1087
              return null;
×
1088
            }
1089

1090
            regQueryResult = output.toString();
×
1091
            if (regQueryResult != null) {
×
1092
              int index = regQueryResult.indexOf("REG_SZ");
×
1093
              if (index != -1) {
×
1094
                String path = regQueryResult.substring(index + "REG_SZ".length()).trim();
×
1095
                return path + "\\bin\\bash.exe";
×
1096
              }
1097
            }
1098

1099
          }
×
1100
        } catch (Exception e) {
×
1101
          return null;
×
1102
        }
×
1103
      }
1104
    }
1105
    // no bash found
1106
    return null;
×
1107
  }
1108

1109
  @Override
1110
  public WindowsPathSyntax getPathSyntax() {
1111
    return this.pathSyntax;
3✔
1112
  }
1113

1114
  /**
1115
   * @param pathSyntax new value of {@link #getPathSyntax()}.
1116
   */
1117
  public void setPathSyntax(WindowsPathSyntax pathSyntax) {
1118

1119
    this.pathSyntax = pathSyntax;
3✔
1120
  }
1✔
1121

1122
  /**
1123
   * @return the {@link IdeStartContextImpl}.
1124
   */
1125
  public IdeStartContextImpl getStartContext() {
1126

1127
    return startContext;
3✔
1128
  }
1129

1130
  /**
1131
   * Reloads this context and re-initializes the {@link #getVariables() variables}.
1132
   */
1133
  public void reload() {
1134
    this.variables = null;
3✔
1135
    this.customToolRepository = null;
3✔
1136
  }
1✔
1137
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc