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

devonfw / IDEasy / 12753118702

13 Jan 2025 05:54PM UTC coverage: 68.077% (+0.5%) from 67.541%
12753118702

Pull #820

github

web-flow
Merge 0eac439b8 into 2145d88f3
Pull Request #820: #759: upgrade settings commandlet

2689 of 4311 branches covered (62.38%)

Branch coverage included in aggregate %.

6946 of 9842 relevant lines covered (70.58%)

3.1 hits per line

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

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

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

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

63
/**
64
 * Abstract base implementation of {@link IdeContext}.
65
 */
66
public abstract class AbstractIdeContext implements IdeContext {
67

68
  private static final GitUrl IDE_URLS_GIT = new GitUrl("https://github.com/devonfw/ide-urls.git", null);
7✔
69

70
  private final IdeStartContextImpl startContext;
71

72
  private Path ideHome;
73

74
  private final Path ideRoot;
75

76
  private Path confPath;
77

78
  protected Path settingsPath;
79

80
  private Path softwarePath;
81

82
  private Path softwareExtraPath;
83

84
  private final Path softwareRepositoryPath;
85

86
  protected Path pluginsPath;
87

88
  private Path workspacePath;
89

90
  private String workspaceName;
91

92
  protected Path urlsPath;
93

94
  private final Path tempPath;
95

96
  private final Path tempDownloadPath;
97

98
  private Path cwd;
99

100
  private Path downloadPath;
101

102
  private final Path toolRepositoryPath;
103

104
  protected Path userHome;
105

106
  private Path userHomeIde;
107

108
  private SystemPath path;
109

110
  private WindowsPathSyntax pathSyntax;
111

112
  private final SystemInfo systemInfo;
113

114
  private EnvironmentVariables variables;
115

116
  private final FileAccess fileAccess;
117

118
  protected CommandletManager commandletManager;
119

120
  protected ToolRepository defaultToolRepository;
121

122
  private CustomToolRepository customToolRepository;
123

124
  private DirectoryMerger workspaceMerger;
125

126
  protected UrlMetadata urlMetadata;
127

128
  protected Path defaultExecutionDirectory;
129

130
  private StepImpl currentStep;
131

132
  protected Boolean online;
133

134
  protected IdeSystem system;
135

136
  private NetworkProxy networkProxy;
137

138
  /**
139
   * The constructor.
140
   *
141
   * @param startContext the {@link IdeLogger}.
142
   * @param workingDirectory the optional {@link Path} to current working directory.
143
   */
144
  public AbstractIdeContext(IdeStartContextImpl startContext, Path workingDirectory) {
145

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

177
    // detection completed, initializing variables
178
    this.ideRoot = findIdeRoot(currentDir);
5✔
179

180
    setCwd(workingDirectory, workspace, currentDir);
5✔
181

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

202
    this.defaultToolRepository = new DefaultToolRepository(this);
6✔
203
  }
1✔
204

205
  private Path findIdeRoot(Path ideHomePath) {
206

207
    Path ideRootPath = null;
2✔
208
    if (ideHomePath != null) {
2✔
209
      ideRootPath = ideHomePath.getParent();
4✔
210
    } else if (!isTest()) {
3!
211
      ideRootPath = getIdeRootPathFromEnv();
×
212
    }
213
    return ideRootPath;
2✔
214
  }
215

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

227
  @Override
228
  public void setCwd(Path userDir, String workspace, Path ideHome) {
229

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

261
    this.path = computeSystemPath();
4✔
262
    this.customToolRepository = CustomToolRepositoryImpl.of(this);
4✔
263
  }
1✔
264

265
  private String getMessageIdeHomeFound() {
266

267
    return "IDE environment variables have been set for " + this.ideHome + " in workspace " + this.workspaceName;
6✔
268
  }
269

270
  private String getMessageIdeHomeNotFound() {
271

272
    return "You are not inside an IDE installation: " + this.cwd;
4✔
273
  }
274

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

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

289
    return false;
×
290
  }
291

292
  protected SystemPath computeSystemPath() {
293

294
    return new SystemPath(this);
×
295
  }
296

297

