Skip to content

Commit fe9631f

Browse files
BornToBeRootclaude
andcommitted
Fix: Run command review findings
- Suggestions: exact command/alias first (e.g. "lookup" no longer opens DNS Lookup), exact profile name first in "@" mode, recent commands of a command before its profiles, the tool's target of a profile (e.g. RDP host) instead of the general host. - DNS servers: configured servers as suggestions, matched by name case-insensitively; values with spaces can be quoted ("Google Public DNS"). - DNS Lookup uses PTR for IP addresses from any request (run command, IP Scanner, Traceroute, profiles); shortened IPv4 forms like "10" are host names. - A failed suggestion (e.g. a recent command with an ambiguous profile name) is put into the input to correct it. - Syntax hints use resource strings; history entries are parsed once. - Docs: quotes, DNS servers, duplicate profile names, "@" only at the start of the target. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 8b515ae commit fe9631f

9 files changed

Lines changed: 258 additions & 72 deletions

File tree

‎Source/NETworkManager.Models/RunCommand/RunCommandParser.cs‎

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,20 @@ public static partial class RunCommandParser
1616
[GeneratedRegex(@"\s*;\s*")]
1717
private static partial Regex ListSeparatorRegex();
1818

19+
/// <summary>
20+
/// A word: a value in quotes (can contain spaces, the closing quote can be missing while typing) or a value
21+
/// without spaces.
22+
/// </summary>
23+
[GeneratedRegex("\"[^\"]*(?:\"|$)|[^\\s\"]+")]
24+
private static partial Regex WordRegex();
25+
1926
/// <summary>
2027
/// Parses the input.
2128
/// - Lists use ";" as everywhere in the application. Whitespace around ";" is removed, so whitespace only
2229
/// separates the arguments.
2330
/// - The first word is the command (name or alias), the second word the target. "@name" (the rest of the input,
2431
/// since profile names can contain spaces) is a profile instead of a target.
32+
/// - A value with spaces is written in quotes (e.g. a DNS server "Google Public DNS").
2533
/// - Further words are a type keyword of the command or its second argument (e.g. ports, DNS server), in any
2634
/// order.
2735
/// </summary>
@@ -32,8 +40,13 @@ public static RunCommandParseResult Parse(string input, IEnumerable<RunCommandDe
3240
{
3341
input = (input ?? string.Empty).TrimStart();
3442

35-
var endsWithWhitespace = input.Length > 0 && char.IsWhiteSpace(input[^1]);
36-
var words = ListSeparatorRegex().Replace(input, ";").Split((char[])null, StringSplitOptions.RemoveEmptyEntries);
43+
// Words as typed (with quotes, to rebuild the input) and their values (without quotes)
44+
var tokens = WordRegex().Matches(ListSeparatorRegex().Replace(input, ";")).Select(x => x.Value).ToArray();
45+
var words = tokens.Select(Unquote).ToArray();
46+
47+
// Whitespace in an open quote (e.g. "Google ) is part of the word that is being typed.
48+
var endsWithWhitespace = input.Length > 0 && char.IsWhiteSpace(input[^1]) &&
49+
!(tokens.Length > 0 && IsOpenQuote(tokens[^1]));
3750

3851
if (words.Length == 0)
3952
return new RunCommandParseResult { Position = RunCommandPosition.Command, Error = RunCommandParseError.Empty };
@@ -68,7 +81,7 @@ public static RunCommandParseResult Parse(string input, IEnumerable<RunCommandDe
6881
// Profile: the rest of the input after "@" is the name.
6982
if (words[1].StartsWith('@'))
7083
{
71-
var profileName = input[(input.IndexOf('@') + 1)..].Trim();
84+
var profileName = Unquote(input[(input.IndexOf('@') + 1)..].Trim());
7285

7386
var error = !command.SupportsProfile
7487
? RunCommandParseError.NoProfiles
@@ -139,9 +152,22 @@ public static RunCommandParseResult Parse(string input, IEnumerable<RunCommandDe
139152
Type = type,
140153
Position = isTypingTarget ? RunCommandPosition.Target : RunCommandPosition.Argument,
141154
CurrentWord = currentWord,
142-
InputBeforeCurrentWord = string.Join(" ", words[..^(currentWord.Length == 0 ? 0 : 1)]) + " ",
155+
InputBeforeCurrentWord = string.Join(" ", tokens[..^(endsWithWhitespace ? 0 : 1)]) + " ",
143156
Error = unknownArgument == null ? RunCommandParseError.None : RunCommandParseError.UnknownArgument,
144157
ErrorValue = unknownArgument
145158
};
146159
}
160+
161+
/// <summary>
162+
/// Removes the quotes of a value (e.g. "Google Public DNS").
163+
/// </summary>
164+
private static string Unquote(string word)
165+
{
166+
return word.StartsWith('"') ? word.Trim('"') : word;
167+
}
168+
169+
private static bool IsOpenQuote(string token)
170+
{
171+
return token.StartsWith('"') && (token.Length == 1 || !token.EndsWith('"'));
172+
}
147173
}

‎Source/NETworkManager.Tests/RunCommand/RunCommandParserTests.cs‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,11 @@ public class RunCommandParserTests
1414
Aliases = ["ping"], SupportsTarget = true, SupportsProfile = true
1515
},
1616
new()
17+
{
18+
Type = RunCommandType.Application, Application = ApplicationName.RemoteDesktop, Command = "remotedesktop",
19+
Aliases = ["rdp"], SupportsTarget = true, SupportsProfile = true
20+
},
21+
new()
1722
{
1823
Type = RunCommandType.Application, Application = ApplicationName.DNSLookup, Command = "dnslookup",
1924
Aliases = ["dns", "nslookup"], SupportsTarget = true, SupportsProfile = true,
@@ -121,6 +126,46 @@ public void DNSServerAndTypeInAnyOrder(string input)
121126
Assert.Equal(RunCommandParseError.None, result.Error);
122127
}
123128

129+
[Theory]
130+
[InlineData("dns borntoberoot.net \"Google Public DNS\" aaaa")]
131+
[InlineData("dns borntoberoot.net aaaa \"Google Public DNS\"")]
132+
public void QuotedArgument(string input)
133+
{
134+
var result = Parse(input);
135+
136+
Assert.Equal("Google Public DNS", result.Argument);
137+
Assert.Equal("aaaa", result.Type);
138+
Assert.Equal(RunCommandParseError.None, result.Error);
139+
}
140+
141+
[Fact]
142+
public void OpenQuoteIsTheWordThatIsBeingTyped()
143+
{
144+
// Whitespace in an open quote doesn't start a new word.
145+
var result = Parse("dns borntoberoot.net \"Google ");
146+
147+
Assert.Equal(RunCommandPosition.Argument, result.Position);
148+
Assert.Equal("Google ", result.CurrentWord);
149+
Assert.Equal("dns borntoberoot.net ", result.InputBeforeCurrentWord);
150+
}
151+
152+
[Fact]
153+
public void CompletionKeepsQuotes()
154+
{
155+
var result = Parse("dns borntoberoot.net \"Google Public DNS\" aa");
156+
157+
Assert.Equal("aa", result.CurrentWord);
158+
Assert.Equal("dns borntoberoot.net \"Google Public DNS\" ", result.InputBeforeCurrentWord);
159+
}
160+
161+
[Fact]
162+
public void QuotedProfileName()
163+
{
164+
var result = Parse("rdp @\"Web Server 01\"");
165+
166+
Assert.Equal("Web Server 01", result.ProfileName);
167+
}
168+
124169
[Fact]
125170
public void HostsAndType()
126171
{

‎Source/NETworkManager/RunCommandManager.cs‎

Lines changed: 38 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
using System.Collections.Generic;
1313
using System.Globalization;
1414
using System.Linq;
15-
using System.Net;
1615
using System.Windows.Controls;
1716

1817
namespace NETworkManager;
@@ -35,8 +34,6 @@ public static class RunCommandManager
3534
["entity"] = RDAPQueryType.Entity
3635
};
3736

38-
private static readonly IReadOnlyList<RunCommandDefinition> Commands = CreateCommands();
39-
4037
/// <summary>
4138
/// Gets the commands of the visible applications and the settings.
4239
/// </summary>
@@ -46,7 +43,17 @@ public static IReadOnlyList<RunCommandDefinition> GetCommands()
4643
var visibleApplications = SettingsManager.Current.General_ApplicationList.Where(x => x.IsVisible)
4744
.Select(x => x.Name).ToHashSet();
4845

49-
return [.. Commands.Where(x => x.Type == RunCommandType.Setting || visibleApplications.Contains(x.Application))];
46+
// Created on each call, since the syntax is translated.
47+
return [.. CreateCommands().Where(x => x.Type == RunCommandType.Setting || visibleApplications.Contains(x.Application))];
48+
}
49+
50+
/// <summary>
51+
/// Gets the names of the DNS servers configured in the DNS lookup (e.g. "Cloudflare").
52+
/// </summary>
53+
/// <returns>Names of the DNS servers.</returns>
54+
public static IEnumerable<string> GetDNSServers()
55+
{
56+
return SettingsManager.Current.DNSLookup_DNSServers.Select(x => x.Name);
5057
}
5158

