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

devonfw / IDEasy / 9907372175

12 Jul 2024 11:49AM UTC coverage: 61.142% (-0.02%) from 61.162%
9907372175

push

github

hohwille
fixed tests

1997 of 3595 branches covered (55.55%)

Branch coverage included in aggregate %.

5296 of 8333 relevant lines covered (63.55%)

2.8 hits per line

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

53.37
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.IOException;
5
import java.io.InputStreamReader;
6
import java.net.URL;
7
import java.net.URLConnection;
8
import java.nio.file.Files;
9
import java.nio.file.Path;
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
import java.util.Objects;
16
import java.util.function.Function;
17

18
import com.devonfw.tools.ide.cli.CliAbortException;
19
import com.devonfw.tools.ide.cli.CliArgument;
20
import com.devonfw.tools.ide.cli.CliArguments;
21
import com.devonfw.tools.ide.cli.CliException;
22
import com.devonfw.tools.ide.commandlet.Commandlet;
23
import com.devonfw.tools.ide.commandlet.CommandletManager;
24
import com.devonfw.tools.ide.commandlet.CommandletManagerImpl;
25
import com.devonfw.tools.ide.commandlet.ContextCommandlet;
26
import com.devonfw.tools.ide.commandlet.HelpCommandlet;
27
import com.devonfw.tools.ide.common.SystemPath;
28
import com.devonfw.tools.ide.completion.CompletionCandidate;
29
import com.devonfw.tools.ide.completion.CompletionCandidateCollector;
30
import com.devonfw.tools.ide.completion.CompletionCandidateCollectorDefault;
31
import com.devonfw.tools.ide.environment.AbstractEnvironmentVariables;
32
import com.devonfw.tools.ide.environment.EnvironmentVariables;
33
import com.devonfw.tools.ide.environment.EnvironmentVariablesType;
34
import com.devonfw.tools.ide.io.FileAccess;
35
import com.devonfw.tools.ide.io.FileAccessImpl;
36
import com.devonfw.tools.ide.log.IdeLogLevel;
37
import com.devonfw.tools.ide.log.IdeSubLogger;
38
import com.devonfw.tools.ide.log.IdeSubLoggerNone;
39
import com.devonfw.tools.ide.merge.DirectoryMerger;
40
import com.devonfw.tools.ide.network.ProxyContext;
41
import com.devonfw.tools.ide.os.SystemInfo;
42
import com.devonfw.tools.ide.os.SystemInfoImpl;
43
import com.devonfw.tools.ide.os.WindowsPathSyntax;
44
import com.devonfw.tools.ide.process.ProcessContext;
45
import com.devonfw.tools.ide.process.ProcessContextImpl;
46
import com.devonfw.tools.ide.process.ProcessResult;
47
import com.devonfw.tools.ide.property.Property;
48
import com.devonfw.tools.ide.repo.CustomToolRepository;
49
import com.devonfw.tools.ide.repo.CustomToolRepositoryImpl;
50
import com.devonfw.tools.ide.repo.DefaultToolRepository;
51
import com.devonfw.tools.ide.repo.ToolRepository;
52
import com.devonfw.tools.ide.step.Step;
53
import com.devonfw.tools.ide.step.StepImpl;
54
import com.devonfw.tools.ide.url.model.UrlMetadata;
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 Map<IdeLogLevel, IdeSubLogger> loggers;
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 toolRepository;
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 final ToolRepository defaultToolRepository;
114

115
  private CustomToolRepository customToolRepository;
116

117
  private DirectoryMerger workspaceMerger;
118

119
  private final Function<IdeLogLevel, IdeSubLogger> loggerFactory;
120

121
  private boolean offlineMode;
122

123
  private boolean forceMode;
124

125
  private boolean batchMode;
126

127
  private boolean quietMode;
128

129
  private Locale locale;
130

131
  private UrlMetadata urlMetadata;
132

133
  private Path defaultExecutionDirectory;
134

135
  private StepImpl currentStep;
136

137
  /**
138
   * The constructor.
139
   *
140
   * @param minLogLevel the minimum {@link IdeLogLevel} to enable. Should be {@link IdeLogLevel#INFO} by default.
141
   * @param factory the {@link Function} to create {@link IdeSubLogger} per {@link IdeLogLevel}.
142
   * @param userDir the optional {@link Path} to current working directory.
143
   * @param toolRepository @param toolRepository the {@link ToolRepository} of the context. If it is set to {@code null} {@link DefaultToolRepository} will be
144
   * used.
145
   */
