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

devonfw / IDEasy / 12088062306

29 Nov 2024 04:30PM UTC coverage: 67.008% (+0.01%) from 66.998%
12088062306

push

github

web-flow
#739: removed "not inside an IDE installation message" (#753)

2506 of 4088 branches covered (61.3%)

Branch coverage included in aggregate %.

6534 of 9403 relevant lines covered (69.49%)

3.06 hits per line

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

59.75
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.ValidationResultValid;
56
import com.devonfw.tools.ide.validation.ValidationState;
57
import com.devonfw.tools.ide.variable.IdeVariables;
58

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

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

66
  private final IdeStartContextImpl startContext;
67

68
  private Path ideHome;
69

70
  private final Path ideRoot;
71

72
  private Path confPath;
73

74
  protected Path settingsPath;
75

76
  private Path softwarePath;
77

78
  private Path softwareExtraPath;
79

80
  private Path softwareRepositoryPath;
81

82
  protected Path pluginsPath;
83

84
  private Path workspacePath;
85

86
  private String workspaceName;
87

88
  protected Path urlsPath;
89

90
  private Path tempPath;
91

92
  private Path tempDownloadPath;
93

94
  private Path cwd;
95

96
  private Path downloadPath;
97

98
  private Path toolRepositoryPath;
99

100
  protected Path userHome;
101

102
  private Path userHomeIde;
103

104
  private SystemPath path;
105

106
  private WindowsPathSyntax pathSyntax;
107

108
  private final SystemInfo systemInfo;
109

110
  private EnvironmentVariables variables;
111

112
  private final FileAccess fileAccess;
113

114
  protected CommandletManager commandletManager;
115

116
  protected ToolRepository defaultToolRepository;
117

118
  private CustomToolRepository customToolRepository;
119

120
  private DirectoryMerger workspaceMerger;
121

122
  protected UrlMetadata urlMetadata;
123

124
  protected Path defaultExecutionDirectory;
125

126
  private StepImpl currentStep;
127

128
  protected Boolean online;
129

130
  protected IdeSystem system;
131

132
  private NetworkProxy networkProxy;
133

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

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

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

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

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

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