298
  private boolean isIdeHome(Path dir) {
299

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

308
  private EnvironmentVariables createVariables() {
309

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

318
  protected AbstractEnvironmentVariables createSystemVariables() {
319

320
    return EnvironmentVariables.ofSystem(this);
3✔
321
  }
322

323
  @Override
324
  public SystemInfo getSystemInfo() {
325

326
    return this.systemInfo;
3✔
327
  }
328

329
  @Override
330
  public FileAccess getFileAccess() {
331

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

337
  @Override
338
  public CommandletManager getCommandletManager() {
339

340
    return this.commandletManager;
3✔
341
  }
342

343
  @Override
344
  public ToolRepository getDefaultToolRepository() {
345

346
    return this.defaultToolRepository;
3✔
347
  }
348

349
  @Override
350
  public CustomToolRepository getCustomToolRepository() {
351

352
    return this.customToolRepository;
3✔
353
  }
354

355
  @Override
356
  public Path getIdeHome() {
357

358
    return this.ideHome;
3✔
359
  }
360

361
  @Override
362
  public String getProjectName() {
363

364
    if (this.ideHome != null) {
3!
365
      return this.ideHome.getFileName().toString();
5✔
366
    }
367
    return "";
×
368
  }
369

370
  @Override
371
  public Path getIdeRoot() {
372

373
    return this.ideRoot;
3✔
374
  }
375

376
  @Override
377
  public Path getCwd() {
378

379
    return this.cwd;
3✔
380
  }
381

382
  @Override
383
  public Path getTempPath() {
384

385
    return this.tempPath;
3✔
386
  }
387

388
  @Override
389
  public Path getTempDownloadPath() {
390

391
    return this.tempDownloadPath;
3✔
392
  }
393

394
  @Override
395
  public Path getUserHome() {
396

397
    return this.userHome;
3✔
398
  }
399

400
  @Override
401
  public Path getUserHomeIde() {
402

403
    return this.userHomeIde;
3✔
404
  }
405

406
  @Override
407
  public Path getSettingsPath() {
408

409
    return this.settingsPath;
3✔
410
  }
411

412
  @Override
413
  public Path getConfPath() {
414

415
    return this.confPath;
3✔
416
  }
417

418
  @Override
419
  public Path getSoftwarePath() {
420

421
    return this.softwarePath;
3✔
422
  }
423

424
  @Override
425
  public Path getSoftwareExtraPath() {
426

427
    return this.softwareExtraPath;
3✔
428
  }
429

430
  @Override
431
  public Path getSoftwareRepositoryPath() {
432

433
    return this.softwareRepositoryPath;
3✔
434
  }
435

436
  @Override
437
  public Path getPluginsPath() {
438

439
    return this.pluginsPath;
3✔
440
  }
441

442
  @Override
443
  public String getWorkspaceName() {
444

445
    return this.workspaceName;
3✔
446
  }
447

448
  @Override
449
  public Path getWorkspacePath() {
450

451
    return this.workspacePath;
3✔
452
  }
453

454
  @Override
455
  public Path getDownloadPath() {
456

457
    return this.downloadPath;
3✔
458
  }
459

460
  @Override
461
  public Path getUrlsPath() {
462

463
    return this.urlsPath;
3✔
464
  }
465

466
  @Override
467
  public Path getToolRepositoryPath() {
468

469
    return this.toolRepositoryPath;
3✔
470
  }
471

472
  @Override
473
  public SystemPath getPath() {
474

475
    return this.path;
3✔
476
  }
477

478
  @Override
479
  public EnvironmentVariables getVariables() {
480

481
    if (this.variables == null) {
3✔
482
      this.variables = createVariables();
4✔
483
    }
484
    return this.variables;
3✔
485
  }
486

487
  @Override
488
  public UrlMetadata getUrls() {
489

490
    if (this.urlMetadata == null) {
3✔
491
      if (!isTest()) {
3!
492
        getGitContext().pullOrCloneAndResetIfNeeded(IDE_URLS_GIT, this.urlsPath, null);
×
493
      }
494
      this.urlMetadata = new UrlMetadata(this);
6✔
495
    }
496
    return this.urlMetadata;
3✔
497
  }
498

499
  @Override
500
  public boolean isQuietMode() {
501

502
    return this.startContext.isQuietMode();
4✔
503
  }
504

505
  @Override
506
  public boolean isBatchMode() {
507

508
    return this.startContext.isBatchMode();
×
509
  }
510

511
  @Override
512
  public boolean isForceMode() {
513

514
    return this.startContext.isForceMode();
4✔
515
  }
516

517
  @Override
518
  public boolean isOfflineMode() {
519

520
    return this.startContext.isOfflineMode();
4✔
521
  }
522

523
  @Override
524
  public boolean isSkipUpdatesMode() {
525
    return this.startContext.isSkipUpdatesMode();
×
526
  }
527

528
  @Override
529
  public boolean isOnline() {
530

531
    if (this.online == null) {
3✔
532
      configureNetworkProxy();
2✔
533
      // we currently assume we have only a CLI process that runs shortly
534
      // therefore we run this check only once to save resources when this method is called many times
535
      try {
536
        int timeout = 1000;
2✔
537
        //open a connection to github.com and try to retrieve data
538
        //getContent fails if there is no connection
539
        URLConnection connection = new URL("https://www.github.com").openConnection();
6✔
540
        connection.setConnectTimeout(timeout);
3✔
541
        connection.getContent();
3✔
542
        this.online = Boolean.TRUE;
3✔
543
      } catch (Exception ignored) {
×
544
        this.online = Boolean.FALSE;
×
545
      }
1✔
546
    }
547
    return this.online.booleanValue();
4✔
548
  }
549

550
  private void configureNetworkProxy() {
551
    if (this.networkProxy == null) {
3✔
552
      this.networkProxy = new NetworkProxy(this);
6✔
553
      this.networkProxy.configure();
3✔
554
    }
555
  }
1✔
556

557
  @Override
558
  public Locale getLocale() {
559

560
    Locale locale = this.startContext.getLocale();
4✔
561
    if (locale == null) {
2!
562
      locale = Locale.getDefault();
×
563
    }
564
    return locale;
2✔
565
  }
566

567
  @Override
568
  public DirectoryMerger getWorkspaceMerger() {
569

570
    if (this.workspaceMerger == null) {
3✔
571
      this.workspaceMerger = new DirectoryMerger(this);
6✔
572
    }
573
    return this.workspaceMerger;
3✔
574
  }
575

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

582
    return this.defaultExecutionDirectory;
×
583
  }
584

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

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

595
  @Override
596
  public GitContext getGitContext() {
597

598
    return new GitContextImpl(this);
×
599
  }
600

601
  @Override
602
  public ProcessContext newProcess() {
603

604
    ProcessContext processContext = createProcessContext();
3✔
605
    if (this.defaultExecutionDirectory != null) {
3!
606
      processContext.directory(this.defaultExecutionDirectory);
×
607
    }
608
    return processContext;
2✔
609
  }
610

611
  @Override
612
  public IdeSystem getSystem() {
613

614
    if (this.system == null) {
×
615
      this.system = new IdeSystemImpl(this);
×
616
    }
617
    return this.system;
×
618
  }
619

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

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

629
  @Override
630
  public IdeSubLogger level(IdeLogLevel level) {
631

632
    return this.startContext.level(level);
5✔
633
  }
634

635
  @Override
636
  public void logIdeHomeAndRootStatus() {
637

638
    if (this.ideRoot != null) {
3!
639
      success("IDE_ROOT is set to {}", this.ideRoot);
×
640
    }
641
    if (this.ideHome == null) {
3!
642
      warning(getMessageIdeHomeNotFound());
5✔
643
    } else {
644
      success("IDE_HOME is set to {}", this.ideHome);
×
645
    }
646
  }
1✔
647

648
  @Override
649
  public String askForInput(String message, String defaultValue) {
650

651
    if (!message.isBlank()) {
×
652
      info(message);
×
653
    }
654
    if (isBatchMode()) {
×
655
      if (isForceMode()) {
×
656
        return defaultValue;
×
657
      } else {
658
        throw new CliAbortException();
×
659
      }
660
    }
661
    String input = readLine().trim();
×
662
    return input.isEmpty() ? defaultValue : input;
×
663
  }
664

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

668
    String input;
669
    do {
670
      info(message);
3✔
671
      input = readLine().trim();
4✔
672
    } while (input.isEmpty());
3!
673

674
    return input;
2✔
675
  }
676

677
  @SuppressWarnings("unchecked")
678
  @Override
679
  public <O> O question(String question, O... options) {
680

681
    assert (options.length >= 2);
×
682
    interaction(question);
×
683
    Map<String, O> mapping = new HashMap<>(options.length);
×
684
    int i = 0;
×
685
    for (O option : options) {
×
686
      i++;
×
687
      String key = "" + option;
×
688
      addMapping(mapping, key, option);
×
689
      String numericKey = Integer.toString(i);
×
690
      if (numericKey.equals(key)) {
×
691
        trace("Options should not be numeric: " + key);
×
692
      } else {
693
        addMapping(mapping, numericKey, option);
×
694
      }
695
      interaction("Option " + numericKey + ": " + key);
×
696
    }
697
    O option = null;
×
698
    if (isBatchMode()) {
×
699
      if (isForceMode()) {
×
700
        option = options[0];
×
701
        interaction("" + option);
×
702
      }
703
    } else {
704
      while (option == null) {
×
705
        String answer = readLine();
×
706
        option = mapping.get(answer);
×
707
        if (option == null) {
×
708
          warning("Invalid answer: '" + answer + "' - please try again.");
×
709
        }
710
      }
×
711
    }
712
    return option;
×
713
  }
714

715
  /**
716
   * @return the input from the end-user (e.g. read from the console).
717
   */
718
  protected abstract String readLine();
719

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

722
    O duplicate = mapping.put(key, option);
×
723
    if (duplicate != null) {
×
724
      throw new IllegalArgumentException("Duplicated option " + key);
×
725
    }
726
  }