5259
/// <summary>
@@ -217,13 +224,11 @@ private static ApplicationRequest CreateRequest(RunCommandParseResult result)
217224
ApplicationName.DNSLookup => new DNSLookupRequest
218225
{
219226
Target = result.Target,
220-
DNSServer = result.Argument,
221-
QueryType = result.Type != null
222-
? Enum.Parse<QueryType>(result.Type, true)
223-
// Only IP addresses: reverse lookup
224-
: result.Target.Split(';').All(x => IPAddress.TryParse(x, out _))
225-
? QueryType.PTR
226-
: null
227+
// A configured DNS server is matched by its name (case-insensitive), otherwise it's a custom server.
228+
DNSServer = GetDNSServers().FirstOrDefault(x =>
229+
string.Equals(x, result.Argument, StringComparison.OrdinalIgnoreCase)) ?? result.Argument,
230+
// Without a type, the DNS lookup uses PTR for IP addresses and its selected type for hosts.
231+
QueryType = result.Type != null ? Enum.Parse<QueryType>(result.Type, true) : null
227232
},
228233
ApplicationName.PortScanner => new PortScannerRequest { Target = result.Target, Ports = result.Argument },
229234
ApplicationName.RDAP => new RDAPRequest { Target = result.Target, QueryType = GetRDAPQueryType(result.Type) },
@@ -242,24 +247,31 @@ private static RDAPQueryType GetRDAPQueryType(string type)
242247
/// </summary>
243248
private static List<RunCommandDefinition> CreateCommands()
244249
{
250+
// Syntax of the arguments, e.g. "<Hosts> [Ports]"
251+
static string Required(string name) => $"<{name}>";
252+
static string Optional(string name) => $"[{name}]";
253+
245254
var commands = ApplicationManager.GetNames().Where(x => x != ApplicationName.None).Select(name => name switch
246255
{
247-
ApplicationName.IPScanner => Create(name, ["scan"], "<range>", true),
248-
ApplicationName.PortScanner => Create(name, ["portscan"], "<hosts> [ports]", true,
249-
RunCommandArgument.Ports),
250-
ApplicationName.PingMonitor => Create(name, ["ping"], "<hosts>", true),
251-
ApplicationName.Traceroute => Create(name, ["trace", "tracert"], "<host>", true),
252-
ApplicationName.DNSLookup => Create(name, ["dns", "nslookup"], "<hosts> [server] [type]", true,
256+
ApplicationName.IPScanner => Create(name, ["scan"], Required(Strings.IPRange), true),
257+
ApplicationName.PortScanner => Create(name, ["portscan"],
258+
$"{Required(Strings.Hosts)} {Optional(Strings.Ports)}", true, RunCommandArgument.Ports),
259+
ApplicationName.PingMonitor => Create(name, ["ping"], Required(Strings.Hosts), true),
260+
ApplicationName.Traceroute => Create(name, ["trace", "tracert"], Required(Strings.Host), true),
261+
ApplicationName.DNSLookup => Create(name, ["dns", "nslookup"],
262+
$"{Required(Strings.Hosts)} {Optional(Strings.DNSServer)} {Optional(Strings.Type)}", true,
253263
RunCommandArgument.DNSServer,
254264
[.. DNSLookup.QueryTypes.Select(x => x.ToString().ToLowerInvariant()).Order()]),
255-
ApplicationName.RemoteDesktop => Create(name, ["rdp", "mstsc"], "<host[:port]>", true),
256-
ApplicationName.PowerShell => Create(name, ["ps", "pwsh"], "<host>", true),
257-
ApplicationName.PuTTY => Create(name, ["ssh"], "<host>", true),
258-
ApplicationName.TigerVNC => Create(name, ["vnc"], "<host>", true),
259-
ApplicationName.WebConsole => Create(name, ["web"], "<url>", true),
260-
ApplicationName.SNMP => Create(name, [], "<host>", true),
261-
ApplicationName.RDAP => Create(name, [], "<query> [type]", true, types: [.. RDAPTypes.Keys]),
262-
ApplicationName.Whois => Create(name, [], "<domain>", true),
265+
ApplicationName.RemoteDesktop => Create(name, ["rdp", "mstsc"],
266+
$"{Required(Strings.Host)}[:{Required(Strings.Port)}]", true),
267+
ApplicationName.PowerShell => Create(name, ["ps", "pwsh"], Required(Strings.Host), true),
268+
ApplicationName.PuTTY => Create(name, ["ssh"], Required(Strings.Host), true),
269+
ApplicationName.TigerVNC => Create(name, ["vnc"], Required(Strings.Host), true),
270+
ApplicationName.WebConsole => Create(name, ["web"], Required(Strings.URL), true),
271+
ApplicationName.SNMP => Create(name, [], Required(Strings.Host), true),
272+
ApplicationName.RDAP => Create(name, [], $"{Required(Strings.Query)} {Optional(Strings.Type)}", true,
273+
types: [.. RDAPTypes.Keys]),
274+
ApplicationName.Whois => Create(name, [], Required(Strings.Domain), true),
263275
_ => Create(name, [], string.Empty, false)
264276
}).ToList();
265277

@@ -287,7 +299,7 @@ private static RunCommandDefinition Create(ApplicationName application, string[]
287299
SupportsProfile = supportsTarget,
288300
Argument = argument,
289301
Types = types ?? [],
290-
Syntax = supportsTarget ? $"{syntax} | @<profile>" : string.Empty
302+
Syntax = supportsTarget ? $"{syntax} | @<{Strings.Profile}>" : string.Empty
291303
};
292304
}
293305
}

