This repository has been archived by the owner on Jan 18, 2022. It is now read-only.
/
CommandLineUtility.cs
99 lines (86 loc) · 2.84 KB
/
CommandLineUtility.cs
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
using System;
using System.Collections.Generic;
namespace Improbable.Gdk.Core
{
public class CommandLineArgs
{
private Dictionary<string, string> arguments;
// Hide default constructor
private CommandLineArgs()
{
}
public static CommandLineArgs FromCommandLine()
{
return From(Environment.GetCommandLineArgs());
}
public static CommandLineArgs From(Dictionary<string, string> args)
{
return new CommandLineArgs
{
arguments = args
};
}
public static CommandLineArgs From(IList<string> args)
{
return new CommandLineArgs
{
arguments = ParseCommandLineArgs(args)
};
}
public bool Contains(string key)
{
return arguments.ContainsKey(key);
}
public T GetCommandLineValue<T>(string key, T defaultValue)
{
T value = defaultValue;
TryGetCommandLineValue(key, ref value);
return value;
}
public bool TryGetCommandLineValue<T>(string key, ref T value)
{
var desiredType = typeof(T);
if (arguments.TryGetValue(key, out var strValue))
{
if (desiredType.IsEnum)
{
try
{
value = (T) Enum.Parse(desiredType, strValue);
return true;
}
catch (Exception e)
{
throw new FormatException($"Unable to parse argument {strValue} as enum {desiredType.Name}.",
e);
}
}
value = (T) Convert.ChangeType(strValue, typeof(T));
return true;
}
return false;
}
private static Dictionary<string, string> ParseCommandLineArgs(IList<string> args)
{
var config = new Dictionary<string, string>();
for (var i = 0; i < args.Count; i++)
{
var flag = args[i];
if (flag.StartsWith("+") || flag.StartsWith("-"))
{
if (i + 1 >= args.Count)
{
throw new ArgumentException(
$"Flag \"{flag}\" requires an argument\nArguments: \"{string.Join(", ", args)}\"");
}
var flagArg = args[i + 1];
var strippedOfPlus = flag.Substring(1, flag.Length - 1);
config[strippedOfPlus] = flagArg;
// We've already processed the next argument, so skip it.
i++;
}
}
return config;
}
}
}