×
727

728
  @Override
729
  public Step getCurrentStep() {
730

731
    return this.currentStep;
×
732
  }
733

734
  @Override
735
  public StepImpl newStep(boolean silent, String name, Object... parameters) {
736

737
    this.currentStep = new StepImpl(this, this.currentStep, name, silent, parameters);
11✔
738
    return this.currentStep;
3✔
739
  }
740

741
  /**
742
   * Internal method to end the running {@link Step}.
743
   *
744
   * @param step the current {@link Step} to end.
745
   */
746
  public void endStep(StepImpl step) {
747

748
    if (step == this.currentStep) {
4!
749
      this.currentStep = this.currentStep.getParent();
6✔
750
    } else {
751
      String currentStepName = "null";
×
752
      if (this.currentStep != null) {
×
753
        currentStepName = this.currentStep.getName();
×
754
      }
755
      warning("endStep called with wrong step '{}' but expected '{}'", step.getName(), currentStepName);
×
756
    }
757
  }
1✔
758

759
  /**
760
   * Finds the matching {@link Commandlet} to run, applies {@link CliArguments} to its {@link Commandlet#getProperties() properties} and will execute it.
761
   *
762
   * @param arguments the {@link CliArgument}.
763
   * @return the return code of the execution.
764
   */
765
  public int run(CliArguments arguments) {
766

767
    CliArgument current = arguments.current();
3✔
768
    assert (this.currentStep == null);
4!
769
    boolean supressStepSuccess = false;
2✔
770
    StepImpl step = newStep(true, "ide", (Object[]) current.asArray());
8✔
771
    Iterator<Commandlet> commandletIterator = this.commandletManager.findCommandlet(arguments, null);
6✔
772
    Commandlet cmd = null;
2✔
773
    ValidationResult result = null;
2✔
774
    try {
775
      while (commandletIterator.hasNext()) {
3!
776
        cmd = commandletIterator.next();
4✔
777
        result = applyAndRun(arguments.copy(), cmd);
6✔
778
        if (result.isValid()) {
3!
779
          supressStepSuccess = cmd.isSuppressStepSuccess();
3✔
780
          step.success();
2✔
781
          return ProcessResult.SUCCESS;
4✔
782
        }
783
      }
784
      this.startContext.activateLogging();
×
785
      if (result != null) {
×
786
        error(result.getErrorMessage());
×
787
      }
788
      step.error("Invalid arguments: {}", current.getArgs());
×
789
      HelpCommandlet help = this.commandletManager.getCommandlet(HelpCommandlet.class);
×
790
      if (cmd != null) {
×
791
        help.commandlet.setValue(cmd);
×
792
      }
793
      help.run();
×
794
      return 1;
×
795
    } catch (Throwable t) {
×
796
      this.startContext.activateLogging();
×
797
      step.error(t, true);
×
798
      throw t;
×
799
    } finally {
800
      step.close();
2✔
801
      assert (this.currentStep == null);
4!
802
      step.logSummary(supressStepSuccess);
3✔
803
    }
804
  }
