-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathToolPathResolver.cs
More file actions
81 lines (67 loc) · 2.54 KB
/
Copy pathToolPathResolver.cs
File metadata and controls
81 lines (67 loc) · 2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
using System.IO;
namespace SimpleMusicPlayer;
internal static class ToolPathResolver
{
public static string? ResolveExecutablePath(string toolName)
=> ResolveTool(toolName).ExecutablePath;
public static ToolResolution ResolveTool(string toolName)
{
var searchedPaths = new List<string>();
foreach (var candidate in EnumerateLocalToolPaths(toolName, ToolResolutionSource.Bundled)
.Concat(EnumeratePathToolPaths(toolName)))
{
searchedPaths.Add(candidate.Path);
if (File.Exists(candidate.Path))
{
return new ToolResolution(toolName, candidate.Path, candidate.Source, searchedPaths);
}
}
return new ToolResolution(toolName, null, ToolResolutionSource.NotFound, searchedPaths);
}
private static IEnumerable<ToolCandidate> EnumerateLocalToolPaths(string toolName, ToolResolutionSource source)
{
foreach (var executableName in EnumerateExecutableNames(toolName))
{
yield return new ToolCandidate(Path.Combine(AppContext.BaseDirectory, "tools", toolName, executableName), source);
yield return new ToolCandidate(Path.Combine(AppContext.BaseDirectory, "tools", executableName), source);
}
}
private static IEnumerable<ToolCandidate> EnumeratePathToolPaths(string toolName)
{
var pathValue = Environment.GetEnvironmentVariable("PATH");
if (string.IsNullOrWhiteSpace(pathValue))
{
yield break;
}
foreach (var directory in pathValue.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
foreach (var executableName in EnumerateExecutableNames(toolName))
{
yield return new ToolCandidate(Path.Combine(directory, executableName), ToolResolutionSource.Path);
}
}
}
private static IEnumerable<string> EnumerateExecutableNames(string toolName)
{
yield return toolName;
if (!OperatingSystem.IsWindows())
{
yield break;
}
yield return $"{toolName}.exe";
yield return $"{toolName}.cmd";
yield return $"{toolName}.bat";
}
private sealed record ToolCandidate(string Path, ToolResolutionSource Source);
}
internal sealed record ToolResolution(
string ToolName,
string? ExecutablePath,
ToolResolutionSource Source,
IReadOnlyList<string> SearchedPaths);
internal enum ToolResolutionSource
{
NotFound,
Bundled,
Path
}