201
  private Path findIdeRoot(Path ideHomePath) {
202

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

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

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

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

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

261
  private String getMessageIdeHomeFound() {
262

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

266
  private String getMessageIdeHomeNotFound() {
267

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

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

280
  /**
281
   * @return {@code true} if this is a test context for JUnits, {@code false} otherwise.
282
   */
283
  public boolean isTest() {
284

285
    return false;
×
286
  }
287

288
  protected SystemPath computeSystemPath() {
289

290
    return new SystemPath(this);
×
291
  }
292

293

294
  private boolean isIdeHome(Path dir) {
295

296
    if (!Files.isDirectory(dir.resolve("workspaces"))) {
7✔
297
      return false;
2✔
298
    } else if (!Files.isDirectory(dir.resolve("settings"))) {
7!
299
      return false;
×
300
    }
301
    return true;
2✔
302
  }
303

304
  private EnvironmentVariables createVariables() {
305

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

315
  protected AbstractEnvironmentVariables createSystemVariables() {
316

317
    return EnvironmentVariables.ofSystem(this);
3✔
318
  }
319

320
  protected AbstractEnvironmentVariables extendVariables(AbstractEnvironmentVariables envVariables, Path propertiesPath, EnvironmentVariablesType type) {
321

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

340
  @Override
341
  public SystemInfo getSystemInfo() {
342

343
    return this.systemInfo;
3✔
344
  }
345

346
  @Override
347
  public FileAccess getFileAccess() {
348

349
    // currently FileAccess contains download method and requires network proxy to be configured. Maybe download should be moved to its own interface/class
350
    configureNetworkProxy();
2✔
351
    return this.fileAccess;
3✔
352
  }
353

354
  @Override
355
  public CommandletManager getCommandletManager() {
356

357
    return this.commandletManager;
3✔
358
  }
359

360
  @Override
361
  public ToolRepository getDefaultToolRepository() {
362

363
    return this.defaultToolRepository;
3✔
364
  }
365

366
  @Override
367
  public CustomToolRepository getCustomToolRepository() {
368

369
    return this.customToolRepository;
3✔
370
  }
371

372
  @Override
373
  public Path getIdeHome() {
374

375
    return this.ideHome;
3✔
376
  }
377

378
  @Override
379
  public String getProjectName() {
380

381
    if (this.ideHome != null) {
3!
382
      return this.ideHome.getFileName().toString();
5✔
383
    }
384
    return "";
×
385
  }
386

387
  @Override
388
  public Path getIdeRoot() {
389

390
    return this.ideRoot;
3✔
391
  }
392

393
  @Override
394
  public Path getCwd() {
395

396
    return this.cwd;
3✔
397
  }
398

399
  @Override
400
  public Path getTempPath() {
401

402
    return this.tempPath;
3✔
403
  }
404

405
  @Override
406
  public Path getTempDownloadPath() {
407

408
    return this.tempDownloadPath;
3✔
409
  }
410

411
  @Override
412
  public Path getUserHome() {
413

414
    return this.userHome;
3✔
415
  }
416

417
  @Override
418
  public Path getUserHomeIde() {
419

420
    return this.userHomeIde;
3✔
421
  }
422

423
  @Override
424
  public Path getSettingsPath() {
425

426
    return this.settingsPath;
3✔
427
  }
428

429
  @Override
430
  public Path getConfPath() {
431

432
    return this.confPath;
3✔
433
  }
434

435
  @Override
436
  public Path getSoftwarePath() {
437

438
    return this.softwarePath;
3✔
439
  }
440

441
  @Override
442
  public Path getSoftwareExtraPath() {
443

444
    return this.softwareExtraPath;
3✔
445
  }
446

447
  @Override
448
  public Path getSoftwareRepositoryPath() {
449

450
    return this.softwareRepositoryPath;
3✔
451
  }
452

453
  @Override
454
  public Path getPluginsPath() {
455

456
    return this.pluginsPath;
3✔
457
  }
458

459
  @Override
460
  public String getWorkspaceName() {
461

462
    return this.workspaceName;
3✔
463
  }
464

465
  @Override
466
  public Path getWorkspacePath() {
467

468
    return this.workspacePath;
3✔
469
  }
470

471
  @Override
472
  public Path getDownloadPath() {
473

474
    return this.downloadPath;
3✔
475
  }
476

477
  @Override
478
  public Path getUrlsPath() {
479

480
    return this.urlsPath;
3✔
481
  }
482

483
  @Override
484
  public Path getToolRepositoryPath() {
485

486
    return this.toolRepositoryPath;
3✔
487
  }
488

489
  @Override
490
  public SystemPath getPath() {
491

492
    return this.path;
3✔
493
  }
494

495
  @Override
496
  public EnvironmentVariables getVariables() {
497

498
    if (this.variables == null) {
3✔
499
      this.variables = createVariables();
4✔
500
    }
501
    return this.variables;
3✔
502
  }
503

504
  @Override
505
  public UrlMetadata getUrls() {
506

507
    if (this.urlMetadata == null) {
3✔
508
      if (!isTest()) {
3!
509
        getGitContext().pullOrCloneAndResetIfNeeded(IDE_URLS_GIT, this.urlsPath, null);
×
510
      }
511
      this.urlMetadata = new UrlMetadata(this);
6✔
512
    }
513
    return this.urlMetadata;
3✔
514
  }
515

516
  @Override
517
  public boolean isQuietMode() {
518

519
    return this.startContext.isQuietMode();
4✔
520
  }
521

522
  @Override
523
  public boolean isBatchMode() {
524

525
    return this.startContext.isBatchMode();
×
526
  }
527

528
  @Override
529
  public boolean isForceMode() {
530

531
    return this.startContext.isForceMode();
4✔
532
  }
533

534
  @Override
535
  public boolean isOfflineMode() {
536

537
    return this.startContext.isOfflineMode();
4✔
538
  }
539

540
  @Override
541
  public boolean isSkipUpdatesMode() {
542
    return this.startContext.isSkipUpdatesMode();
×
543
  }
544

545
  @Override
546
  public boolean isOnline() {
547

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

567
  private void configureNetworkProxy() {
568
    if (this.networkProxy == null) {
3✔
569
      this.networkProxy = new NetworkProxy(this);
6✔
570
      this.networkProxy.configure();
3✔
571
    }
572
  }
1✔
573

574
  @Override
575
  public Locale getLocale() {
576

577
    Locale locale = this.startContext.getLocale();
4✔
578
    if (locale == null) {
2!
579
      locale = Locale.getDefault();
×
580
    }
581
    return locale;
2✔
582
  }
583

584
  @Override
585
  public DirectoryMerger getWorkspaceMerger() {
586

587
    if (this.workspaceMerger == null) {
3✔
588
      this.workspaceMerger = new DirectoryMerger(this);
6✔
589
    }
590
    return this.workspaceMerger;
3✔
591
  }
592

593
  /**
594
   * @return the {@link #getDefaultExecutionDirectory() default execution directory} in which a command process is executed.
595
   */
596
  @Override
597
  public Path getDefaultExecutionDirectory() {
598

599
    return this.defaultExecutionDirectory;
×
600
  }
601

602
  /**
603
   * @param defaultExecutionDirectory new value of {@link #getDefaultExecutionDirectory()}.
604
   */
605
  public void setDefaultExecutionDirectory(Path defaultExecutionDirectory) {
606

607
    if (defaultExecutionDirectory != null) {
×
608
      this.defaultExecutionDirectory = defaultExecutionDirectory;
×
609
    }
610
  }
×
611

612
  @Override
613
  public GitContext getGitContext() {
614

615
    return new GitContextImpl(this);
×
616
  }
617

618
  @Override
619
  public ProcessContext newProcess() {
620

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

628
  @Override
629
  public IdeSystem getSystem() {
630

631
    if (this.system == null) {
×
632
      this.system = new IdeSystemImpl(this);
×
633
    }
634
    return this.system;
×
635
  }
636

637
  /**
638
   * @return a new instance of {@link ProcessContext}.
639
   * @see #newProcess()
640
   */
641
  protected ProcessContext createProcessContext() {
642

643
    return new ProcessContextImpl(this);
×
644
  }
645

646
  @Override
647
  public IdeSubLogger level(IdeLogLevel level) {
648

649
    return this.startContext.level(level);
5✔
650
  }
651

652
  @Override
653
  public void logIdeHomeAndRootStatus() {
654

655
    if (this.ideRoot != null) {
×
656
      success("IDE_ROOT is set to {}", this.ideRoot);
×
657
    }
658
    if (this.ideHome == null) {
×
659
      warning(getMessageIdeHomeNotFound());
×
660
    } else {
661
      success("IDE_HOME is set to {}", this.ideHome);
×
662
    }
663
  }
×
664

665
  @Override
666
  public String askForInput(String message, String defaultValue) {
667

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

682
  @Override
683
  public String askForInput(String message) {
684

685
    String input;
686
    do {
687
      info(message);
3✔
688
      input = readLine().trim();
4✔
689
    } while (input.isEmpty());
3!
690

691
    return input;
2✔
692
  }
693

694
  @SuppressWarnings("unchecked")
695
  @Override
696
  public <O> O question(String question, O... options) {
697

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

732
  /**
733
   * @return the input from the end-user (e.g. read from the console).
734
   */
735
  protected abstract String readLine();
736

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

739
    O duplicate = mapping.put(key, option);
×
740
    if (duplicate != null) {
×
741
      throw new IllegalArgumentException("Duplicated option " + key);
×
742
    }
743
  }
×
744

745
  @Override
746
  public Step getCurrentStep() {
747

748
    return this.currentStep;
×
749
  }
750

751
  @Override
752
  public StepImpl newStep(boolean silent, String name, Object... parameters) {
753

754
    this.currentStep = new StepImpl(this, this.currentStep, name, silent, parameters);
11✔
755
    return this.currentStep;
3✔
756
  }
757

758
  /**
759
   * Internal method to end the running {@link Step}.
760
   *
761
   * @param step the current {@link Step} to end.
762
   */
763
  public void endStep(StepImpl step) {
764

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

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

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

818
      HelpCommandlet help = this.commandletManager.getCommandlet(HelpCommandlet.class);
×
819
      if (firstCandidate != null) {
×
820
        help.commandlet.setValue(firstCandidate);
×
821
      }
822
      help.run();
×
823
      return 1;
×
824
    } catch (Throwable t) {
×
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, CompletionCandidateCollector) apply} and
836
   *     {@link Commandlet#run() run}.
837
   * @return {@code true} if the given {@link Commandlet} matched and did {@link Commandlet#run() run} successfully, {@code false} otherwise (the
838
   *     {@link Commandlet} did not match and we have to try a different candidate).
839
   */
840
  private ValidationResult applyAndRun(CliArguments arguments, Commandlet cmd) {
841

842
    cmd.clearProperties();
2✔
843

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

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

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

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

942

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

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

1004
  @Override
1005
  public String findBash() {
1006

1007
    String bash = "bash";
2✔
1008
    if (SystemInfoImpl.INSTANCE.isWindows()) {
3!
1009
      bash = findBashOnWindows();
×
1010
    }
1011

1012
    return bash;
2✔
1013
  }
1014

1015
  private String findBashOnWindows() {
1016

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

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

1032
        try {
1033
          Process process = new ProcessBuilder("cmd.exe", "/c", command).start();
×
1034
          try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
×
1035
            StringBuilder output = new StringBuilder();
×
1036
            String line;
1037

1038
            while ((line = reader.readLine()) != null) {
×
1039
              output.append(line);
×
1040
            }
1041

1042
            int exitCode = process.waitFor();
×
1043
            if (exitCode != 0) {
×
1044
              return null;
×
1045
            }
1046

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

1056
          }
×
1057
        } catch (Exception e) {
×
1058
          return null;
×
1059
        }
×
1060
      }
1061
    }
1062
    // no bash found
1063
    return null;
×
1064
  }
1065

1066
  @Override
1067
  public WindowsPathSyntax getPathSyntax() {
1068
    return this.pathSyntax;
3✔
1069
  }
1070

1071
  /**
1072
   * @param pathSyntax new value of {@link #getPathSyntax()}.
1073
   */
1074
  public void setPathSyntax(WindowsPathSyntax pathSyntax) {
1075

1076
    this.pathSyntax = pathSyntax;
3✔
1077
  }
1✔
1078

1079
  /**
1080
   * @return the {@link IdeStartContextImpl}.
1081
   */
1082
  public IdeStartContextImpl getStartContext() {
1083

1084
    return startContext;
3✔
1085
  }
1086

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