805

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

813
    IdeLogLevel previousLogLevel = null;
2✔
814
    cmd.reset();
2✔
815
    ValidationResult result = apply(arguments, cmd);
5✔
816
    if (result.isValid()) {
3!
817
      result = cmd.validate();
3✔
818
    }
819
    if (result.isValid()) {
3!
820
      debug("Running commandlet {}", cmd);
9✔
821
      if (cmd.isIdeHomeRequired() && (this.ideHome == null)) {
6!
822
        throw new CliException(getMessageIdeHomeNotFound(), ProcessResult.NO_IDE_HOME);
×
823
      } else if (cmd.isIdeRootRequired() && (this.ideRoot == null)) {
6!
824
        throw new CliException(getMessageIdeRootNotFound(), ProcessResult.NO_IDE_ROOT);
×
825
      }
826
      try {
827
        if (cmd.isProcessableOutput()) {
3!
828
          if (!debug().isEnabled()) {
×
829
            // unless --debug or --trace was supplied, processable output commandlets will disable all log-levels except INFO to prevent other logs interfere
830
            previousLogLevel = this.startContext.setLogLevel(IdeLogLevel.PROCESSABLE);
×
831
          }
832
          this.startContext.activateLogging();
×
833
        } else {
834
          this.startContext.activateLogging();
3✔
835
          verifyIdeRoot();
2✔
836
          if (cmd.isIdeHomeRequired()) {
3✔
837
            debug(getMessageIdeHomeFound());
4✔
838
          }
839
          if (this.settingsPath != null) {
3✔
840
            if (getGitContext().isRepositoryUpdateAvailable(this.settingsPath) ||
7!
841
                (getGitContext().fetchIfNeeded(this.settingsPath) && getGitContext().isRepositoryUpdateAvailable(this.settingsPath))) {
5!
842
              interaction("Updates are available for the settings repository. If you want to pull the latest changes, call ide update.");
×
843
            }
844
          }
845
        }
846
        cmd.run();
2✔
847
      } finally {
848
        if (previousLogLevel != null) {
2!
849
          this.startContext.setLogLevel(previousLogLevel);
×
850
        }
851
      }
1✔
852
    } else {
853
      trace("Commandlet did not match");
×
854
    }
