-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathCommandLineOptions.cs
More file actions
85 lines (73 loc) · 2.7 KB
/
Copy pathCommandLineOptions.cs
File metadata and controls
85 lines (73 loc) · 2.7 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
82
83
84
85
namespace Opcilloscope;
internal sealed record CommandLineOptions(
string? ConfigPath,
string? AutoConnectUrl,
bool AllowInsecureCertificates,
bool ShowHelp);
internal static class CommandLineParser
{
public static CommandLineOptions Parse(IReadOnlyList<string> args)
{
// Help is an immediate, side-effect-free request. Keep it usable even
// when a shell alias appends stale/invalid arguments after --help.
if (args.Any(arg => arg is "--help" or "-h"))
{
return new CommandLineOptions(null, null, false, ShowHelp: true);
}
string? configPath = null;
string? autoConnectUrl = null;
var allowInsecure = false;
for (var i = 0; i < args.Count; i++)
{
var arg = args[i];
switch (arg)
{
case "--config":
case "-f":
configPath = ReadOptionValue(args, ref i, arg);
break;
case "--connect":
case "-c":
autoConnectUrl = ReadOptionValue(args, ref i, arg);
break;
case "--insecure":
allowInsecure = true;
break;
default:
if (arg.StartsWith('-'))
{
throw new ArgumentException($"Unknown option: {arg}");
}
if (arg.StartsWith("opc.tcp://", StringComparison.OrdinalIgnoreCase))
{
autoConnectUrl = arg;
}
else if (HasConfigExtension(arg))
{
configPath = arg;
}
else
{
throw new ArgumentException($"Unexpected argument: {arg}");
}
break;
}
}
return new CommandLineOptions(configPath, autoConnectUrl, allowInsecure, ShowHelp: false);
}
private static string ReadOptionValue(IReadOnlyList<string> args, ref int index, string option)
{
if (index + 1 >= args.Count
|| string.IsNullOrWhiteSpace(args[index + 1])
|| args[index + 1].StartsWith('-'))
{
throw new ArgumentException($"Option {option} requires a value.");
}
index++;
return args[index];
}
private static bool HasConfigExtension(string path) =>
path.EndsWith(".cfg", StringComparison.OrdinalIgnoreCase)
|| path.EndsWith(".opcilloscope", StringComparison.OrdinalIgnoreCase)
|| path.EndsWith(".json", StringComparison.OrdinalIgnoreCase);
}