Skip to content

Commit afe938c

Browse files
committed
wsl: add ability to detect WSL distro and version
Add methods to the WslUtils class to enable detection of a WSL distribution, and also determine which WSL version is being used. Version 1 uses the Windows NT kernel and runs the distribution in the same user-mode space as Windows programs. Version 2 uses a light-weight VM to host a real Linux kernel, and runs the distribution also inside the VM; interop with Windows is achieved using other mechanisms.
1 parent f256672 commit afe938c

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

src/shared/Core/WslUtils.cs

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
using System;
2+
using System.Collections.Generic;
23
using System.Diagnostics;
34
using System.IO;
45
using System.Text;
6+
using System.Text.RegularExpressions;
57

68
namespace GitCredentialManager
79
{
@@ -10,6 +12,60 @@ public static class WslUtils
1012
private const string WslUncPrefix = @"\\wsl$\";
1113
private const string WslLocalHostUncPrefix = @"\\wsl.localhost\";
1214
private const string WslCommandName = "wsl.exe";
15+
private const string WslInteropEnvar = "WSL_INTEROP";
16+
17+
/// <summary>
18+
/// Cached WSL version.
19+
/// </summary>
20+
/// <remarks>A value of 0 represents "not WSL", and a value less than 0 represents "unknown".</remarks>
21+
private static int _wslVersion = -1;
22+
23+
public static bool IsWslDistribution(IEnvironment env, IFileSystem fs, out int wslVersion)
24+
{
25+
if (_wslVersion < 0)
26+
{
27+
_wslVersion = GetWslVersion(env, fs);
28+
}
29+
30+
wslVersion = _wslVersion;
31+
return _wslVersion > 0;
32+
}
33+
34+
private static int GetWslVersion(IEnvironment env, IFileSystem fs)
35+
{
36+
// All WSL distributions are Linux.. obviously!
37+
if (!PlatformUtils.IsLinux())
38+
{
39+
return 0;
40+
}
41+
42+
// The WSL_INTEROP variable is set in WSL2 distributions
43+
if (env.Variables.TryGetValue(WslInteropEnvar, out _))
44+
{
45+
return 2;
46+
}
47+
48+
const string procVersionPath = "/proc/version";
49+
if (fs.FileExists(procVersionPath))
50+
{
51+
// Both WSL1 and WSL2 distributions include "[Mm]icrosoft" in the version string
52+
string procVersion = fs.ReadAllText(procVersionPath);
53+
if (!Regex.IsMatch(procVersion, "[Mm]icrosoft"))
54+
{
55+
return 0;
56+
}
57+
58+
// WSL2 distributions return "WSL2" in the version string
59+
if (Regex.IsMatch(procVersion, "wsl2", RegexOptions.IgnoreCase))
60+
{
61+
return 2;
62+
}
63+
64+
return 1;
65+
}
66+
67+
return 0;
68+
}
1369

1470
/// <summary>
1571
/// Test if a file path points to a location in a Windows Subsystem for Linux distribution.

0 commit comments

Comments
 (0)