146
  public AbstractIdeContext(IdeLogLevel minLogLevel, Function<IdeLogLevel, IdeSubLogger> factory, Path userDir, ToolRepository toolRepository) {
147

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

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

184
    setCwd(userDir, workspace, currentDir);
5✔
185

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

206
    if (toolRepository == null) {
2✔
207
      this.defaultToolRepository = new DefaultToolRepository(this);
7✔
208
    } else {
209
      this.defaultToolRepository = toolRepository;
3✔
210
    }
211
  }
1✔
212

213
  private Path findIdeRoot(Path ideHomePath) {
214
    final Path ideRoot;
215
    Path ideRootPath = null;
2✔
216
    if (ideHomePath != null) {
2✔
217
      ideRootPath = ideHomePath.getParent();
3✔
218
    }
219

220
    if (!isTest()) {
3✔
221
      String root = System.getenv("IDE_ROOT");
3✔
222
      if (root != null) {
2!
223
        Path rootPath = Path.of(root);
×
224
        if ((ideRootPath == null)) {
×
225
          if (Files.isDirectory(rootPath)) {
×
226
            ideRootPath = rootPath;
×
227
          }
228
        } else if (!ideRootPath.equals(rootPath)) {
×
229
          warning("Variable IDE_ROOT is set to '{}' but for your project '{}' the path '{}' would have been expected.", rootPath, this.ideHome.getFileName(),
×
230
              ideRootPath);
231
        }
232
      }
233
    }
234
    return ideRootPath;
2✔
235
  }
236

237
  @Override
238
  public void setCwd(Path userDir, String workspace, Path ideHome) {
239

240
    this.cwd = userDir;
3✔
241
    this.workspaceName = workspace;
3✔
242
    this.ideHome = ideHome;
3✔
243
    if (ideHome == null) {
2✔
244
      this.workspacePath = null;
3✔
245
      this.confPath = null;
3✔
246
      this.settingsPath = null;
3✔
247
      this.softwarePath = null;
3✔
248
      this.softwareExtraPath = null;
3✔
249
      this.pluginsPath = null;
4✔
250
    } else {
251
      this.workspacePath = this.ideHome.resolve(FOLDER_WORKSPACES).resolve(this.workspaceName);
9✔
252
      this.confPath = this.ideHome.resolve(FOLDER_CONF);
6✔
253
      this.settingsPath = this.ideHome.resolve(FOLDER_SETTINGS);
6✔
254
      this.softwarePath = this.ideHome.resolve(FOLDER_SOFTWARE);
6✔
255
      this.softwareExtraPath = this.softwarePath.resolve(FOLDER_EXTRA);
6✔
256
      this.pluginsPath = this.ideHome.resolve(FOLDER_PLUGINS);
6✔
257
    }
258
    if (isTest()) {
3✔
259
      // only for testing...
260
      if (this.ideHome == null) {
3✔
261
        this.userHome = Path.of("/non-existing-user-home-for-testing");
7✔
262
      } else {
263
        this.userHome = this.ideHome.resolve("home");
7✔
264
      }
265
    } else {
266
      this.userHome = Path.of(System.getProperty("user.home"));
7✔
267
    }
268
    this.userHomeIde = this.userHome.resolve(".ide");
6✔
269
    this.downloadPath = this.userHome.resolve("Downloads/ide");
6✔
270

271
    this.variables = createVariables();
4✔
272
    this.path = computeSystemPath();
4✔
273
    this.customToolRepository = CustomToolRepositoryImpl.of(this);
4✔
274
    this.workspaceMerger = new DirectoryMerger(this);
6✔
275
  }
1✔
276

277
  private String getMessageIdeHomeFound() {
278

279
    return "IDE environment variables have been set for " + this.ideHome + " in workspace " + this.workspaceName;
×
280
  }
281

282
  private String getMessageIdeHomeNotFound() {
283

284
    return "You are not inside an IDE installation: " + this.cwd;
×
285
  }
286

287
  private static String getMessageIdeRootNotFound() {
288
    String root = System.getenv("IDE_ROOT");
×
289
    if (root == null) {
×
290
      return "The environment variable IDE_ROOT is undefined. Please reinstall IDEasy or manually repair IDE_ROOT variable.";
×
291
    } else {
292
      return "The environment variable IDE_ROOT is pointing to an invalid path " + root + ". Please reinstall IDEasy or manually repair IDE_ROOT variable.";
×
293
    }
294
  }
