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

devonfw / IDEasy / 11660539114

04 Nov 2024 08:27AM UTC coverage: 66.948% (+0.03%) from 66.917%
11660539114

push

github

web-flow
#727: allow fallback to edition independent dependencies.json (#728)

2421 of 3958 branches covered (61.17%)

Branch coverage included in aggregate %.

6311 of 9085 relevant lines covered (69.47%)

3.06 hits per line

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

60.0
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.io.FileAccess;
32
import com.devonfw.tools.ide.io.FileAccessImpl;
33
import com.devonfw.tools.ide.log.IdeLogLevel;
34
import com.devonfw.tools.ide.log.IdeLogger;
35
import com.devonfw.tools.ide.log.IdeSubLogger;
36
import com.devonfw.tools.ide.merge.DirectoryMerger;
37
import com.devonfw.tools.ide.network.ProxyContext;
38
import com.devonfw.tools.ide.os.SystemInfo;
39
import com.devonfw.tools.ide.os.SystemInfoImpl;
40
import com.devonfw.tools.ide.os.WindowsPathSyntax;
41
import com.devonfw.tools.ide.process.ProcessContext;
42
import com.devonfw.tools.ide.process.ProcessContextImpl;
43
import com.devonfw.tools.ide.process.ProcessResult;
44
import com.devonfw.tools.ide.property.Property;
45
import com.devonfw.tools.ide.repo.CustomToolRepository;
46
import com.devonfw.tools.ide.repo.CustomToolRepositoryImpl;
47
import com.devonfw.tools.ide.repo.DefaultToolRepository;
48
import com.devonfw.tools.ide.repo.ToolRepository;
49
import com.devonfw.tools.ide.step.Step;
50
import com.devonfw.tools.ide.step.StepImpl;
51
import com.devonfw.tools.ide.url.model.UrlMetadata;
52
import com.devonfw.tools.ide.validation.ValidationResult;
53
import com.devonfw.tools.ide.validation.ValidationState;
54
import com.devonfw.tools.ide.variable.IdeVariables;
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 IdeStartContextImpl startContext;
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
  protected 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 toolRepositoryPath;
96

97
  protected 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
  protected ToolRepository defaultToolRepository;
114

115
  private CustomToolRepository customToolRepository;
116

117
  private DirectoryMerger workspaceMerger;
118

119
  protected UrlMetadata urlMetadata;
120

121
  protected Path defaultExecutionDirectory;
122

123
  private StepImpl currentStep;
124

125
  protected Boolean online;
126

127
  /**
128
   * The constructor.
129
   *
130
   * @param startContext the {@link IdeLogger}.
131
   * @param userDir the optional {@link Path} to current working directory.
132
   */
133
  public AbstractIdeContext(IdeStartContextImpl startContext, Path userDir) {
134

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

166
    // detection completed, initializing variables
167
    this.ideRoot = findIdeRoot(currentDir);
5✔
168

169
    setCwd(userDir, workspace, currentDir);
5✔
170

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

191
    this.defaultToolRepository = new DefaultToolRepository(this);
6✔
192
  }
1✔
193

194
  private Path findIdeRoot(Path ideHomePath) {
195

196
    Path ideRootPath = null;
2✔
197
    if (ideHomePath != null) {
2✔
198
      ideRootPath = ideHomePath.getParent();
4✔
199
    } else if (!isTest()) {
3!
200
      ideRootPath = getIdeRootPathFromEnv();
×
201
    }
202
    return ideRootPath;
2✔
203
  }
204

205
  private static Path getIdeRootPathFromEnv() {
206
    String root = System.getenv(IdeVariables.IDE_ROOT.getName());
×
207
    if (root != null) {
×
208
      Path rootPath = Path.of(root);
×
209
      if (Files.isDirectory(rootPath)) {
×
210
        return rootPath;
×
211
      }
212
    }
213
    return null;
×
214
  }
215

216
  @Override
217
  public void setCwd(Path userDir, String workspace, Path ideHome) {
218

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

250
    this.variables = createVariables();
4✔
251
    this.path = computeSystemPath();
4✔
252
    this.customToolRepository = CustomToolRepositoryImpl.of(this);
4✔
253
    this.workspaceMerger = new DirectoryMerger(this);
6✔
254
  }
