forked from JamesDunne/aardwolf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConfigurationDictionary.cs
executable file
·92 lines (78 loc) · 3.03 KB
/
ConfigurationDictionary.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Aardwolf
{
public sealed class ConfigurationDictionary
{
readonly Dictionary<string, List<string>> _values;
public ConfigurationDictionary(Dictionary<string, List<string>> values)
{
_values = values;
}
public static ConfigurationDictionary Parse(IEnumerable<string> args)
{
var values = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
foreach (var arg in args)
{
// Split at first '=':
int eqidx;
if ((eqidx = arg.IndexOf('=')) == -1) continue;
string key, value;
key = arg.Substring(0, eqidx);
value = arg.Substring(eqidx + 1);
// Create the list of values for the key if necessary:
List<string> list;
if (!values.TryGetValue(key, out list))
{
list = new List<string>();
values.Add(key, list);
}
// Add the value to the list:
list.Add(value);
}
return new ConfigurationDictionary(values);
}
public string SingleValue(string key)
{
List<string> list;
if (!_values.TryGetValue(key, out list) || list.Count == 0)
throw new Exception(String.Format("Configuration key '{0}' is required", key));
if (list.Count > 1)
throw new Exception(String.Format("Configuration key '{0}' has more than one value", key));
return list[0];
}
public string SingleValueOrDefault(string key, string defaultValue)
{
List<string> list;
if (!_values.TryGetValue(key, out list) || list.Count == 0)
return defaultValue;
if (list.Count > 1)
throw new Exception(String.Format("Configuration key '{0}' has more than one value", key));
return list[0];
}
public List<string> Values(string key)
{
List<string> list;
if (!_values.TryGetValue(key, out list))
throw new Exception(String.Format("Configuration key '{0}' is required", key));
return list;
}
public bool TryGetValue(string key, out List<string> values)
{
return _values.TryGetValue(key, out values);
}
public bool TryGetSingleValue(string key, out string value)
{
value = null;
List<string> list;
if (!_values.TryGetValue(key, out list)) return false;
if (list.Count > 1)
throw new Exception(String.Format("Configuration key '{0}' has more than one value", key));
value = list[0];
return true;
}
}
}