295

296
  /**
297
   * @return the status message about the {@link #getIdeHome() IDE_HOME} detection and environment variable initialization.
298
   */
299
  public String getMessageIdeHome() {
300

301
    if (this.ideHome == null) {
×
302
      return getMessageIdeHomeNotFound();
×
303
    }
304
    return getMessageIdeHomeFound();
×
305
  }
306

307
  /**
308
   * @return {@code true} if this is a test context for JUnits, {@code false} otherwise.
309
   */
310
  public boolean isTest() {
311

312
    return isMock();
3✔
313
  }
314

315
  /**
316
   * @return {@code true} if this is a mock context for JUnits, {@code false} otherwise.
317
   */
318
  public boolean isMock() {
319

320
    return false;
2✔
321
  }
322

323
  private SystemPath computeSystemPath() {
324

325
    return new SystemPath(this);
5✔
326
  }
327

328
  private boolean isIdeHome(Path dir) {
329

330
    if (!Files.isDirectory(dir.resolve("workspaces"))) {
7✔
331
      return false;
2✔
332
    } else if (!Files.isDirectory(dir.resolve("settings"))) {
7!
333
      return false;
×
334
    }
335
    return true;
2✔
336
  }
337

338
  private Path getParentPath(Path dir) {
339

340
    try {
341
      Path linkDir = dir.toRealPath();
5✔
342
      if (!dir.equals(linkDir)) {
4!
343
        return linkDir;
×
344
      } else {
345
        return dir.getParent();
3✔
346
      }
347
    } catch (IOException e) {
×
348
      throw new IllegalStateException(e);
×
349
    }
350

351
  }
352

353
  private EnvironmentVariables createVariables() {
354

355
    AbstractEnvironmentVariables system = EnvironmentVariables.ofSystem(this);
3✔
356
    AbstractEnvironmentVariables user = extendVariables(system, this.userHomeIde, EnvironmentVariablesType.USER);
7✔
357
    AbstractEnvironmentVariables settings = extendVariables(user, this.settingsPath, EnvironmentVariablesType.SETTINGS);
7✔
358
    // TODO should we keep this workspace properties? Was this feature ever used?
359
    AbstractEnvironmentVariables workspace = extendVariables(settings, this.workspacePath, EnvironmentVariablesType.WORKSPACE);
7✔
360
    AbstractEnvironmentVariables conf = extendVariables(workspace, this.confPath, EnvironmentVariablesType.CONF);
7✔
361
    return conf.resolved();
3✔
362
  }
363

364
  private AbstractEnvironmentVariables extendVariables(AbstractEnvironmentVariables envVariables, Path propertiesPath, EnvironmentVariablesType type) {
365

366
    Path propertiesFile = null;
2✔
367
    if (propertiesPath == null) {
2✔
368
      trace("Configuration directory for type {} does not exist.", type);
10✔
369
    } else if (Files.isDirectory(propertiesPath)) {
5✔
370
      propertiesFile = propertiesPath.resolve(EnvironmentVariables.DEFAULT_PROPERTIES);
4✔
371
      boolean legacySupport = (type != EnvironmentVariablesType.USER);
7✔
372
      if (legacySupport && !Files.exists(propertiesFile)) {
7✔
373
        Path legacyFile = propertiesPath.resolve(EnvironmentVariables.LEGACY_PROPERTIES);
4✔
374
        if (Files.exists(legacyFile)) {
5!
375
          propertiesFile = legacyFile;
×
376
        }
377
      }
378
    } else {
1✔
379
      debug("Configuration directory {} does not exist.", propertiesPath);
9✔
380
    }
381
    return envVariables.extend(propertiesFile, type);
5✔
382
  }
383

384
  @Override
385
  public SystemInfo getSystemInfo() {
386

387
    return this.systemInfo;
3✔
388
  }
389

390
  @Override
391
  public FileAccess getFileAccess() {
392

393
    return this.fileAccess;
3✔
394
  }
395

396
  @Override
397
  public CommandletManager getCommandletManager() {
398

399
    return this.commandletManager;
3✔
400
  }
401

402
  @Override
403
  public ToolRepository getDefaultToolRepository() {
404

405
    return this.defaultToolRepository;
3✔
406
  }
407

408
  @Override
409
  public CustomToolRepository getCustomToolRepository() {
410

411
    return this.customToolRepository;
3✔
412
  }
