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

devonfw / IDEasy / 12073943517

28 Nov 2024 06:24PM UTC coverage: 67.417% (+0.03%) from 67.39%
12073943517

push

github

web-flow
#778: add icd #779: use functions instead of alias #810: setup in current shell #782: fix IDE_ROOT on linux/mac #774: fixed HTTP proxy support (#811)

2500 of 4050 branches covered (61.73%)

Branch coverage included in aggregate %.

6511 of 9316 relevant lines covered (69.89%)

3.09 hits per line

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

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

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

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

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

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

65
  private final IdeStartContextImpl startContext;
66

67
  private Path ideHome;
68

69
  private final Path ideRoot;
70

71
  private Path confPath;
72

73
  protected Path settingsPath;
74

75
  private Path softwarePath;
76

77
  private Path softwareExtraPath;
78

79
  private Path softwareRepositoryPath;
80

81
  protected Path pluginsPath;
82

83
  private Path workspacePath;
84

85
  private String workspaceName;
86

87
  protected Path urlsPath;
88

89
  private Path tempPath;
90

91
  private Path tempDownloadPath;
92

93
  private Path cwd;
94

95
  private Path downloadPath;
96

97
  private Path toolRepositoryPath;
98

99
  protected Path userHome;
100

101
  private Path userHomeIde;
102

103
  private SystemPath path;
104

105
  private WindowsPathSyntax pathSyntax;
106

107
  private final SystemInfo systemInfo;
108

109
  private EnvironmentVariables variables;
110

111
  private final FileAccess fileAccess;
112

113
  protected CommandletManager commandletManager;
114

115
  protected ToolRepository defaultToolRepository;
116

117
  private CustomToolRepository customToolRepository;
118

119
  private DirectoryMerger workspaceMerger;
120

121
  protected UrlMetadata urlMetadata;
122

123
  protected Path defaultExecutionDirectory;
124

125
  private StepImpl currentStep;
126

127
  protected Boolean online;
128

129
  protected IdeSystem system;
130

131
  private NetworkProxy networkProxy;
132

133
  /**
134
   * The constructor.
135
   *
136
   * @param startContext the {@link IdeLogger}.
137
   * @param workingDirectory the optional {@link Path} to current working directory.
138
   */
139
  public AbstractIdeContext(IdeStartContextImpl startContext, Path workingDirectory) {
140

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

172
    // detection completed, initializing variables
173
    this.ideRoot = findIdeRoot(currentDir);
5✔
174

175
    setCwd(workingDirectory, workspace, currentDir);
5✔
176

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

197
    this.defaultToolRepository = new DefaultToolRepository(this);
6✔
198
  }
1✔
199

200
  private Path findIdeRoot(Path ideHomePath) {
201

202
    Path ideRootPath = null;
2✔
203
    if (ideHomePath != null) {
2✔
204
      ideRootPath = ideHomePath.getParent();
4✔
205
    } else if (!isTest()) {
3!
206
      ideRootPath = getIdeRootPathFromEnv();
×
207
    }
208
    return ideRootPath;
2✔
209
  }
210

211
  private Path getIdeRootPathFromEnv() {
212
    String root = getSystem().getEnv(IdeVariables.IDE_ROOT.getName());
×
213
    if (root != null) {
×
214
      Path rootPath = Path.of(root);
×
215
      if (Files.isDirectory(rootPath)) {
×
216
        return rootPath;
×
217
      }
218
    }
219
    return null;
×
220
  }
221

222
  @Override
223
  public void setCwd(Path userDir, String workspace, Path ideHome) {
224

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

256
    this.path = computeSystemPath();
4✔
257
    this.customToolRepository = CustomToolRepositoryImpl.of(this);
4✔
258
  }
1✔
259

260
  private String getMessageIdeHomeFound() {
261

262
    return "IDE environment variables have been set for " + this.ideHome + " in workspace " + this.workspaceName;
6✔
263
  }