855
    return result;
2✔
856
  }
857

858
  private void verifyIdeRoot() {
859
    if (!isTest()) {
3!
860
      if (this.ideRoot == null) {
×
861
        warning("Variable IDE_ROOT is undefined. Please check your installation or run setup script again.");
×
862
      } else if (this.ideHome != null) {
×
863
        Path ideRootPath = getIdeRootPathFromEnv();
×
864
        if (!this.ideRoot.equals(ideRootPath)) {
×
865
          warning("Variable IDE_ROOT is set to '{}' but for your project '{}' the path '{}' would have been expected.", ideRootPath,
×
866
              this.ideHome.getFileName(), this.ideRoot);
×
867
        }
868
      }
869
    }
870
  }
1✔
871

872
  /**
873
   * @param arguments the {@link CliArguments#ofCompletion(String...) completion arguments}.
874
   * @param includeContextOptions to include the options of {@link ContextCommandlet}.
875
   * @return the {@link List} of {@link CompletionCandidate}s to suggest.
876
   */
877
  public List<CompletionCandidate> complete(CliArguments arguments, boolean includeContextOptions) {
878
    CompletionCandidateCollector collector = new CompletionCandidateCollectorDefault(this);
5✔
879
    if (arguments.current().isStart()) {
4✔
880
      arguments.next();
3✔
881
    }
882
    if (includeContextOptions) {
2✔
883
      ContextCommandlet cc = new ContextCommandlet();
4✔
884
      for (Property<?> property : cc.getProperties()) {
11✔
885
        assert (property.isOption());
4!
886
        property.apply(arguments, this, cc, collector);
7✔
887
      }
1✔
888
    }
889
    Iterator<Commandlet> commandletIterator = this.commandletManager.findCommandlet(arguments, collector);
6✔
890
    CliArgument current = arguments.current();
3✔
891
    if (current.isCompletion() && current.isCombinedShortOption()) {
6✔
892
      collector.add(current.get(), null, null, null);
7✔
893
    }
894
    arguments.next();
3✔
895
    while (commandletIterator.hasNext()) {
3✔
896
      Commandlet cmd = commandletIterator.next();
4✔
897
      if (!arguments.current().isEnd()) {
4✔
898
        completeCommandlet(arguments.copy(), cmd, collector);
6✔
899
      }
900
    }
1✔
901
    return collector.getSortedCandidates();
3✔
902
  }