413

414
  @Override
415
  public Path getIdeHome() {
416

417
    return this.ideHome;
3✔
418
  }
419

420
  @Override
421
  public String getProjectName() {
422

423
    if (this.ideHome != null) {
3!
424
      return this.ideHome.getFileName().toString();
5✔
425
    }
426
    return "";
×
427
  }
428

429
  @Override
430
  public Path getIdeRoot() {
431

432
    return this.ideRoot;
3✔
433
  }
434

435
  @Override
436
  public Path getCwd() {
437

438
    return this.cwd;
3✔
439
  }
440

441
  @Override
442
  public Path getTempPath() {
443

444
    return this.tempPath;
3✔
445
  }
446

447
  @Override
448
  public Path getTempDownloadPath() {
449

450
    return this.tempDownloadPath;
3✔
451
  }
452

453
  @Override
454
  public Path getUserHome() {
455

456
    return this.userHome;
3✔
457
  }
458

459
  @Override
460
  public Path getUserHomeIde() {
461

462
    return this.userHomeIde;
3✔
463
  }
464

465
  @Override
466
  public Path getSettingsPath() {
467

468
    return this.settingsPath;
3✔
469
  }
470

471
  @Override
472
  public Path getConfPath() {
473

474
    return this.confPath;
3✔
475
  }
476

477
  @Override
478
  public Path getSoftwarePath() {
479

480
    return this.softwarePath;
3✔
481
  }
482

483
  @Override
484
  public Path getSoftwareExtraPath() {
485

486
    return this.softwareExtraPath;
3✔
487
  }
488

489
  @Override
490
  public Path getSoftwareRepositoryPath() {
491

492
    return this.softwareRepositoryPath;
3✔
493
  }
494

495
  @Override
496
  public Path getPluginsPath() {
497

498
    return this.pluginsPath;
3✔
499
  }
500

501
  @Override
502
  public String getWorkspaceName() {
503

504
    return this.workspaceName;
3✔
505
  }
506

507
  @Override
508
  public Path getWorkspacePath() {
509

510
    return this.workspacePath;
3✔
511
  }
512

513
  @Override
514
  public Path getDownloadPath() {
515

516
    return this.downloadPath;
3✔
517
  }
518

519
  @Override
520
  public Path getUrlsPath() {
521

522
    return this.urlsPath;
3✔
523
  }
524

525
  @Override
526
  public Path getToolRepositoryPath() {
527

528
    return this.toolRepository;
3✔
529
  }
530

531
  @Override
532
  public SystemPath getPath() {
533

534
    return this.path;
3✔
535
  }
536

537
  @Override
538
  public EnvironmentVariables getVariables() {
539

540
    return this.variables;
3✔
541
  }
542

543
  @Override
544
  public UrlMetadata getUrls() {
545

546
    if (this.urlMetadata == null) {
3✔
547
      if (!isTest()) {
3!
548
        getGitContext().pullOrCloneAndResetIfNeeded(IDE_URLS_GIT, this.urlsPath, null);
×
549
      }
550
      this.urlMetadata = new UrlMetadata(this);
6✔
551
    }
552
    return this.urlMetadata;
3✔
553
  }
554

555
  @Override
556
  public boolean isQuietMode() {
557

558
    return this.quietMode;
3✔
559
  }
560

561
  /**
562
   * @param quietMode new value of {@link #isQuietMode()}.
563
   */
564
  public void setQuietMode(boolean quietMode) {
565

566
    this.quietMode = quietMode;
3✔
567
  }
1✔
568

569
  @Override
570
  public boolean isBatchMode() {
571

572
    return this.batchMode;
3✔
573
  }
574

575
  /**
576
   * @param batchMode new value of {@link #isBatchMode()}.
577
   */
578
  public void setBatchMode(boolean batchMode) {
579

580
    this.batchMode = batchMode;
3✔
581
  }
1✔
582

583
  @Override
584
  public boolean isForceMode() {
585

586
    return this.forceMode;
3✔
587
  }
588

589
  /**
590
   * @param forceMode new value of {@link #isForceMode()}.
591
   */
592
  public void setForceMode(boolean forceMode) {
593

594
    this.forceMode = forceMode;
3✔
595
  }
1✔
596

597
  @Override
598
  public boolean isOfflineMode() {
599

600
    return this.offlineMode;
3✔
601
  }
602

