-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathInputArguments.cs
134 lines (116 loc) · 4.04 KB
/
InputArguments.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ArgumentParser
{
public class InputArguments
{
#region fields & properties
public const string DEFAULT_KEY_LEADING_PATTERN = "-";
protected Dictionary<string, string> _parsedArguments = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
protected readonly string _keyLeadingPattern;
public string this[string key]
{
get { return GetValue(key); }
set
{
if (key != null)
_parsedArguments[key] = value;
}
}
public string KeyLeadingPattern
{
get { return _keyLeadingPattern; }
}
#endregion
#region public methods
public InputArguments(string[] args, string keyLeadingPattern)
{
_keyLeadingPattern = !string.IsNullOrEmpty(keyLeadingPattern) ? keyLeadingPattern : DEFAULT_KEY_LEADING_PATTERN;
if (args != null && args.Length > 0)
Parse(args);
}
public InputArguments(string[] args)
: this(args, null)
{
}
public bool Contains(string key)
{
string adjustedKey;
return ContainsKey(key, out adjustedKey);
}
public virtual string GetPeeledKey(string key)
{
return IsKey(key) ? key.Substring(_keyLeadingPattern.Length) : key;
}
public virtual string GetDecoratedKey(string key)
{
return !IsKey(key) ? (_keyLeadingPattern + key) : key;
}
public virtual bool IsKey(string str)
{
return str.StartsWith(_keyLeadingPattern);
}
#endregion
#region internal methods
protected virtual void Parse(string[] args)
{
for (int i = 0; i < args.Length; i++)
{
if (args[i] == null) continue;
string key = null;
string val = null;
if (IsKey(args[i]))
{
key = args[i];
if (i + 1 < args.Length && !IsKey(args[i + 1]))
{
val = args[i + 1];
i++;
}
}
else
val = args[i];
// adjustment
if (key == null)
{
key = val;
val = null;
}
_parsedArguments[key] = val;
}
}
protected virtual string GetValue(string key)
{
string adjustedKey;
if (ContainsKey(key, out adjustedKey))
return _parsedArguments[adjustedKey];
return null;
}
protected virtual bool ContainsKey(string key, out string adjustedKey)
{
adjustedKey = key;
if (_parsedArguments.ContainsKey(key))
return true;
if (IsKey(key))
{
string peeledKey = GetPeeledKey(key);
if (_parsedArguments.ContainsKey(peeledKey))
{
adjustedKey = peeledKey;
return true;
}
return false;
}
string decoratedKey = GetDecoratedKey(key);
if (_parsedArguments.ContainsKey(decoratedKey))
{
adjustedKey = decoratedKey;
return true;
}
return false;
}
#endregion
}
}