903

904
  private void completeCommandlet(CliArguments arguments, Commandlet cmd, CompletionCandidateCollector collector) {
905
    trace("Trying to match arguments for auto-completion for commandlet {}", cmd.getName());
10✔
906
    Iterator<Property<?>> valueIterator = cmd.getValues().iterator();
4✔
907
    valueIterator.next(); // skip first property since this is the keyword property that already matched to find the commandlet
3✔
908
    List<Property<?>> properties = cmd.getProperties();
3✔
909
    // we are creating our own list of options and remove them when matched to avoid duplicate suggestions
910
    List<Property<?>> optionProperties = new ArrayList<>(properties.size());
6✔
911
    for (Property<?> property : properties) {
10✔
912
      if (property.isOption()) {
3✔
913
        optionProperties.add(property);
4✔
914
      }
915
    }
1✔
916
    CliArgument currentArgument = arguments.current();
3✔
917
    while (!currentArgument.isEnd()) {
3✔
918
      trace("Trying to match argument '{}'", currentArgument);
9✔
919
      if (currentArgument.isOption() && !arguments.isEndOptions()) {
6!
920
        if (currentArgument.isCompletion()) {
3✔
921
          Iterator<Property<?>> optionIterator = optionProperties.iterator();
3✔
922
          while (optionIterator.hasNext()) {
3✔
923
            Property<?> option = optionIterator.next();
4✔
924
            boolean success = option.apply(arguments, this, cmd, collector);
7✔
925
            if (success) {
2✔
926
              optionIterator.remove();
2✔
927
              arguments.next();
3✔
928
            }
929
          }
1✔
930
        } else {
1✔
931
          Property<?> option = cmd.getOption(currentArgument.get());
5✔
932
          if (option != null) {
2✔
933
            arguments.next();
3✔
934
            boolean removed = optionProperties.remove(option);
4✔
935
            if (!removed) {
2!
936
              option = null;
×
937
            }
938
          }
939
          if (option == null) {
2✔
940
            trace("No such option was found.");
3✔
941
            return;
1✔
942
          }
943
        }
1✔
944
      } else {
945
        if (valueIterator.hasNext()) {
3✔
946
          Property<?> valueProperty = valueIterator.next();
4✔
947
          boolean success = valueProperty.apply(arguments, this, cmd, collector);
7✔
948
          if (!success) {
2!
949
            trace("Completion cannot match any further.");
×
950
            return;
×
951
          }
952
        } else {
1✔
953
          trace("No value left for completion.");
3✔
954
          return;
1✔
955
        }
956
      }
957
      currentArgument = arguments.current();
4✔
958
    }
959
  }
1✔
960

961

962
  /**
963
   * @param arguments the {@link CliArguments} to apply. Will be {@link CliArguments#next() consumed} as they are matched. Consider passing a
964
   *     {@link CliArguments#copy() copy} as needed.
965
   * @param cmd the potential {@link Commandlet} to match.
966
   * @return the {@link ValidationResult} telling if the {@link CliArguments} can be applied successfully or if validation errors ocurred.
967
   */
968
  public ValidationResult apply(CliArguments arguments, Commandlet cmd) {
969

970
    trace("Trying to match arguments to commandlet {}", cmd.getName());
10✔
971
    CliArgument currentArgument = arguments.current();
3✔
972
    Iterator<Property<?>> propertyIterator = cmd.getValues().iterator();
4✔
973
    Property<?> property = null;
2✔
974
    if (propertyIterator.hasNext()) {
3!
975
      property = propertyIterator.next();
4✔
976
    }
977
    while (!currentArgument.isEnd()) {
3✔
978
      trace("Trying to match argument '{}'", currentArgument);
9✔
979
      Property<?> currentProperty = property;
2✔
980
      if (!arguments.isEndOptions()) {
3!
981
        Property<?> option = cmd.getOption(currentArgument.getKey());
5✔
982
        if (option != null) {
2!
983
          currentProperty = option;
×
984
        }
985
      }
986
      if (currentProperty == null) {
2!
987
        trace("No option or next value found");
×
988
        ValidationState state = new ValidationState(null);
×
989
        state.addErrorMessage("No matching property found");
×
990
        return state;
×
991
      }
992
      trace("Next property candidate to match argument is {}", currentProperty);
9✔
993
      if (currentProperty == property) {
3!
994
        if (!property.isMultiValued()) {
3✔
995
          if (propertyIterator.hasNext()) {
3✔
996
            property = propertyIterator.next();
5✔
997
          } else {
998
            property = null;
2✔
999
          }
1000
        }
1001
        if ((property != null) && property.isValue() && property.isMultiValued()) {
8!
1002
          arguments.stopSplitShortOptions();
2✔
1003
        }
1004
      }
1005
      boolean matches = currentProperty.apply(arguments, this, cmd, null);
7✔
1006
      if (!matches && currentArgument.isCompletion()) {
2!
1007
        ValidationState state = new ValidationState(null);
×
1008
        state.addErrorMessage("No matching property found");
×
1009
        return state;
×
1010
      }
1011
      currentArgument = arguments.current();
3✔
1012
    }
1✔
1013
    return ValidationResultValid.get();
2✔
1014
  }