603
  /**
604
   * @param offlineMode new value of {@link #isOfflineMode()}.
605
   */
606
  public void setOfflineMode(boolean offlineMode) {
607

608
    this.offlineMode = offlineMode;
3✔
609
  }
1✔
610

611
  @Override
612
  public boolean isOnline() {
613

614
    boolean online = false;
×
615
    try {
616
      int timeout = 1000;
×
617
      //open a connection to github.com and try to retrieve data
618
      //getContent fails if there is no connection
619
      URLConnection connection = new URL("https://www.github.com").openConnection();
×
620
      connection.setConnectTimeout(timeout);
×
621
      connection.getContent();
×
622
      online = true;
×
623

624
    } catch (Exception ignored) {
×
625

626
    }
×
627
    return online;
×
628
  }
629

630
  @Override
631
  public Locale getLocale() {
632

633
    if (this.locale == null) {
3!
634
      return Locale.getDefault();
2✔
635
    }
636
    return this.locale;
×
637
  }
638

639
  /**
640
   * @param locale new value of {@link #getLocale()}.
641
   */
642
  public void setLocale(Locale locale) {
643

644
    this.locale = locale;
3✔
645
  }
1✔
646

647
  @Override
648
  public DirectoryMerger getWorkspaceMerger() {
649

650
    return this.workspaceMerger;
3✔
651
  }
652

653
  /**
654
   * @return the {@link #getDefaultExecutionDirectory() default execution directory} in which a command process is executed.
655
   */
656
  @Override
657
  public Path getDefaultExecutionDirectory() {
658

659
    return this.defaultExecutionDirectory;
×
660
  }
661

662
  /**
663
   * @param defaultExecutionDirectory new value of {@link #getDefaultExecutionDirectory()}.
664
   */
665
  public void setDefaultExecutionDirectory(Path defaultExecutionDirectory) {
666

667
    if (defaultExecutionDirectory != null) {
×
668
      this.defaultExecutionDirectory = defaultExecutionDirectory;
×
669
    }
670
  }
×
671

672
  @Override
673
  public ProxyContext getProxyContext() {
674

675
    return new ProxyContext(this);
5✔
676
  }
677

678
  @Override
679
  public GitContext getGitContext() {
680

681
    return new GitContextImpl(this);
×
682
  }
683

684
  @Override
685
  public ProcessContext newProcess() {
686

687
    ProcessContext processContext = createProcessContext();
3✔
688
    if (this.defaultExecutionDirectory != null) {
3!
689
      processContext.directory(this.defaultExecutionDirectory);
×
690
    }
691
    return processContext;
2✔
692
  }
693

694
  /**
695
   * @return a new instance of {@link ProcessContext}.
696
   * @see #newProcess()
697
   */
698
  protected ProcessContext createProcessContext() {
699

700
    return new ProcessContextImpl(this);
×
701
  }
702

703
  @Override
704
  public IdeSubLogger level(IdeLogLevel level) {
705

706
    IdeSubLogger logger = this.loggers.get(level);
6✔
707
    Objects.requireNonNull(logger);
3✔
708
    return logger;
2✔
709
  }
710

711
  @Override
712
  public String askForInput(String message, String defaultValue) {
713

714
    if (!message.isBlank()) {
×
715
      info(message);
×
716
    }
717
    if (isBatchMode()) {
×
718
      if (isForceMode()) {
×
719
        return defaultValue;
×
720
      } else {
721
        throw new CliAbortException();
×
722
      }
723
    }
724
    String input = readLine().trim();
×
725
    return input.isEmpty() ? defaultValue : input;
×
726
  }
727

728
  @Override
729
  public String askForInput(String message) {
730

731
    String input;
732
    do {
733
      info(message);
×
734
      input = readLine().trim();
×
735
    } while (input.isEmpty());
×
736

737
    return input;
×
738
  }
739

740
  @SuppressWarnings("unchecked")
741
  @Override