‎Source/NETworkManager/RunCommandSuggestion.cs‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,12 @@ public enum RunCommandSuggestionKind
3131
/// <summary>
3232
/// Type keyword of the command (e.g. DNS record type).
3333
/// </summary>
34-
Type
34+
Type,
35+
36+
/// <summary>
37+
/// DNS server configured in the DNS lookup.
38+
/// </summary>
39+
DNSServer
3540
}
3641

3742
/// <summary>

‎Source/NETworkManager/ViewModels/DNSLookupHostViewModel.cs‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@
99
using System;
1010
using System.Collections.Generic;
1111
using System.Collections.ObjectModel;
12+
using System.Linq;
13+
using System.Net;
14+
using System.Net.Sockets;
1215
using System.Windows.Input;
1316

1417
namespace NETworkManager.ViewModels;
@@ -150,9 +153,15 @@ private static void CloseItemAction(ItemActionCallbackArgs<TabablzControl> args)
150153
/// </summary>
151154
/// <param name="host">The host to lookup.</param>
152155
/// <param name="dnsServer">DNS server(s) to use. If null, the selected DNS server is used.</param>
153-
/// <param name="queryType">Query type. If null, the selected query type is used.</param>
156+
/// <param name="queryType">
157+
/// Query type. If null, PTR is used for IP addresses (e.g. from the IP Scanner) and the selected query type for
158+
/// hosts.
159+
/// </param>
154160
public void AddTab(string host = null, string dnsServer = null, QueryType? queryType = null)
155161
{
162+
if (queryType == null && IsIPAddresses(host))
163+
queryType = QueryType.PTR;
164+
156165
var tabId = Guid.NewGuid();
157166

158167
TabItems.Add(new DragablzTabItem(host ?? Strings.NewTab, new DNSLookupView(tabId, host, dnsServer, queryType),
@@ -161,6 +170,17 @@ public void AddTab(string host = null, string dnsServer = null, QueryType? query
161170
SelectedTabIndex = TabItems.Count - 1;
162171
}
163172

173+
/// <summary>
174+
/// Checks if the host(s) are only IP addresses (shortened IPv4 forms like "10" are host names).
175+
/// </summary>
176+
private static bool IsIPAddresses(string hosts)
177+
{
178+
return !string.IsNullOrWhiteSpace(hosts) && hosts.Split(';').Select(x => x.Trim()).All(x =>
179+
RegexHelper.IPv4AddressRegex().IsMatch(x) ||
180+
x.Contains(':') && IPAddress.TryParse(x, out var ipAddress) &&
181+
ipAddress.AddressFamily == AddressFamily.InterNetworkV6);
182+
}
183+
164184
/// <summary>
165185
/// Adds a new tab for the host of the specified profile.
166186
/// </summary>

0 commit comments

Comments
 (0)