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

devonfw / IDEasy / 12765982517

14 Jan 2025 10:42AM UTC coverage: 67.829% (-0.3%) from 68.082%
12765982517

push

github

web-flow
#757: Settings in code repository (#850)

2691 of 4335 branches covered (62.08%)

Branch coverage included in aggregate %.

6961 of 9895 relevant lines covered (70.35%)

3.09 hits per line

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

62.11
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
    this.customToolRepository = CustomToolRepositoryImpl.of(this);
4✔
266
  }
1✔
267

268
  private String getMessageIdeHomeFound() {
269

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

273
  private String getMessageIdeHomeNotFound() {
274

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

278
  private String getMessageIdeRootNotFound() {
279
    String root = getSystem().getEnv("IDE_ROOT");
×
280
    if (root == null) {
×
281
      return "The environment variable IDE_ROOT is undefined. Please reinstall IDEasy or manually repair IDE_ROOT variable.";
×
282
    } else {
283
      return "The environment variable IDE_ROOT is pointing to an invalid path " + root + ". Please reinstall IDEasy or manually repair IDE_ROOT variable.";
×
284
    }
285
  }
286

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

292
    return false;
×
293
  }
294

295
  protected SystemPath computeSystemPath() {
296

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

300

301
  private boolean isIdeHome(Path dir) {
302

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

311
  private EnvironmentVariables createVariables() {
312

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

321
  protected AbstractEnvironmentVariables createSystemVariables() {
322

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

326
  @Override
327
  public SystemInfo getSystemInfo() {
328

329
    return this.systemInfo;
3✔
330
  }
331

332
  @Override
333
  public FileAccess getFileAccess() {
334

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

340
  @Override
341
  public CommandletManager getCommandletManager() {
342

343
    return this.commandletManager;
3✔
344
  }
345

346
  @Override
347
  public ToolRepository getDefaultToolRepository() {
348

349
    return this.defaultToolRepository;
3✔
350
  }
351

352
  @Override
353
  public CustomToolRepository getCustomToolRepository() {
354

355
    return this.customToolRepository;
3✔
356
  }
357

358
  @Override
359
  public Path getIdeHome() {
360

361
    return this.ideHome;
3✔
362
  }
363

364
  @Override
365
  public String getProjectName() {
366

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

373
  @Override
374
  public Path getIdeRoot() {
375

376
    return this.ideRoot;
3✔
377
  }
378

379
  @Override
380
  public Path getCwd() {
381

382
    return this.cwd;
3✔
383
  }
384

385
  @Override
386
  public Path getTempPath() {
387

388
    return this.tempPath;
3✔
389
  }
390

391
  @Override
392
  public Path getTempDownloadPath() {
393

394
    return this.tempDownloadPath;
3✔
395
  }
396

397
  @Override
398
  public Path getUserHome() {
399

400
    return this.userHome;
3✔
401
  }
402

403
  @Override
404
  public Path getUserHomeIde() {
405

406
    return this.userHomeIde;
3✔
407
  }
408

409
  @Override
410
  public Path getSettingsPath() {
411

412
    return this.settingsPath;
3✔
413
  }
414

415
  @Override
416
  public Path getSettingsGitRepository() {
417

418
    Path settingsPath = getSettingsPath();
3✔
419

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

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

431
    return settingsPath;
×
432
  }
433

434
  @Override
435
  public Path getSettingsCommitIdPath() {
436

437
    return this.settingsCommitIdPath;
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
    if (this.variables == null) {
3✔
510
      this.variables = createVariables();
4✔
511
    }
512
    return this.variables;
3✔
513
  }
514

515
  @Override
516
  public UrlMetadata getUrls() {
517

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

527
  @Override
528
  public boolean isQuietMode() {
529

530
    return this.startContext.isQuietMode();
4✔
531
  }
532

533
  @Override
534
  public boolean isBatchMode() {
535

536
    return this.startContext.isBatchMode();
×
537
  }
538

539
  @Override
540
  public boolean isForceMode() {
541

542
    return this.startContext.isForceMode();
4✔
543
  }
544

545
  @Override
546
  public boolean isOfflineMode() {
547

548
    return this.startContext.isOfflineMode();
4✔
549
  }
550

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

556
  @Override
557
  public boolean isOnline() {
558

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

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

585
  @Override
586
  public Locale getLocale() {
587

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

595
  @Override
596
  public DirectoryMerger getWorkspaceMerger() {
597

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

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

610
    return this.defaultExecutionDirectory;
×
611
  }
612

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

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

623
  @Override
624
  public GitContext getGitContext() {
625

626
    return new GitContextImpl(this);
×
627
  }
628

629
  @Override
630
  public ProcessContext newProcess() {
631

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

639
  @Override
640
  public IdeSystem getSystem() {
641

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

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

654
    return new ProcessContextImpl(this);
×
655
  }
656

657
  @Override
658
  public IdeSubLogger level(IdeLogLevel level) {
659

660
    return this.startContext.level(level);
5✔
661
  }
662

663
  @Override
664
  public void logIdeHomeAndRootStatus() {
665

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

676
  @Override
677
  public String askForInput(String message, String defaultValue) {
678

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

693
  @Override
694
  public String askForInput(String message) {
695

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

702
    return input;
2✔
703
  }
704

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

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

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

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

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

756
  @Override
757
  public Step getCurrentStep() {
758

759
    return this.currentStep;
×
760
  }
761

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

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

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

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

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

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

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

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

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

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

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

990

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

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

1045
  @Override
1046
  public String findBash() {
1047

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

1053
    return bash;
2✔
1054
  }
1055

1056
  private String findBashOnWindows() {
1057

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

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

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

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

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

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

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

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

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

1117
    this.pathSyntax = pathSyntax;
3✔
1118
  }
1✔
1119

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

1125
    return startContext;
3✔
1126
  }
1127

1128
  /**
1129
   * Reloads this context and re-initializes the {@link #getVariables() variables}.
1130
   */
1131
  public void reload() {
1132
    this.variables = null;
3✔
1133
  }
1✔
1134
}
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