742
  public <O> O question(String question, O... options) {
743

744
    assert (options.length >= 2);
×
745
    interaction(question);
×
746
    Map<String, O> mapping = new HashMap<>(options.length);
×
747
    int i = 0;
×
748
    for (O option : options) {
×
749
      i++;
×
750
      String key = "" + option;
×
751
      addMapping(mapping, key, option);
×
752
      String numericKey = Integer.toString(i);
×
753
      if (numericKey.equals(key)) {
×
754
        trace("Options should not be numeric: " + key);
×
755
      } else {
756
        addMapping(mapping, numericKey, option);
×
757
      }
758
      interaction("Option " + numericKey + ": " + key);
×
759
    }
760
    O option = null;
×
761
    if (isBatchMode()) {
×
762
      if (isForceMode()) {
×
763
        option = options[0];
×
764
        interaction("" + option);
×
765
      }
766
    } else {
767
      while (option == null) {
×
768
        String answer = readLine();
×
769
        option = mapping.get(answer);
×
770
        if (option == null) {
×
771
          warning("Invalid answer: '" + answer + "' - please try again.");
×
772
        }
773
      }
×
774
    }
775
    return option;
×
776
  }
777

778
  /**
779
   * @return the input from the end-user (e.g. read from the console).
780
   */
781
  protected abstract String readLine();
782

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

785
    O duplicate = mapping.put(key, option);
×
786
    if (duplicate != null) {
×
787
      throw new IllegalArgumentException("Duplicated option " + key);
×
788
    }
789
  }
×
790

791
  /**
792
   * Sets the log level.
793
   *
794
   * @param logLevel {@link IdeLogLevel}
795
   */
796
  public void setLogLevel(IdeLogLevel logLevel) {
797

798
    for (IdeLogLevel level : IdeLogLevel.values()) {
16✔
799
      IdeSubLogger logger;
800
      if (level.ordinal() < logLevel.ordinal()) {
5✔
801
        logger = new IdeSubLoggerNone(level);
6✔
802
      } else {
803
        logger = this.loggerFactory.apply(level);
6✔
804
      }
805
      this.loggers.put(level, logger);
6✔
806
    }
807
  }
1✔
808

809
  @Override
810
  public Step getCurrentStep() {
811

812
    return this.currentStep;
×
813
  }
814

815
  @Override
816
  public StepImpl newStep(boolean silent, String name, Object... parameters) {
817

818
    this.currentStep = new StepImpl(this, this.currentStep, name, silent, parameters);
11✔
819
    return this.currentStep;
3✔
820
  }
821

822
  /**
823
   * Internal method to end the running {@link Step}.
824
   *
825
   * @param step the current {@link Step} to end.
826
   */
827
  public void endStep(StepImpl step) {
828

829
    if (step == this.currentStep) {
4!
830
      this.currentStep = this.currentStep.getParent();
6✔
831
    } else {
832
      String currentStepName = "null";
×
833
      if (this.currentStep != null) {
×
834
        currentStepName = this.currentStep.getName();
×
835
      }
836
      warning("endStep called with wrong step '{}' but expected '{}'", step.getName(), currentStepName);
×
837
    }
838
  }
1✔
839

840
  /**
841
   * Finds the matching {@link Commandlet} to run, applies {@link CliArguments} to its {@link Commandlet#getProperties() properties} and will execute it.
842
   *
843
   * @param arguments the {@link CliArgument}.
844
   * @return the return code of the execution.
845
   */
846
  public int run(CliArguments arguments) {
847

848
    CliArgument current = arguments.current();
×
849
    assert (this.currentStep == null);
×
850
    boolean supressStepSuccess = false;
×
851
    StepImpl step = newStep(true, "ide", (Object[]) current.asArray());
×
852
    Commandlet firstCandidate = null;
×
853
    try {
854
      if (!current.isEnd()) {
×
855
        String keyword = current.get();
×
856
        firstCandidate = this.commandletManager.getCommandletByFirstKeyword(keyword);
×
857
        boolean matches;
858
        if (firstCandidate != null) {
×
859
          matches = applyAndRun(arguments.copy(), firstCandidate);
×
860
          if (matches) {
×
861
            supressStepSuccess = firstCandidate.isSuppressStepSuccess();
×
862
            step.success();
×
863
            return ProcessResult.SUCCESS;
×
864
          }
865
        }
866
        for (Commandlet cmd : this.commandletManager.getCommandlets()) {
×
867
          if (cmd != firstCandidate) {
×
868
            matches = applyAndRun(arguments.copy(), cmd);
×
869
            if (matches) {
×
870
              supressStepSuccess = cmd.isSuppressStepSuccess();
×
871
              step.success();
×
872
              return ProcessResult.SUCCESS;
×
873
            }
874
          }
875
        }
×
876
        step.error("Invalid arguments: {}", current.getArgs());
×
877
      }
878

879
      HelpCommandlet help = this.commandletManager.getCommandlet(HelpCommandlet.class);
×
880
      if (firstCandidate != null) {
×
881
        help.commandlet.setValue(firstCandidate);
×
882
      }
883
      help.run();
×
884
      return 1;
×
885
    } catch (Throwable t) {
×
886
      step.error(t, true);
×
887
      throw t;
×
888
    } finally {
889
      step.close();
×
890
      assert (this.currentStep == null);
×
891
      step.logSummary(supressStepSuccess);
×
892
    }
893
  }
