-
Notifications
You must be signed in to change notification settings - Fork 396
Expand file tree
/
Copy pathCommandLineArgs.cs
More file actions
120 lines (104 loc) · 2.54 KB
/
CommandLineArgs.cs
File metadata and controls
120 lines (104 loc) · 2.54 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
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
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
namespace ReClassNET.Util
{
public class CommandLineArgs
{
private readonly List<string> fileNames = new List<string>();
private readonly SortedDictionary<string, string> parms = new SortedDictionary<string, string>();
/// <summary>
/// Get the primary file name.
/// </summary>
public string FileName => fileNames.Count < 1 ? null : fileNames[0];
/// <summary>
/// Gets all file names.
/// </summary>
public IEnumerable<string> FileNames => fileNames;
/// <summary>
/// Gets all provided parameters.
/// </summary>
public IEnumerable<KeyValuePair<string, string>> Parameters => parms;
public CommandLineArgs(string[] args)
{
if (args == null)
{
return;
}
foreach (var str in args)
{
if (string.IsNullOrEmpty(str))
{
continue;
}
var kv = GetParameter(str);
if (kv.Key.Length == 0)
{
fileNames.Add(kv.Value);
}
else
{
parms[kv.Key] = kv.Value;
}
}
}
/// <summary>
/// Get the value of a command line parameter.
/// </summary>
/// <returns>
/// Returns <c>null</c> if no parameter with the specified key exists.
/// </returns>
public string this[string strKey]
{
get
{
if (parms.TryGetValue(strKey.ToLower(), out var strValue))
{
return strValue;
}
return null;
}
}
/// <summary>
/// Parses the parameter and extracts the key and value.
/// </summary>
/// <param name="str">The parameter string to parse.</param>
/// <returns>
/// The parameter split in key and value. An empty key signals a file name.
/// </returns>
internal static KeyValuePair<string, string> GetParameter(string str)
{
Contract.Requires(str != null);
if (str.StartsWith("--"))
{
str = str.Remove(0, 2);
}
else if (str.StartsWith("-"))
{
str = str.Remove(0, 1);
}
else
{
return new KeyValuePair<string, string>(string.Empty, str);
}
var posColon = str.IndexOf(':');
var posEqual = str.IndexOf('=');
if (posColon < 0 && posEqual < 0)
{
return new KeyValuePair<string, string>(str.ToLower(), string.Empty);
}
var posMin = Math.Min(posColon, posEqual);
if (posMin < 0)
{
posMin = posColon < 0 ? posEqual : posColon;
}
if (posMin <= 0)
{
return new KeyValuePair<string, string>(str.ToLower(), string.Empty);
}
var key = str.Substring(0, posMin).ToLower();
var value = str.Remove(0, posMin + 1);
return new KeyValuePair<string, string>(key, value);
}
}
}