264

265
  private String getMessageIdeHomeNotFound() {
266

267
    return "You are not inside an IDE installation: " + this.cwd;
×
268
  }
269

270
  private String getMessageIdeRootNotFound() {
271
    String root = getSystem().getEnv("IDE_ROOT");
×
272
    if (root == null) {
×
273
      return "The environment variable IDE_ROOT is undefined. Please reinstall IDEasy or manually repair IDE_ROOT variable.";
×
274
    } else {
275
      return "The environment variable IDE_ROOT is pointing to an invalid path " + root + ". Please reinstall IDEasy or manually repair IDE_ROOT variable.";
×
276
    }
277
  }
278

279
  /**
280
   * @return the status message about the {@link #getIdeHome() IDE_HOME} detection and environment variable initialization.
281
   */
282
  public String getMessageIdeHome() {
283

284
    if (this.ideHome == null) {
×
285
      return getMessageIdeHomeNotFound();
×
286
    }
287
    return getMessageIdeHomeFound();
×
288
  }
289

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

295
    return false;
×
296
  }
297

298
  protected SystemPath computeSystemPath() {
299

300
    return new SystemPath(this);
×
301
  }
302

303
  private boolean isIdeHome(Path dir) {
304

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

313
  private EnvironmentVariables createVariables() {
314

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

324
  protected AbstractEnvironmentVariables createSystemVariables() {
325

326
    return EnvironmentVariables.ofSystem(this);
3✔
327
  }
328

329
  protected AbstractEnvironmentVariables extendVariables(AbstractEnvironmentVariables envVariables, Path propertiesPath, EnvironmentVariablesType type) {
330

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

349
  @Override
350
  public SystemInfo getSystemInfo() {
351

352
    return this.systemInfo;
3✔
353
  }
354

355
  @Override
356
  public FileAccess getFileAccess() {
357

358
    // currently FileAccess contains download method and requires network proxy to be configured. Maybe download should be moved to its own interface/class
359
    configureNetworkProxy();
2✔
360
    return this.fileAccess;
3✔
361
  }
362

363
  @Override
364
  public CommandletManager getCommandletManager() {
365

366
    return this.commandletManager;
3✔
367
  }
368

369
  @Override
370
  public ToolRepository getDefaultToolRepository() {
371

372
    return this.defaultToolRepository;
3✔
373
  }
374

375
  @Override
376
  public CustomToolRepository getCustomToolRepository() {
377

378
    return this.customToolRepository;
3✔
379
  }
380

381
  @Override
382
  public Path getIdeHome() {
383

384
    return this.ideHome;
3✔
385
  }
386

387
  @Override
388
  public String getProjectName() {
389

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

396
  @Override
397
  public Path getIdeRoot() {
398

399
    return this.ideRoot;
3✔
400
  }
401

402
  @Override
403
  public Path getCwd() {
404

405
    return this.cwd;
3✔
406
  }
407

408
  @Override
409
  public Path getTempPath() {
410

411
    return this.tempPath;
3✔
412
  }
413

414
  @Override
415
  public Path getTempDownloadPath() {
416

417
    return this.tempDownloadPath;
3✔
418
  }
419

420
  @Override
421
  public Path getUserHome() {
422

423
    return this.userHome;
3✔
424
  }
425

426
  @Override
427
  public Path getUserHomeIde() {
428

429
    return this.userHomeIde;
3✔
430
  }
431

432
  @Override
433
  public Path getSettingsPath() {
434

435
    return this.settingsPath;
3✔
436
  }
437

438
  @Override
439
  public Path getConfPath() {
440

441
    return this.confPath;
3✔
442
  }
443

444
  @Override
445
  public Path getSoftwarePath() {
446

447
    return this.softwarePath;
3✔
448
  }
449

450
  @Override
451
  public Path getSoftwareExtraPath() {
452

453
    return this.softwareExtraPath;
3✔
454
  }
455

456
  @Override
457
  public Path getSoftwareRepositoryPath() {
458

459
    return this.softwareRepositoryPath;
3✔
460
  }
461

462
  @Override
463
  public Path getPluginsPath() {
464

465
    return this.pluginsPath;
3✔
466
  }
467

468
  @Override
469
  public String getWorkspaceName() {
470

471
    return this.workspaceName;
3✔
472
  }
473

474
  @Override
475
  public Path getWorkspacePath() {
476

477
    return this.workspacePath;
3✔
478
  }
479

480
  @Override
481
  public Path getDownloadPath() {
482

483
    return this.downloadPath;
3✔
484
  }
485

486
  @Override
487
  public Path getUrlsPath() {
488

489
    return this.urlsPath;
3✔
490
  }
491

492
  @Override
493
  public Path getToolRepositoryPath() {
494

495
    return this.toolRepositoryPath;
3✔
496
  }
497

498
  @Override
499
  public SystemPath getPath() {
500

501
    return this.path;
3✔
502
  }
503

504
  @Override
505
  public EnvironmentVariables getVariables() {
506

507
    if (this.variables == null) {
3✔
508
      this.variables = createVariables();
4✔
509
    }
510
    return this.variables;
3✔
511
  }
512

513
  @Override
514
  public UrlMetadata getUrls() {
515

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

525
  @Override
526
  public boolean isQuietMode() {
527

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

531
  @Override
532
  public boolean isBatchMode() {
533

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

537
  @Override
538
  public boolean isForceMode() {
539

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

543
  @Override
544
  public boolean isOfflineMode() {
545

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

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

554
  @Override
555
  public boolean isOnline() {
556

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

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

583
  @Override
584
  public Locale getLocale() {
585

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

593
  @Override
594
  public DirectoryMerger getWorkspaceMerger() {
595

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

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

608
    return this.defaultExecutionDirectory;
×
609
  }
610

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

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

621
  @Override
622
  public GitContext getGitContext() {
623

624
    return new GitContextImpl(this);
×
625
  }
626

627
  @Override
628
  public ProcessContext newProcess() {
629

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

637
  @Override
638
  public IdeSystem getSystem() {
639

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

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

652
    return new ProcessContextImpl(this);
×
653
  }
654

655
  @Override
656
  public IdeSubLogger level(IdeLogLevel level) {
657

658
    return this.startContext.level(level);
5✔
659
  }
660

661
  @Override
662
  public String askForInput(String message, String defaultValue) {
663

664
    if (!message.isBlank()) {
×
665
      info(message);
×
666
    }
667
    if (isBatchMode()) {
×
668
      if (isForceMode()) {
×
669
        return defaultValue;
×
670
      } else {
671
        throw new CliAbortException();
×
672
      }
673
    }
674
    String input = readLine().trim();
×
675
    return input.isEmpty() ? defaultValue : input;
×
676
  }
677

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

681
    String input;
682
    do {
683
      info(message);
3✔
684
      input = readLine().trim();
4✔
685
    } while (input.isEmpty());
3!
686

687
    return input;
2✔
688
  }
689

690
  @SuppressWarnings("unchecked")
691
  @Override
692
  public <O> O question(String question, O... options) {
693

694
    assert (options.length >= 2);
×
695
    interaction(question);
×
696
    Map<String, O> mapping = new HashMap<>(options.length);
×
697
    int i = 0;
×
698
    for (O option : options) {
×
699
      i++;
×
700
      String key = "" + option;
×
701
      addMapping(mapping, key, option);
×
702
      String numericKey = Integer.toString(i);
×
703
      if (numericKey.equals(key)) {
×
704
        trace("Options should not be numeric: " + key);
×
705
      } else {
706
        addMapping(mapping, numericKey, option);
×
707
      }
708
      interaction("Option " + numericKey + ": " + key);
×
709
    }
710
    O option = null;
×
711
    if (isBatchMode()) {
×
712
      if (isForceMode()) {
×
713
        option = options[0];
×
714
        interaction("" + option);
×
715
      }
716
    } else {
717
      while (option == null) {
×
718
        String answer = readLine();
×
719
        option = mapping.get(answer);
×
720
        if (option == null) {
×
721
          warning("Invalid answer: '" + answer + "' - please try again.");
×
722
        }
723
      }
×
724
    }
725
    return option;
×
726
  }
727

728
  /**
729
   * @return the input from the end-user (e.g. read from the console).
730
   */
731
  protected abstract String readLine();
732

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

735
    O duplicate = mapping.put(key, option);
×
736
    if (duplicate != null) {
×
737
      throw new IllegalArgumentException("Duplicated option " + key);
×
738
    }
739
  }
×
740

741
  @Override
742
  public Step getCurrentStep() {
743

744
    return this.currentStep;
×
745
  }
746

747
  @Override
748
  public StepImpl newStep(boolean silent, String name, Object... parameters) {
749

750
    this.currentStep = new StepImpl(this, this.currentStep, name, silent, parameters);
11✔
751
    return this.currentStep;
3✔
752
  }
753

754
  /**
755
   * Internal method to end the running {@link Step}.
756
   *
757
   * @param step the current {@link Step} to end.
758
   */
759
  public void endStep(StepImpl step) {
760

761
    if (step == this.currentStep) {
4!
762
      this.currentStep = this.currentStep.getParent();
6✔
763
    } else {
764
      String currentStepName = "null";
×
765
      if (this.currentStep != null) {
×
766
        currentStepName = this.currentStep.getName();
×
767
      }
768
      warning("endStep called with wrong step '{}' but expected '{}'", step.getName(), currentStepName);
×
769
    }
770
  }
1✔
771

772
  /**
773
   * Finds the matching {@link Commandlet} to run, applies {@link CliArguments} to its {@link Commandlet#getProperties() properties} and will execute it.
774
   *
775
   * @param arguments the {@link CliArgument}.
776
   * @return the return code of the execution.
777
   */
778
  public int run(CliArguments arguments) {
779

780
    CliArgument current = arguments.current();
3✔
781
    assert (this.currentStep == null);
4!
782
    boolean supressStepSuccess = false;
2✔
783
    StepImpl step = newStep(true, "ide", (Object[]) current.asArray());
8✔
784
    Commandlet firstCandidate = null;
2✔
785
    try {
786
      if (!current.isEnd()) {
3!
787
        String keyword = current.get();
3✔
788
        firstCandidate = this.commandletManager.getCommandletByFirstKeyword(keyword);
5✔
789
        ValidationResult firstResult = null;
2✔
790
        if (firstCandidate != null) {
2!
791
          firstResult = applyAndRun(arguments.copy(), firstCandidate);
6✔
792
          if (firstResult.isValid()) {
3!
793
            supressStepSuccess = firstCandidate.isSuppressStepSuccess();
3✔
794
            step.success();
2✔
795
            return ProcessResult.SUCCESS;
4✔
796
          }
797
        }
798
        for (Commandlet cmd : this.commandletManager.getCommandlets()) {
×
799
          if (cmd != firstCandidate) {
×
800
            ValidationResult result = applyAndRun(arguments.copy(), cmd);
×
801
            if (result.isValid()) {
×
802
              supressStepSuccess = cmd.isSuppressStepSuccess();
×
803
              step.success();
×
804
              return ProcessResult.SUCCESS;
×
805
            }
806
          }
807
        }
×
808
        if (firstResult != null) {
×
809
          throw new CliException(firstResult.getErrorMessage());
×
810
        }
811
        step.error("Invalid arguments: {}", current.getArgs());
×
812
      }
813

814
      HelpCommandlet help = this.commandletManager.getCommandlet(HelpCommandlet.class);
×
815
      if (firstCandidate != null) {
×
816
        help.commandlet.setValue(firstCandidate);
×
817
      }
818
      help.run();
×
819
      return 1;
×
820
    } catch (Throwable t) {
×
821
      step.error(t, true);
×
822
      throw t;
×
823
    } finally {
824
      step.close();
2✔
825
      assert (this.currentStep == null);
4!
826
      step.logSummary(supressStepSuccess);
3✔
827
    }
828
  }
829

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

838
    cmd.clearProperties();
2✔
839

840
    ValidationResult result = apply(arguments, cmd, null);
6✔
841
    if (result.isValid()) {
3!
842
      result = cmd.validate();
3✔
843
    }
844
    if (result.isValid()) {
3!
845
      debug("Running commandlet {}", cmd);
9✔
846
      if (cmd.isIdeHomeRequired() && (this.ideHome == null)) {
6!
847
        throw new CliException(getMessageIdeHomeNotFound(), ProcessResult.NO_IDE_HOME);
×
848
      } else if (cmd.isIdeRootRequired() && (this.ideRoot == null)) {
6!
849
        throw new CliException(getMessageIdeRootNotFound(), ProcessResult.NO_IDE_ROOT);
×
850
      }
851
      if (cmd.isProcessableOutput()) {
3!
852
        if (!debug().isEnabled()) {
×
853
          // unless --debug or --trace was supplied, processable output commandlets will disable all log-levels except INFO to prevent other logs interfere
854
          for (IdeLogLevel level : IdeLogLevel.values()) {
×
855
            if (level != IdeLogLevel.PROCESSABLE) {
×
856
              this.startContext.setLogLevel(level, false);
×
857
            }
858
          }
859
        }
860
        this.startContext.activateLogging();
×
861
      } else {
862
        this.startContext.activateLogging();
3✔
863
        if (!isTest()) {
3!
864
          if (this.ideRoot == null) {
×
865
            warning("Variable IDE_ROOT is undefined. Please check your installation or run setup script again.");
×
866
          } else if (this.ideHome != null) {
×
867
            Path ideRootPath = getIdeRootPathFromEnv();
×
868
            if (!this.ideRoot.equals(ideRootPath)) {
×
869
              warning("Variable IDE_ROOT is set to '{}' but for your project '{}' the path '{}' would have been expected.", ideRootPath,
×
870
                  this.ideHome.getFileName(), this.ideRoot);
×
871
            }
872
          }
873
        }
874
        if (cmd.isIdeHomeRequired()) {
3!
875
          debug(getMessageIdeHomeFound());
4✔
876
        }
877
      }
878
      if (this.settingsPath != null) {
3!
879
        if (getGitContext().isRepositoryUpdateAvailable(this.settingsPath) ||
7!
880
            (getGitContext().fetchIfNeeded(this.settingsPath) && getGitContext().isRepositoryUpdateAvailable(this.settingsPath))) {
5!
881
          interaction("Updates are available for the settings repository. If you want to pull the latest changes, call ide update.");
×
882
        }
883
      }
884
      cmd.run();
3✔
885
    } else {
886
      trace("Commandlet did not match");
×
887
    }
888
    return result;
2✔
889
  }
890

891
  /**
892
   * @param arguments the {@link CliArguments#ofCompletion(String...) completion arguments}.
893
   * @param includeContextOptions to include the options of {@link ContextCommandlet}.
894
   * @return the {@link List} of {@link CompletionCandidate}s to suggest.
895
   */
896
  public List<CompletionCandidate> complete(CliArguments arguments, boolean includeContextOptions) {
897

898
    CompletionCandidateCollector collector = new CompletionCandidateCollectorDefault(this);
5✔
899
    if (arguments.current().isStart()) {
4✔
900
      arguments.next();
3✔
901
    }
902
    if (includeContextOptions) {
2✔
903
      ContextCommandlet cc = new ContextCommandlet();
4✔
904
      for (Property<?> property : cc.getProperties()) {
11✔
905
        assert (property.isOption());
4!
906
        property.apply(arguments, this, cc, collector);
7✔
907
      }
1✔
908
    }
909
    CliArgument current = arguments.current();
3✔
910
    if (!current.isEnd()) {
3!
911
      String keyword = current.get();
3✔
912
      Commandlet firstCandidate = this.commandletManager.getCommandletByFirstKeyword(keyword);
5✔
913
      boolean matches = false;
2✔
914
      if (firstCandidate != null) {
2✔
915
        matches = completeCommandlet(arguments, firstCandidate, collector);
7✔
916
      } else if (current.isCombinedShortOption()) {
3✔
917
        collector.add(keyword, null, null, null);
6✔
918
      }
919
      if (!matches) {
2!
920
        for (Commandlet cmd : this.commandletManager.getCommandlets()) {
12✔
921
          if (cmd != firstCandidate) {
3✔
922
            completeCommandlet(arguments, cmd, collector);
6✔
923
          }
924
        }
1✔
925
      }
926
    }
927
    return collector.getSortedCandidates();
3✔
928
  }
929

930
  private boolean completeCommandlet(CliArguments arguments, Commandlet cmd, CompletionCandidateCollector collector) {
931
    if (cmd.isIdeHomeRequired() && (this.ideHome == null)) {
6!
932
      return false;
×
933
    } else {
934
      return apply(arguments.copy(), cmd, collector).isValid();
8✔
935
    }
936
  }
937

938

939
  /**
940
   * @param arguments the {@link CliArguments} to apply. Will be {@link CliArguments#next() consumed} as they are matched. Consider passing a
941
   *     {@link CliArguments#copy() copy} as needed.
942
   * @param cmd the potential {@link Commandlet} to match.
943
   * @param collector the {@link CompletionCandidateCollector}.
944
   * @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}
945
   *     and {@link Commandlet#validate() validated}), {@code false} otherwise (the {@link Commandlet} did not match and we have to try a different candidate).
946
   */
947
  public ValidationResult apply(CliArguments arguments, Commandlet cmd, CompletionCandidateCollector collector) {
948

949
    trace("Trying to match arguments to commandlet {}", cmd.getName());
10✔
950
    CliArgument currentArgument = arguments.current();
3✔
951
    Iterator<Property<?>> propertyIterator;
952
    if (currentArgument.isCompletion()) {
3✔
953
      propertyIterator = cmd.getProperties().iterator();
5✔
954
    } else {
955
      propertyIterator = cmd.getValues().iterator();
4✔
956
    }
957
    Property<?> property = null;
2✔
958
    if (propertyIterator.hasNext()) {
3✔
959
      property = propertyIterator.next();
4✔
960
    }
961
    while (!currentArgument.isEnd()) {
3✔
962
      trace("Trying to match argument '{}'", currentArgument);
9✔
963
      Property<?> currentProperty = property;
2✔
964
      if (!arguments.isEndOptions()) {
3!
965
        Property<?> option = cmd.getOption(currentArgument.getKey());
5✔
966
        if (option != null) {
2✔
967
          currentProperty = option;
2✔
968
        }
969
      }
970
      if (currentProperty == null) {
2✔
971
        trace("No option or next value found");
3✔
972
        ValidationState state = new ValidationState(null);
5✔
973
        state.addErrorMessage("No matching property found");
3✔
974
        return state;
2✔
975
      }
976
      trace("Next property candidate to match argument is {}", currentProperty);
9✔
977
      if (currentProperty == property) {
3✔
978
        if (!property.isMultiValued()) {
3✔
979
          if (propertyIterator.hasNext()) {
3✔
980
            property = propertyIterator.next();
5✔
981
          } else {
982
            property = null;
2✔
983
          }
984
        }
985
        if ((property != null) && property.isValue() && property.isMultiValued()) {
8✔
986
          arguments.stopSplitShortOptions();
2✔
987
        }
988
      }
989
      boolean matches = currentProperty.apply(arguments, this, cmd, collector);
7✔
990
      if (!matches || currentArgument.isCompletion()) {
5✔
991
        ValidationState state = new ValidationState(null);
5✔
992
        state.addErrorMessage("No matching property found");
3✔
993
        return state;
2✔
994
      }
995
      currentArgument = arguments.current();
3✔
996
    }
1✔
997
    return new ValidationState(null);
5✔
998
  }
999

1000
  @Override
1001
  public String findBash() {
1002

1003
    String bash = "bash";
2✔
1004
    if (SystemInfoImpl.INSTANCE.isWindows()) {
3!
1005
      bash = findBashOnWindows();
×
1006
    }
1007

1008
    return bash;
2✔
1009
  }
1010

1011
  private String findBashOnWindows() {
1012

1013
    // Check if Git Bash exists in the default location
1014
    Path defaultPath = Path.of("C:\\Program Files\\Git\\bin\\bash.exe");
×
1015
    if (Files.exists(defaultPath)) {
×
1016
      return defaultPath.toString();
×
1017
    }
1018

1019
    // If not found in the default location, try the registry query
1020
    String[] bashVariants = { "GitForWindows", "Cygwin\\setup" };
×
1021
    String[] registryKeys = { "HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER" };
×
1022
    String regQueryResult;
1023
    for (String bashVariant : bashVariants) {
×
1024
      for (String registryKey : registryKeys) {
×
1025
        String toolValueName = ("GitForWindows".equals(bashVariant)) ? "InstallPath" : "rootdir";
×
1026
        String command = "reg query " + registryKey + "\\Software\\" + bashVariant + "  /v " + toolValueName + " 2>nul";
×
1027

1028
        try {
1029
          Process process = new ProcessBuilder("cmd.exe", "/c", command).start();
×
1030
          try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
×
1031
            StringBuilder output = new StringBuilder();
×
1032
            String line;
1033

1034
            while ((line = reader.readLine()) != null) {
×
1035
              output.append(line);
×
1036
            }
1037

1038
            int exitCode = process.waitFor();
×
1039
            if (exitCode != 0) {
×
1040
              return null;
×
1041
            }
1042

1043
            regQueryResult = output.toString();
×
1044
            if (regQueryResult != null) {
×
1045
              int index = regQueryResult.indexOf("REG_SZ");
×
1046
              if (index != -1) {
×
1047
                String path = regQueryResult.substring(index + "REG_SZ".length()).trim();
×
1048
                return path + "\\bin\\bash.exe";
×
1049
              }
1050
            }
1051

1052
          }
×
1053
        } catch (Exception e) {
×
1054
          return null;
×
1055
        }
×
1056
      }
1057
    }
1058
    // no bash found
1059
    return null;
×
1060
  }
1061

1062
  @Override
1063
  public WindowsPathSyntax getPathSyntax() {
1064
    return this.pathSyntax;
3✔
1065
  }
1066

1067
  /**
1068
   * @param pathSyntax new value of {@link #getPathSyntax()}.
1069
   */
1070
  public void setPathSyntax(WindowsPathSyntax pathSyntax) {
1071

1072
    this.pathSyntax = pathSyntax;
3✔
1073
  }
1✔
1074

1075
  /**
1076
   * @return the {@link IdeStartContextImpl}.
1077
   */
1078
  public IdeStartContextImpl getStartContext() {
1079

1080
    return startContext;
3✔
1081
  }
1082

1083
  /**
1084
   * Reloads this context and re-initializes the {@link #getVariables() variables}.
1085
   */
1086
  public void reload() {
1087
    this.variables = null;
3✔
1088
  }
1✔
1089
}
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