894

895
  /**
896
   * @param cmd the potential {@link Commandlet} to {@link #apply(CliArguments, Commandlet, CompletionCandidateCollector) apply} and
897
   * {@link Commandlet#run() run}.
898
   * @return {@code true} if the given {@link Commandlet} matched and did {@link Commandlet#run() run} successfully, {@code false} otherwise (the
899
   * {@link Commandlet} did not match and we have to try a different candidate).
900
   */
901
  private boolean applyAndRun(CliArguments arguments, Commandlet cmd) {
902

903
    cmd.clearProperties();
×
904

905
    boolean matches = apply(arguments, cmd, null);
×
906
    if (matches) {
×
907
      matches = cmd.validate();
×
908
    }
909
    if (matches) {
×
910
      debug("Running commandlet {}", cmd);
×
911
      if (cmd.isIdeHomeRequired() && (this.ideHome == null)) {
×
912
        throw new CliException(getMessageIdeHomeNotFound(), ProcessResult.NO_IDE_HOME);
×
913
      } else if (cmd.isIdeRootRequired() && (this.ideRoot == null)) {
×
914
        throw new CliException(getMessageIdeRootNotFound(), ProcessResult.NO_IDE_ROOT);
×
915
      }
916
      if (!cmd.isProcessableOutput()) {
×
917
        if (cmd.isIdeHomeRequired()) {
×
918
          debug(getMessageIdeHomeFound());
×
919
        }
920
      }
921
      cmd.run();
×
922
    } else {
923
      trace("Commandlet did not match");
×
924
    }
925
    return matches;
×
926
  }
927

928
  /**
929
   * @param arguments the {@link CliArguments#ofCompletion(String...) completion arguments}.
930
   * @param includeContextOptions to include the options of {@link ContextCommandlet}.
931
   * @return the {@link List} of {@link CompletionCandidate}s to suggest.
932
   */
933
  public List<CompletionCandidate> complete(CliArguments arguments, boolean includeContextOptions) {
934

935
    CompletionCandidateCollector collector = new CompletionCandidateCollectorDefault(this);
5✔
936
    if (arguments.current().isStart()) {
4✔
937
      arguments.next();
3✔
938
    }
939
    if (includeContextOptions) {
2✔
940
      ContextCommandlet cc = new ContextCommandlet();
4✔
941
      for (Property<?> property : cc.getProperties()) {
11✔
942
        assert (property.isOption());
4!
943
        property.apply(arguments, this, cc, collector);
7✔
944
      }
1✔
945
    }
946
    CliArgument current = arguments.current();
3✔
947
    if (!current.isEnd()) {
3!
948
      String keyword = current.get();
3✔
949
      Commandlet firstCandidate = this.commandletManager.getCommandletByFirstKeyword(keyword);
5✔
950
      boolean matches = false;
2✔
951
      if (firstCandidate != null) {
2✔
952
        matches = apply(arguments.copy(), firstCandidate, collector);
8✔
953
      } else if (current.isCombinedShortOption()) {
3✔
954
        collector.add(keyword, null, null, null);
6✔
955
      }
956
      if (!matches) {
2!
957
        for (Commandlet cmd : this.commandletManager.getCommandlets()) {
12✔
958
          if (cmd != firstCandidate) {
3✔
959
            apply(arguments.copy(), cmd, collector);
7✔
960
          }
961
        }
1✔
962
      }
963
    }
964
    return collector.getSortedCandidates();
3✔
965
  }
966

967
  /**
968
   * @param arguments the {@link CliArguments} to apply. Will be {@link CliArguments#next() consumed} as they are matched. Consider passing a
969
   * {@link CliArguments#copy() copy} as needed.
970
   * @param cmd the potential {@link Commandlet} to match.
971
   * @param collector the {@link CompletionCandidateCollector}.
972
   * @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}
973
   * and {@link Commandlet#validate() validated}), {@code false} otherwise (the {@link Commandlet} did not match and we have to try a different candidate).
974
   */