1015

1016
  @Override
1017
  public String findBash() {
1018

1019
    String bash = "bash";
2✔
1020
    if (SystemInfoImpl.INSTANCE.isWindows()) {
3!
1021
      bash = findBashOnWindows();
×
1022
    }
1023

1024
    return bash;
2✔
1025
  }
1026

1027
  private String findBashOnWindows() {
1028

1029
    // Check if Git Bash exists in the default location
1030
    Path defaultPath = Path.of("C:\\Program Files\\Git\\bin\\bash.exe");
×
1031
    if (Files.exists(defaultPath)) {
×
1032
      return defaultPath.toString();
×
1033
    }
1034

1035
    // If not found in the default location, try the registry query
1036
    String[] bashVariants = { "GitForWindows", "Cygwin\\setup" };
×
1037
    String[] registryKeys = { "HKEY_LOCAL_MACHINE", "HKEY_CURRENT_USER" };
×
1038
    String regQueryResult;
1039
    for (String bashVariant : bashVariants) {
×
1040
      for (String registryKey : registryKeys) {
×
1041
        String toolValueName = ("GitForWindows".equals(bashVariant)) ? "InstallPath" : "rootdir";
×
1042
        String command = "reg query " + registryKey + "\\Software\\" + bashVariant + "  /v " + toolValueName + " 2>nul";
×
1043

1044
        try {
1045
          Process process = new ProcessBuilder("cmd.exe", "/c", command).start();
×
1046
          try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
×
1047
            StringBuilder output = new StringBuilder();
×
1048
            String line;
1049

1050
            while ((line = reader.readLine()) != null) {
×
1051
              output.append(line);
×
1052
            }
1053

1054
            int exitCode = process.waitFor();
×
1055
            if (exitCode != 0) {
×
1056
              return null;
×
1057
            }
1058

1059
            regQueryResult = output.toString();
×
1060
            if (regQueryResult != null) {
×
1061
              int index = regQueryResult.indexOf("REG_SZ");
×
1062
              if (index != -1) {
×
1063
                String path = regQueryResult.substring(index + "REG_SZ".length()).trim();
×
1064
                return path + "\\bin\\bash.exe";
×
1065
              }
1066
            }
1067

1068
          }
×
1069
        } catch (Exception e) {
×
1070
          return null;
×
1071
        }
×
1072
      }
1073
    }
1074
    // no bash found
1075
    return null;
×
1076
  }
1077

1078
  @Override
1079
  public WindowsPathSyntax getPathSyntax() {
1080
    return this.pathSyntax;
3✔
1081
  }
1082

1083
  /**
1084
   * @param pathSyntax new value of {@link #getPathSyntax()}.
1085
   */
1086
  public void setPathSyntax(WindowsPathSyntax pathSyntax) {
1087

1088
    this.pathSyntax = pathSyntax;
3✔
1089
  }
1✔
1090

1091
  /**
1092
   * @return the {@link IdeStartContextImpl}.
1093
   */
1094
  public IdeStartContextImpl getStartContext() {
1095

1096
    return startContext;
3✔
1097
  }
1098

1099
  /**
1100
   * Reloads this context and re-initializes the {@link #getVariables() variables}.
1101
   */
1102
  public void reload() {
1103
    this.variables = null;
3✔
1104
  }
1✔
1105
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc