Refactor SshHosts for immutability and improve retrieval methods
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
// Required namespaces:
|
||||
// System, System.IO, System.Linq, System.Text, System.Text.RegularExpressions, System.Collections.Generic, Renci.SshNet
|
||||
|
||||
using System.Collections.Immutable;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
@@ -21,10 +23,11 @@ public record Host(
|
||||
);
|
||||
|
||||
public static class SshHosts {
|
||||
public static List<Host> Hosts { get; set; }
|
||||
|
||||
private static ImmutableDictionary<string, Host> hosts;
|
||||
public static IReadOnlyDictionary<string, Host> Hosts => hosts;
|
||||
|
||||
static SshHosts() {
|
||||
Hosts = new List<Host>();
|
||||
var hosts = new Dictionary<string, Host>();
|
||||
|
||||
var path = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
|
||||
@@ -124,7 +127,7 @@ public static class SshHosts {
|
||||
foreach (var f in currentIdentityFiles) idFiles.Add(ExpandPath(f));
|
||||
}
|
||||
|
||||
Hosts.Add(new Host(
|
||||
hosts.Add(n, new Host(
|
||||
Name: n,
|
||||
Hostname: hn,
|
||||
User: currentUser ?? string.Empty,
|
||||
@@ -233,6 +236,7 @@ public static class SshHosts {
|
||||
}
|
||||
|
||||
Flush();
|
||||
SshHosts.hosts = hosts.ToImmutableDictionary();
|
||||
}
|
||||
|
||||
// Builds a ConnectionInfo from a parsed host, ensuring all ~/.ssh private keys are tried.
|
||||
@@ -345,23 +349,11 @@ public static class SshHosts {
|
||||
|
||||
|
||||
public static Host Get(string name) {
|
||||
for (int i = 0; i < Hosts.Count; i++) {
|
||||
if (string.Equals(Hosts[i].Name, name, StringComparison.OrdinalIgnoreCase)) {
|
||||
return Hosts[i];
|
||||
}
|
||||
}
|
||||
throw new KeyNotFoundException($"SSH host '{name}' not found.");
|
||||
return TryGetHost(name, out var h) ? h : throw new KeyNotFoundException($"SSH host '{name}' not found.");
|
||||
}
|
||||
|
||||
public static bool TryGetHost(string name, out Host host) {
|
||||
for (int i = 0; i < Hosts.Count; i++) {
|
||||
if (string.Equals(Hosts[i].Name, name, StringComparison.OrdinalIgnoreCase)) {
|
||||
host = Hosts[i];
|
||||
return true;
|
||||
}
|
||||
}
|
||||
host = default!;
|
||||
return false;
|
||||
public static bool TryGetHost(string name, [NotNullWhen(true)] out Host? host) {
|
||||
return Hosts.TryGetValue(name, out host);
|
||||
}
|
||||
|
||||
public static Renci.SshNet.ConnectionInfo GetConnection(string name)
|
||||
|
||||
Reference in New Issue
Block a user