975
  public boolean apply(CliArguments arguments, Commandlet cmd, CompletionCandidateCollector collector) {
976

977
    trace("Trying to match arguments to commandlet {}", cmd.getName());
10✔
978
    CliArgument currentArgument = arguments.current();
3✔
979
    Iterator<Property<?>> propertyIterator;
980
    if (currentArgument.isCompletion()) {
3✔
981
      propertyIterator = cmd.getProperties().iterator();
5✔
982
    } else {
983
      propertyIterator = cmd.getValues().iterator();
4✔
984
    }
985
    while (!currentArgument.isEnd()) {
3!
986
      trace("Trying to match argument '{}'", currentArgument);
9✔
987
      Property<?> property = null;
2✔
988
      if (!arguments.isEndOptions()) {
3!
989
        property = cmd.getOption(currentArgument.getKey());
5✔
990
      }
991
      if (property == null) {
2✔
992
        if (!propertyIterator.hasNext()) {
3✔
993
          trace("No option or next value found");
3✔
994
          return false;
2✔
995
        }
996
        property = propertyIterator.next();
4✔
997
      }
998
      trace("Next property candidate to match argument is {}", property);
9✔
999
      boolean matches = property.apply(arguments, this, cmd, collector);
7✔
1000
      if (!matches || currentArgument.isCompletion()) {
5✔
1001
        return false;
2✔
1002
      }
1003
      currentArgument = arguments.current();
3✔
1004
    }
1✔
1005
    return true;
×
1006
  }
1007

1008
  @Override
1009
  public String findBash() {
1010

1011
    String bash = "bash";
2✔
1012
    if (SystemInfoImpl.INSTANCE.isWindows()) {
3!
1013
      bash = findBashOnWindows();
×
1014
    }
1015

1016
    return bash;
2✔
1017
  }
1018

1019
  private String findBashOnWindows() {
1020

1021
    // Check if Git Bash exists in the default location
1022
    Path defaultPath = Path.of("C:\\Program Files\\Git\\bin\\bash.exe");
×
1023
    if (Files.exists(defaultPath)) {
×
1024
      return defaultPath.toString();
×
1025
    }
1026

1027
    // If not found in the default location, try the registry query
1028
    String[] bashVariants = { "GitForWindows", "Cygwin\\setup" };
×
1029
    String[] registryKeys = { "HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER" };
×
1030
    String regQueryResult;
1031
    for (String bashVariant : bashVariants) {
×
1032
      for (String registryKey : registryKeys) {
×
1033
        String toolValueName = ("GitForWindows".equals(bashVariant)) ? "InstallPath" : "rootdir";
×
1034
        String command = "reg query " + registryKey + "\\Software\\" + bashVariant + "  /v " + toolValueName + " 2>nul";
×
1035

1036
        try {
1037
          Process process = new ProcessBuilder("cmd.exe", "/c", command).start();
×
1038
          try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
×
1039
            StringBuilder output = new StringBuilder();
×
1040
            String line;
1041

1042
            while ((line = reader.readLine()) != null) {
×
1043
              output.append(line);
×
1044
            }
1045

1046
            int exitCode = process.waitFor();
×
1047
            if (exitCode != 0) {
×
1048
              return null;
×
1049
            }
1050

1051
            regQueryResult = output.toString();
×
1052
            if (regQueryResult != null) {
×
1053
              int index = regQueryResult.indexOf("REG_SZ");
×
1054
              if (index != -1) {
×
1055
                String path = regQueryResult.substring(index + "REG_SZ".length()).trim();
×
1056
                return path + "\\bin\\bash.exe";
×
1057
              }
1058
            }
1059

1060
          }
×
1061
        } catch (Exception e) {
×
1062
          return null;
×
1063
        }
×
1064
      }
1065
    }
1066
    // no bash found
1067
    throw new IllegalStateException("Could not find Bash. Please install Git for Windows and rerun.");
×
1068
  }
1069

1070
  @Override
1071
  public WindowsPathSyntax getPathSyntax() {
1072
    return this.pathSyntax;
3✔
1073
  }
1074

1075
  /**
1076
   * @param pathSyntax new value of {@link #getPathSyntax()}.
1077
   */
1078
  public void setPathSyntax(WindowsPathSyntax pathSyntax) {
1079

1080
    this.pathSyntax = pathSyntax;
3✔
1081
  }
1✔
1082
}
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