Skip to content

Commit b5a9f93

Browse files
authored
Merge pull request #23 from nils-a/feature/GH-11
(#11) added different outputs after switch command
2 parents bfbda65 + 2a32d6c commit b5a9f93

File tree

7 files changed

+135
-5
lines changed

7 files changed

+135
-5
lines changed

.github/workflows/build.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ jobs:
2222
os: [ windows-2019 ]
2323

2424
env:
25-
#COVERALLS_REPO_TOKEN: ${{ secrets.COVERALLS_REPO_TOKEN }}
25+
COVERALLS_REPO_TOKEN: ${{ secrets.COVERALLS_REPO_TOKEN }}
2626
GITHUB_PAT: ${{ secrets.GH_TOKEN }}
2727
GPR_PASSWORD: ${{ secrets.GPR_PASSWORD }}
2828
GPR_USER: ${{ secrets.GPR_USER }}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
namespace JavaVersionSwitcher.Adapters
2+
{
3+
public interface IShellAdapter
4+
{
5+
ShellType GetShellType();
6+
}
7+
}
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
using System;
2+
using System.Diagnostics;
3+
using JavaVersionSwitcher.Logging;
4+
5+
namespace JavaVersionSwitcher.Adapters
6+
{
7+
// some of this was inspired by https://stackoverflow.com/a/2336322/180156
8+
public class ShellAdapter : IShellAdapter
9+
{
10+
private readonly ILogger _logger;
11+
12+
public ShellAdapter(ILogger logger)
13+
{
14+
_logger = logger;
15+
}
16+
17+
public ShellType GetShellType()
18+
{
19+
try
20+
{
21+
var proc = GetParentProcess(Process.GetCurrentProcess());
22+
// when calling "dotnet jvs" the parent is "dotnet" - not sure if that's the case for dotnet-jvs.exe
23+
if ("dotnet".Equals(proc.ProcessName, StringComparison.OrdinalIgnoreCase))
24+
{
25+
proc = GetParentProcess(proc);
26+
}
27+
28+
_logger.LogVerbose("Parent process name is: " + proc.ProcessName);
29+
var name = proc.ProcessName.ToLowerInvariant();
30+
switch (name)
31+
{
32+
case "pwsh":
33+
case "powershell":
34+
return ShellType.PowerShell;
35+
case "cmd":
36+
return ShellType.CommandPrompt;
37+
default:
38+
return ShellType.Unknown;
39+
}
40+
}
41+
catch(Exception e)
42+
{
43+
_logger.LogVerbose($"{e.GetType().Name} while finding parent process: {e.Message}");
44+
return ShellType.Unknown;
45+
}
46+
}
47+
48+
private static Process GetParentProcess(Process process) {
49+
return FindPidFromIndexedProcessName(FindIndexedProcessName(process.Id));
50+
}
51+
52+
private static string FindIndexedProcessName(int pid) {
53+
var processName = Process.GetProcessById(pid).ProcessName;
54+
var processesByName = Process.GetProcessesByName(processName);
55+
string processIndexedName = null;
56+
57+
for (var index = 0; index < processesByName.Length; index++) {
58+
processIndexedName = index == 0 ? processName : processName + "#" + index;
59+
var processId = new PerformanceCounter("Process", "ID Process", processIndexedName);
60+
if ((int) processId.NextValue() == pid) {
61+
return processIndexedName;
62+
}
63+
}
64+
65+
return processIndexedName;
66+
}
67+
68+
private static Process FindPidFromIndexedProcessName(string indexedProcessName) {
69+
var parentId = new PerformanceCounter("Process", "Creating Process ID", indexedProcessName);
70+
return Process.GetProcessById((int) parentId.NextValue());
71+
}
72+
}
73+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
namespace JavaVersionSwitcher.Adapters
2+
{
3+
public enum ShellType
4+
{
5+
/// <summary>
6+
/// Unknown
7+
/// </summary>
8+
Unknown,
9+
10+
/// <summary>
11+
/// PowerShell
12+
/// </summary>
13+
PowerShell,
14+
15+
/// <summary>
16+
/// CMD
17+
/// </summary>
18+
CommandPrompt,
19+
}
20+
}

src/JavaVersionSwitcher/Commands/SwitchVersionCommand.cs

Lines changed: 32 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System;
2+
using System.Collections.Generic;
23
using System.ComponentModel;
34
using System.IO;
45
using System.Linq;
@@ -18,18 +19,21 @@ internal sealed class SwitchVersionCommand : AsyncCommand<SwitchVersionCommand.S
1819
private readonly IJavaInstallationsAdapter _javaInstallationsAdapter;
1920
private readonly IPathAdapter _pathAdapter;
2021
private readonly ILogger _logger;
22+
private readonly IShellAdapter _shellAdapter;
2123

2224
public SwitchVersionCommand(
2325
IJavaHomeAdapter javaHomeAdapter,
2426
IJavaInstallationsAdapter javaInstallationsAdapter,
2527
IPathAdapter pathAdapter,
26-
ILogger logger
28+
ILogger logger,
29+
IShellAdapter shellAdapter
2730
)
2831
{
2932
_javaHomeAdapter = javaHomeAdapter;
3033
_javaInstallationsAdapter = javaInstallationsAdapter;
3134
_pathAdapter = pathAdapter;
3235
_logger = logger;
36+
_shellAdapter = shellAdapter;
3337
}
3438

3539
[UsedImplicitly]
@@ -56,6 +60,8 @@ public override async Task<int> ExecuteAsync(CommandContext context, Settings se
5660
.AddChoices(installations.Select(x => x.Location).ToArray())
5761
);
5862

63+
string javaHome = null;
64+
string javaBin = null;
5965
await AnsiConsole.Status()
6066
.StartAsync("Applying...", async ctx =>
6167
{
@@ -66,20 +72,42 @@ await AnsiConsole.Status()
6672
? EnvironmentScope.Machine
6773
: EnvironmentScope.User;
6874

69-
var javaHome = await _javaHomeAdapter.GetValue(EnvironmentScope.Process);
75+
javaHome = await _javaHomeAdapter.GetValue(EnvironmentScope.Process);
7076
var paths = (await _pathAdapter.GetValue(scope)).ToList();
7177
if (!string.IsNullOrEmpty(javaHome))
7278
{
7379
paths = paths.Where(x => !x.StartsWith(javaHome,StringComparison.OrdinalIgnoreCase)).ToList();
7480
}
7581

76-
paths.Add(Path.Combine(selected, "bin"));
82+
javaBin = Path.Combine(selected, "bin");
83+
paths.Add(javaBin);
7784

7885
await _javaHomeAdapter.SetValue(selected, scope);
7986
await _pathAdapter.SetValue(paths, scope);
8087
}).ConfigureAwait(false);
8188

82-
AnsiConsole.MarkupLine("[yellow]The environment has been modified. You need to refresh it.[/]");
89+
var shellType = _shellAdapter.GetShellType();
90+
var refreshCommands = new List<string>();
91+
switch (shellType)
92+
{
93+
case ShellType.PowerShell:
94+
refreshCommands.Add($"$env:JAVA_HOME=\"{javaHome}\"");
95+
refreshCommands.Add($"$env:PATH=\"{javaBin}{Path.PathSeparator}$($env:PATH)\"");
96+
break;
97+
case ShellType.CommandPrompt:
98+
refreshCommands.Add($"set \"JAVA_HOME={javaHome}\"");
99+
refreshCommands.Add($"set \"PATH={javaBin}{Path.PathSeparator}%PATH%\"");
100+
break;
101+
}
102+
103+
AnsiConsole.MarkupLine(refreshCommands.Count > 0
104+
? "[yellow]The environment has been modified. Apply modifications:[/]"
105+
: "[yellow]The environment has been modified. You need to refresh it.[/]");
106+
107+
foreach (var line in refreshCommands)
108+
{
109+
Console.WriteLine(line);
110+
}
83111
return 0;
84112
}
85113
}

src/JavaVersionSwitcher/JavaVersionSwitcher.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
<PackageReference Include="JetBrains.Annotations" Version="2021.1.0" />
4040
<PackageReference Include="SimpleInjector" Version="5.3.1" />
4141
<PackageReference Include="Spectre.Console" Version="0.40.0" />
42+
<PackageReference Include="System.Diagnostics.PerformanceCounter" Version="5.0.0" />
4243
</ItemGroup>
4344

4445
</Project>

src/JavaVersionSwitcher/Program.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ private static ITypeRegistrar BuildRegistrar()
6161
container.Register<IPathAdapter, PathAdapter>(Lifestyle.Singleton);
6262
container.Register<IJavaInstallationsAdapter, JavaInstallationsAdapter>(Lifestyle.Singleton);
6363
container.Register<JavaInstallationsAdapterConfigurationProvider>(Lifestyle.Singleton);
64+
container.Register<IShellAdapter, ShellAdapter>(Lifestyle.Singleton);
6465

6566
container.Collection.Register<IConfigurationProvider>(
6667
new[]

0 commit comments

Comments
 (0)