1✔
255

256
  private String getMessageIdeHomeFound() {
257

258
    return "IDE environment variables have been set for " + this.ideHome + " in workspace " + this.workspaceName;
6✔
259
  }
260

261
  private String getMessageIdeHomeNotFound() {
262

263
    return "You are not inside an IDE installation: " + this.cwd;
×
264
  }
265

266
  private static String getMessageIdeRootNotFound() {
267
    String root = System.getenv("IDE_ROOT");
×
268
    if (root == null) {
×
269
      return "The environment variable IDE_ROOT is undefined. Please reinstall IDEasy or manually repair IDE_ROOT variable.";
×
270
    } else {
271
      return "The environment variable IDE_ROOT is pointing to an invalid path " + root + ". Please reinstall IDEasy or manually repair IDE_ROOT variable.";
×
272
    }
273
  }
274

275
  /**
276
   * @return the status message about the {@link #getIdeHome() IDE_HOME} detection and environment variable initialization.
277
   */
278
  public String getMessageIdeHome() {
279

280
    if (this.ideHome == null) {
×
281
      return getMessageIdeHomeNotFound();
×
282
    }
283
    return getMessageIdeHomeFound();
×
284
  }
285

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

291
    return false;
×
292
  }
293

294
  protected SystemPath computeSystemPath() {
295

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

299
  private boolean isIdeHome(Path dir) {
300

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

309
  private EnvironmentVariables createVariables() {
310

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

320
  protected AbstractEnvironmentVariables createSystemVariables() {
321

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

325
  protected AbstractEnvironmentVariables extendVariables(AbstractEnvironmentVariables envVariables, Path propertiesPath, EnvironmentVariablesType type) {
326

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

345
  @Override
346
  public SystemInfo getSystemInfo() {
347

348
    return this.systemInfo;
3✔
349
  }
350

351
  @Override
352
  public FileAccess getFileAccess() {
353

354
    return this.fileAccess;
3✔
355
  }
356

357
  @Override
358
  public CommandletManager getCommandletManager() {
359

360
    return this.commandletManager;
3✔
361
  }
362

363
  @Override
364
  public ToolRepository getDefaultToolRepository() {
365

366
    return this.defaultToolRepository;
3✔
367
  }
368

369
  @Override
370
  public CustomToolRepository getCustomToolRepository() {
371

372
    return this.customToolRepository;
3✔
373
  }
374

375
  @Override
376
  public Path getIdeHome() {
377

378
    return this.ideHome;
3✔
379
  }
380

381
  @Override
382
  public String getProjectName() {
383

384
    if (this.ideHome != null) {
3!
385
      return this.ideHome.getFileName().toString();
5✔
386
    }
387
    return "";
×
388
  }
389

390
  @Override
391
  public Path getIdeRoot() {
392

393
    return this.ideRoot;
3✔
394
  }
395

396
  @Override
397
  public Path getCwd() {
398

399
    return this.cwd;
3✔
400
  }
401

402
  @Override
403
  public Path getTempPath() {
404

405
    return this.tempPath;
3✔
406
  }
407

408
  @Override
409
  public Path getTempDownloadPath() {
410

411
    return this.tempDownloadPath;
3✔
412
  }
413

414
  @Override
415
  public Path getUserHome() {
416

417
    return this.userHome;
3✔
418
  }
419

420
  @Override
421
  public Path getUserHomeIde() {
422

423
    return this.userHomeIde;
3✔
424
  }
425

426
  @Override
427
  public Path getSettingsPath() {
428

429
    return this.settingsPath;
3✔
430
  }
431

432
  @Override
433
  public Path getConfPath() {
434

435
    return this.confPath;
3✔
436
  }
437

438
  @Override
439
  public Path getSoftwarePath() {
440

441
    return this.softwarePath;
3✔
442
  }
443

444
  @Override
445
  public Path getSoftwareExtraPath() {
446

447
    return this.softwareExtraPath;
3✔
448
  }
449

450
  @Override
451
  public Path getSoftwareRepositoryPath() {
452

453
    return this.softwareRepositoryPath;
3✔
454
  }
455

456
  @Override
457
  public Path getPluginsPath() {
458

459
    return this.pluginsPath;
3✔
460
  }
461

462
  @Override
463
  public String getWorkspaceName() {
464

465
    return this.workspaceName;
3✔
466
  }
467

468
  @Override
469
  public Path getWorkspacePath() {
470

471
    return this.workspacePath;
3✔
472
  }
473

474
  @Override
475
  public Path getDownloadPath() {
476

477
    return this.downloadPath;
3✔
478
  }
479

480
  @Override
481
  public Path getUrlsPath() {
482

483
    return this.urlsPath;
3✔
484
  }
485

486
  @Override
487
  public Path getToolRepositoryPath() {
488

489
    return this.toolRepositoryPath;
3✔
490
  }
491

492
  @Override
493
  public SystemPath getPath() {
494

495
    return this.path;
3✔
496
  }
497

498
  @Override
499
  public EnvironmentVariables getVariables() {
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 isOnline() {
542

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

561
  @Override
562
  public Locale getLocale() {
563

564
    Locale locale = this.startContext.getLocale();
4✔
565
    if (locale == null) {
2!
566
      locale = Locale.getDefault();
×
567
    }
568
    return locale;
2✔
569
  }
570

571
  @Override
572
  public DirectoryMerger getWorkspaceMerger() {
573

574
    return this.workspaceMerger;
3✔
575
  }
576

577
  /**
578
   * @return the {@link #getDefaultExecutionDirectory() default execution directory} in which a command process is executed.
579
   */
580
  @Override
581
  public Path getDefaultExecutionDirectory() {
582

583
    return this.defaultExecutionDirectory;
×
584
  }
585

586
  /**
587
   * @param defaultExecutionDirectory new value of {@link #getDefaultExecutionDirectory()}.
588
   */
589
  public void setDefaultExecutionDirectory(Path defaultExecutionDirectory) {
590

591
    if (defaultExecutionDirectory != null) {
×
592
      this.defaultExecutionDirectory = defaultExecutionDirectory;
×
593
    }
594
  }
×
595

596
  @Override
597
  public ProxyContext getProxyContext() {
598

599
    return new ProxyContext(this);
5✔
600
  }
601

602
  @Override
603
  public GitContext getGitContext() {
604

605
    return new GitContextImpl(this);
×
606
  }
607

608
  @Override
609
  public ProcessContext newProcess() {
610

611
    ProcessContext processContext = createProcessContext();
3✔
612
    if (this.defaultExecutionDirectory != null) {
3!
613
      processContext.directory(this.defaultExecutionDirectory);
×
614
    }
615
    return processContext;
2✔
616
  }
617

618
  /**
619
   * @return a new instance of {@link ProcessContext}.
620
   * @see #newProcess()
621
   */
622
  protected ProcessContext createProcessContext() {
623

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

627
  @Override
628
  public IdeSubLogger level(IdeLogLevel level) {
629

630
    return this.startContext.level(level);
5✔
631
  }
632

633
  @Override
634
  public String askForInput(String message, String defaultValue) {
635

636
    if (!message.isBlank()) {
×
637
      info(message);
×
638
    }
639
    if (isBatchMode()) {
×
640
      if (isForceMode()) {
×
641
        return defaultValue;
×
642
      } else {
643
        throw new CliAbortException();
×
644
      }
645
    }
646
    String input = readLine().trim();
×
647
    return input.isEmpty() ? defaultValue : input;
×
648
  }
649

650
  @Override
651
  public String askForInput(String message) {
652

653
    String input;
654
    do {
655
      info(message);
3✔
656
      input = readLine().trim();
4✔
657
    } while (input.isEmpty());
3!
658

659
    return input;
2✔
660
  }
661

662
  @SuppressWarnings("unchecked")
663
  @Override
664
  public <O> O question(String question, O... options) {
665

666
    assert (options.length >= 2);
×
667
    interaction(question);
×
668
    Map<String, O> mapping = new HashMap<>(options.length);
×
669
    int i = 0;
×
670
    for (O option : options) {
×
671
      i++;
×
672
      String key = "" + option;
×
673
      addMapping(mapping, key, option);
×
674
      String numericKey = Integer.toString(i);
×
675
      if (numericKey.equals(key)) {
×
676
        trace("Options should not be numeric: " + key);
×
677
      } else {
678
        addMapping(mapping, numericKey, option);
×
679
      }
680
      interaction("Option " + numericKey + ": " + key);
×
681
    }
682
    O option = null;
×
683
    if (isBatchMode()) {
×
684
      if (isForceMode()) {
×
685
        option = options[0];
×
686
        interaction("" + option);
×
687
      }
688
    } else {
689
      while (option == null) {
×
690
        String answer = readLine();
×
691
        option = mapping.get(answer);
×
692
        if (option == null) {
×
693
          warning("Invalid answer: '" + answer + "' - please try again.");
×
694
        }
695
      }
×
696
    }
697
    return option;
×
698
  }
699

700
  /**
701
   * @return the input from the end-user (e.g. read from the console).
702
   */
703
  protected abstract String readLine();
704

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

707
    O duplicate = mapping.put(key, option);
×
708
    if (duplicate != null) {
×
709
      throw new IllegalArgumentException("Duplicated option " + key);
×
710
    }
711
  }
×
712

713
  @Override
714
  public Step getCurrentStep() {
715

716
    return this.currentStep;
×
717
  }
718

719
  @Override
720
  public StepImpl newStep(boolean silent, String name, Object... parameters) {
721

722
    this.currentStep = new StepImpl(this, this.currentStep, name, silent, parameters);
11✔
723
    return this.currentStep;
3✔
724
  }
725

726
  /**
727
   * Internal method to end the running {@link Step}.
728
   *
729
   * @param step the current {@link Step} to end.
730
   */
731
  public void endStep(StepImpl step) {
732

733
    if (step == this.currentStep) {
4!
734
      this.currentStep = this.currentStep.getParent();
6✔
735
    } else {
736
      String currentStepName = "null";
×
737
      if (this.currentStep != null) {
×
738
        currentStepName = this.currentStep.getName();
×
739
      }
740
      warning("endStep called with wrong step '{}' but expected '{}'", step.getName(), currentStepName);
×
741
    }
742
  }
1✔
743

744
  /**
745
   * Finds the matching {@link Commandlet} to run, applies {@link CliArguments} to its {@link Commandlet#getProperties() properties} and will execute it.
746
   *
747
   * @param arguments the {@link CliArgument}.
748
   * @return the return code of the execution.
749
   */
750
  public int run(CliArguments arguments) {
751

752
    CliArgument current = arguments.current();
3✔
753
    assert (this.currentStep == null);
4!
754
    boolean supressStepSuccess = false;
2✔
755
    StepImpl step = newStep(true, "ide", (Object[]) current.asArray());
8✔
756
    Commandlet firstCandidate = null;
2✔
757
    try {
758
      if (!current.isEnd()) {
3!
759
        String keyword = current.get();
3✔
760
        firstCandidate = this.commandletManager.getCommandletByFirstKeyword(keyword);
5✔
761
        ValidationResult firstResult = null;
2✔
762
        if (firstCandidate != null) {
2!
763
          firstResult = applyAndRun(arguments.copy(), firstCandidate);
6✔
764
          if (firstResult.isValid()) {
3!
765
            supressStepSuccess = firstCandidate.isSuppressStepSuccess();
3✔
766
            step.success();
2✔
767
            return ProcessResult.SUCCESS;
4✔
768
          }
769
        }
770
        for (Commandlet cmd : this.commandletManager.getCommandlets()) {
×
771
          if (cmd != firstCandidate) {
×
772
            ValidationResult result = applyAndRun(arguments.copy(), cmd);
×
773
            if (result.isValid()) {
×
774
              supressStepSuccess = cmd.isSuppressStepSuccess();
×
775
              step.success();
×
776
              return ProcessResult.SUCCESS;
×
777
            }
778
          }
779
        }
×
780
        if (firstResult != null) {
×
781
          throw new CliException(firstResult.getErrorMessage());
×
782
        }
783
        step.error("Invalid arguments: {}", current.getArgs());
×
784
      }
785

786
      HelpCommandlet help = this.commandletManager.getCommandlet(HelpCommandlet.class);
×
787
      if (firstCandidate != null) {
×
788
        help.commandlet.setValue(firstCandidate);
×
789
      }
790
      help.run();
×
791
      return 1;
×
792
    } catch (Throwable t) {
×
793
      step.error(t, true);
×
794
      throw t;
×
795
    } finally {
796
      step.close();
2✔
797
      assert (this.currentStep == null);
4!
798
      step.logSummary(supressStepSuccess);
3✔
799
    }
800
  }
801

802
  /**
803
   * @param cmd the potential {@link Commandlet} to {@link #apply(CliArguments, Commandlet, CompletionCandidateCollector) apply} and
804
   *     {@link Commandlet#run() run}.
805
   * @return {@code true} if the given {@link Commandlet} matched and did {@link Commandlet#run() run} successfully, {@code false} otherwise (the
806
   *     {@link Commandlet} did not match and we have to try a different candidate).
807
   */
808
  private ValidationResult applyAndRun(CliArguments arguments, Commandlet cmd) {
809

810
    cmd.clearProperties();
2✔
811

812
    ValidationResult result = apply(arguments, cmd, null);
6✔
813
    if (result.isValid()) {
3!
814
      result = cmd.validate();
3✔
815
    }
816
    if (result.isValid()) {
3!
817
      debug("Running commandlet {}", cmd);
9✔
818
      if (cmd.isIdeHomeRequired() && (this.ideHome == null)) {
6!
819
        throw new CliException(getMessageIdeHomeNotFound(), ProcessResult.NO_IDE_HOME);
×
820
      } else if (cmd.isIdeRootRequired() && (this.ideRoot == null)) {
6!
821
        throw new CliException(getMessageIdeRootNotFound(), ProcessResult.NO_IDE_ROOT);
×
822
      }
823
      if (cmd.isProcessableOutput()) {
3!
824
        if (!debug().isEnabled()) {
×
825
          // unless --debug or --trace was supplied, processable output commandlets will disable all log-levels except INFO to prevent other logs interfere
826
          for (IdeLogLevel level : IdeLogLevel.values()) {
×
827
            if (level != IdeLogLevel.INFO) {
×
828
              this.startContext.setLogLevel(level, false);
×
829
            }
830
          }
831
        }
832
      } else {
833
        if (!isTest()) {
3!
834
          if (this.ideRoot == null) {
×
835
            warning("Variable IDE_ROOT is undefined. Please check your installation or run setup script again.");
×
836
          } else if (this.ideHome != null) {
×
837
            Path ideRootPath = getIdeRootPathFromEnv();
×
838
            if (!this.ideRoot.equals(ideRootPath)) {
×
839
              warning("Variable IDE_ROOT is set to '{}' but for your project '{}' the path '{}' would have been expected.", ideRootPath,
×
840
                  this.ideHome.getFileName(), this.ideRoot);
×
841
            }
842
          }
843
        }
844
        if (cmd.isIdeHomeRequired()) {
3!
845
          debug(getMessageIdeHomeFound());
4✔
846
        }
847
      }
848
      if (this.settingsPath != null) {
3!
849
        if (getGitContext().isRepositoryUpdateAvailable(this.settingsPath) ||
7!
850
            (getGitContext().fetchIfNeeded(this.settingsPath) && getGitContext().isRepositoryUpdateAvailable(this.settingsPath))) {
5!
851
          interaction("Updates are available for the settings repository. If you want to pull the latest changes, call ide update.");
×
852
        }
853
      }
854
      cmd.run();
3✔
855
    } else {
856
      trace("Commandlet did not match");
×
857
    }
858
    return result;
2✔
859
  }
860

861
  /**
862
   * @param arguments the {@link CliArguments#ofCompletion(String...) completion arguments}.
863
   * @param includeContextOptions to include the options of {@link ContextCommandlet}.
864
   * @return the {@link List} of {@link CompletionCandidate}s to suggest.
865
   */
866
  public List<CompletionCandidate> complete(CliArguments arguments, boolean includeContextOptions) {
867

868
    CompletionCandidateCollector collector = new CompletionCandidateCollectorDefault(this);
5✔
869
    if (arguments.current().isStart()) {
4✔
870
      arguments.next();
3✔
871
    }
872
    if (includeContextOptions) {
2✔
873
      ContextCommandlet cc = new ContextCommandlet();
4✔
874
      for (Property<?> property : cc.getProperties()) {
11✔
875
        assert (property.isOption());
4!
876
        property.apply(arguments, this, cc, collector);
7✔
877
      }
1✔
878
    }
879
    CliArgument current = arguments.current();
3✔
880
    if (!current.isEnd()) {
3!
881
      String keyword = current.get();
3✔
882
      Commandlet firstCandidate = this.commandletManager.getCommandletByFirstKeyword(keyword);
5✔
883
      boolean matches = false;
2✔
884
      if (firstCandidate != null) {
2✔
885
        matches = completeCommandlet(arguments, firstCandidate, collector);
7✔
886
      } else if (current.isCombinedShortOption()) {
3✔
887
        collector.add(keyword, null, null, null);
6✔
888
      }
889
      if (!matches) {
2!
890
        for (Commandlet cmd : this.commandletManager.getCommandlets()) {
12✔
891
          if (cmd != firstCandidate) {
3✔
892
            completeCommandlet(arguments, cmd, collector);
6✔
893
          }
894
        }
1✔
895
      }
896
    }
897
    return collector.getSortedCandidates();
3✔
898
  }
899

900
  private boolean completeCommandlet(CliArguments arguments, Commandlet cmd, CompletionCandidateCollector collector) {
901
    if (cmd.isIdeHomeRequired() && (this.ideHome == null)) {
6!
902
      return false;
×
903
    } else {
904
      return apply(arguments.copy(), cmd, collector).isValid();
8✔
905
    }
906
  }
907

908

909
  /**
910
   * @param arguments the {@link CliArguments} to apply. Will be {@link CliArguments#next() consumed} as they are matched. Consider passing a
911
   *     {@link CliArguments#copy() copy} as needed.
912
   * @param cmd the potential {@link Commandlet} to match.
913
   * @param collector the {@link CompletionCandidateCollector}.
914
   * @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}
915
   *     and {@link Commandlet#validate() validated}), {@code false} otherwise (the {@link Commandlet} did not match and we have to try a different candidate).
916
   */
917
  public ValidationResult apply(CliArguments arguments, Commandlet cmd, CompletionCandidateCollector collector) {
918

919
    trace("Trying to match arguments to commandlet {}", cmd.getName());
10✔
920
    CliArgument currentArgument = arguments.current();
3✔
921
    Iterator<Property<?>> propertyIterator;
922
    if (currentArgument.isCompletion()) {
3✔
923
      propertyIterator = cmd.getProperties().iterator();
5✔
924
    } else {
925
      propertyIterator = cmd.getValues().iterator();
4✔
926
    }
927
    Property<?> property = null;
2✔
928
    if (propertyIterator.hasNext()) {
3✔
929
      property = propertyIterator.next();
4✔
930
    }
931
    while (!currentArgument.isEnd()) {
3✔
932
      trace("Trying to match argument '{}'", currentArgument);
9✔
933
      Property<?> currentProperty = property;
2✔
934
      if (!arguments.isEndOptions()) {
3!
935
        Property<?> option = cmd.getOption(currentArgument.getKey());
5✔
936
        if (option != null) {
2✔
937
          currentProperty = option;
2✔
938
        }
939
      }
940
      if (currentProperty == null) {
2✔
941
        trace("No option or next value found");
3✔
942
        ValidationState state = new ValidationState(null);
5✔
943
        state.addErrorMessage("No matching property found");
3✔
944
        return state;
2✔
945
      }
946
      trace("Next property candidate to match argument is {}", currentProperty);
9✔
947
      if (currentProperty == property) {
3✔
948
        if (!property.isMultiValued()) {
3✔
949
          if (propertyIterator.hasNext()) {
3✔
950
            property = propertyIterator.next();
5✔
951
          } else {
952
            property = null;
2✔
953
          }
954
        }
955
        if ((property != null) && property.isValue() && property.isMultiValued()) {
8✔
956
          arguments.stopSplitShortOptions();
2✔
957
        }
958
      }
959
      boolean matches = currentProperty.apply(arguments, this, cmd, collector);
7✔
960
      if (!matches || currentArgument.isCompletion()) {
5✔
961
        ValidationState state = new ValidationState(null);
5✔
962
        state.addErrorMessage("No matching property found");
3✔
963
        return state;
2✔
964
      }
965
      currentArgument = arguments.current();
3✔
966
    }
1✔
967
    return new ValidationState(null);
5✔
968
  }
969

970
  @Override
971
  public String findBash() {
972

973
    String bash = "bash";
2✔
974
    if (SystemInfoImpl.INSTANCE.isWindows()) {
3!
975
      bash = findBashOnWindows();
×
976
    }
977

978
    return bash;
2✔
979
  }
980

981
  private String findBashOnWindows() {
982

983
    // Check if Git Bash exists in the default location
984
    Path defaultPath = Path.of("C:\\Program Files\\Git\\bin\\bash.exe");
×
985
    if (Files.exists(defaultPath)) {
×
986
      return defaultPath.toString();
×
987
    }
988

989
    // If not found in the default location, try the registry query
990
    String[] bashVariants = { "GitForWindows", "Cygwin\\setup" };
×
991
    String[] registryKeys = { "HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER" };
×
992
    String regQueryResult;
993
    for (String bashVariant : bashVariants) {
×
994
      for (String registryKey : registryKeys) {
×
995
        String toolValueName = ("GitForWindows".equals(bashVariant)) ? "InstallPath" : "rootdir";
×
996
        String command = "reg query " + registryKey + "\\Software\\" + bashVariant + "  /v " + toolValueName + " 2>nul";
×
997

998
        try {
999
          Process process = new ProcessBuilder("cmd.exe", "/c", command).start();
×
1000
          try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
×
1001
            StringBuilder output = new StringBuilder();
×
1002
            String line;
1003

1004
            while ((line = reader.readLine()) != null) {
×
1005
              output.append(line);
×
1006
            }
1007

1008
            int exitCode = process.waitFor();
×
1009
            if (exitCode != 0) {
×
1010
              return null;
×
1011
            }
1012

1013
            regQueryResult = output.toString();
×
1014
            if (regQueryResult != null) {
×
1015
              int index = regQueryResult.indexOf("REG_SZ");
×
1016
              if (index != -1) {
×
1017
                String path = regQueryResult.substring(index + "REG_SZ".length()).trim();
×
1018
                return path + "\\bin\\bash.exe";
×
1019
              }
1020
            }
1021

1022
          }
×
1023
        } catch (Exception e) {
×
1024
          return null;
×
1025
        }
×
1026
      }
1027
    }
1028
    // no bash found
1029
    return null;
×
1030
  }
1031

1032
  @Override
1033
  public WindowsPathSyntax getPathSyntax() {
1034
    return this.pathSyntax;
3✔
1035
  }
1036

1037
  /**
1038
   * @param pathSyntax new value of {@link #getPathSyntax()}.
1039
   */
1040
  public void setPathSyntax(WindowsPathSyntax pathSyntax) {
1041

1042
    this.pathSyntax = pathSyntax;
3✔
1043
  }
1✔
1044

1045
  /**
1046
   * @return the {@link IdeStartContextImpl}.
1047
   */
1048
  public IdeStartContextImpl getStartContext() {
1049

1050
    return startContext;
3✔
1051
  }
1052

1053
  /**
1054
   * Reloads this context and re-initializes the {@link #getVariables() variables}.
1055
   */
1056
  public void reload() {
1057
    this.variables = createVariables();
4✔
1058
  }
1✔
1059
}
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