-
Notifications
You must be signed in to change notification settings - Fork 479
/
Copy pathUnParserExtensions.cs
257 lines (226 loc) · 10.6 KB
/
UnParserExtensions.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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
// Copyright 2005-2015 Giacomo Stelluti Scala & Contributors. All rights reserved. See License.md in the project root for license information.
using System;
using System.Collections;
using System.Linq;
using System.Text;
using CommandLine.Core;
using CommandLine.Infrastructure;
using CSharpx;
namespace CommandLine
{
/// <summary>
/// Provides settings for when formatting command line from an options instance../>.
/// </summary>
public class UnParserSettings
{
private bool preferShortName;
private bool groupSwitches;
private bool useEqualToken;
private bool showHidden;
/// <summary>
/// Gets or sets a value indicating whether unparsing process shall prefer short or long names.
/// </summary>
public bool PreferShortName
{
get { return preferShortName; }
set { PopsicleSetter.Set(Consumed, ref preferShortName, value); }
}
/// <summary>
/// Gets or sets a value indicating whether unparsing process shall group switches.
/// </summary>
public bool GroupSwitches
{
get { return groupSwitches; }
set { PopsicleSetter.Set(Consumed, ref groupSwitches, value); }
}
/// <summary>
/// Gets or sets a value indicating whether unparsing process shall use equal sign with long names.
/// </summary>
public bool UseEqualToken
{
get { return useEqualToken; }
set { PopsicleSetter.Set(Consumed, ref useEqualToken, value); }
}
/// <summary>
/// Gets or sets a value indicating whether unparsing process shall expose hidden options.
/// </summary>
public bool ShowHidden
{
get { return showHidden; }
set { PopsicleSetter.Set(Consumed, ref showHidden, value); }
}
/// <summary>
/// Factory method that creates an instance of <see cref="CommandLine.UnParserSettings"/> with GroupSwitches set to true.
/// </summary>
/// <returns>A properly initalized <see cref="CommandLine.UnParserSettings"/> instance.</returns>
public static UnParserSettings WithGroupSwitchesOnly()
{
return new UnParserSettings { GroupSwitches = true };
}
/// <summary>
/// Factory method that creates an instance of <see cref="CommandLine.UnParserSettings"/> with UseEqualToken set to true.
/// </summary>
/// <returns>A properly initalized <see cref="CommandLine.UnParserSettings"/> instance.</returns>
public static UnParserSettings WithUseEqualTokenOnly()
{
return new UnParserSettings { UseEqualToken = true };
}
internal bool Consumed { get; set; }
}
/// <summary>
/// Provides overloads to unparse options instance.
/// </summary>
public static class UnParserExtensions
{
/// <summary>
/// Format a command line argument string from a parsed instance.
/// </summary>
/// <typeparam name="T">Type of <paramref name="options"/>.</typeparam>
/// <param name="parser">Parser instance.</param>
/// <param name="options">A parsed (or manually correctly constructed instance).</param>
/// <returns>A string with command line arguments.</returns>
public static string FormatCommandLine<T>(this Parser parser, T options)
{
return parser.FormatCommandLine(options, config => {});
}
/// <summary>
/// Format a command line argument string from a parsed instance.
/// </summary>
/// <typeparam name="T">Type of <paramref name="options"/>.</typeparam>
/// <param name="parser">Parser instance.</param>
/// <param name="options">A parsed (or manually correctly constructed instance).</param>
/// <param name="configuration">The <see cref="Action{UnParserSettings}"/> lambda used to configure
/// aspects and behaviors of the unparsersing process.</param>
/// <returns>A string with command line arguments.</returns>
public static string FormatCommandLine<T>(this Parser parser, T options, Action<UnParserSettings> configuration)
{
if (options == null) throw new ArgumentNullException("options");
var settings = new UnParserSettings();
configuration(settings);
settings.Consumed = true;
var type = options.GetType();
var builder = new StringBuilder();
type.GetVerbSpecification()
.MapValueOrDefault(verb => builder.Append(verb.Name).Append(' '), builder);
var specs =
(from info in
type.GetSpecifications(
pi => new { Specification = Specification.FromProperty(pi),
Value = pi.GetValue(options, null).NormalizeValue(), PropertyValue = pi.GetValue(options, null) })
where !info.PropertyValue.IsEmpty()
select info)
.Memorize();
var allOptSpecs = from info in specs.Where(i => i.Specification.Tag == SpecificationType.Option)
let o = (OptionSpecification)info.Specification
where o.TargetType != TargetType.Switch || (o.TargetType == TargetType.Switch && ((bool)info.Value))
where !o.Hidden || settings.ShowHidden
orderby o.UniqueName()
select info;
var shortSwitches = from info in allOptSpecs
let o = (OptionSpecification)info.Specification
where o.TargetType == TargetType.Switch
where o.ShortName.Length > 0
orderby o.UniqueName()
select info;
var optSpecs = settings.GroupSwitches
? allOptSpecs.Where(info => !shortSwitches.Contains(info))
: allOptSpecs;
var valSpecs = from info in specs.Where(i => i.Specification.Tag == SpecificationType.Value)
let v = (ValueSpecification)info.Specification
orderby v.Index
select info;
builder = settings.GroupSwitches && shortSwitches.Any()
? builder.Append('-').Append(string.Join(string.Empty, shortSwitches.Select(
info => ((OptionSpecification)info.Specification).ShortName).ToArray())).Append(' ')
: builder;
optSpecs.ForEach(
opt =>
builder
.Append(FormatOption((OptionSpecification)opt.Specification, opt.Value, settings))
.Append(' ')
);
builder.AppendWhen(valSpecs.Any() && parser.Settings.EnableDashDash, "-- ");
valSpecs.ForEach(
val => builder.Append(FormatValue(val.Specification, val.Value)).Append(' '));
return builder
.ToString().TrimEnd(' ');
}
private static string FormatValue(Specification spec, object value)
{
var builder = new StringBuilder();
switch (spec.TargetType)
{
case TargetType.Scalar:
builder.Append(FormatWithQuotesIfString(value));
break;
case TargetType.Sequence:
var sep = spec.SeperatorOrSpace();
Func<object, object> format = v
=> sep == ' ' ? FormatWithQuotesIfString(v) : v;
var e = ((IEnumerable)value).GetEnumerator();
while (e.MoveNext())
builder.Append(format(e.Current)).Append(sep);
builder.TrimEndIfMatch(sep);
break;
}
return builder.ToString();
}
private static object FormatWithQuotesIfString(object value)
{
Func<string, string> doubQt = v
=> v.Contains("\"") ? v.Replace("\"", "\\\"") : v;
return (value as string)
.ToMaybe()
.MapValueOrDefault(v => v.Contains(' ') || v.Contains("\"")
? "\"".JoinTo(doubQt(v), "\"") : v, value);
}
private static char SeperatorOrSpace(this Specification spec)
{
return (spec as OptionSpecification).ToMaybe()
.MapValueOrDefault(o => o.Separator != '\0' ? o.Separator : ' ', ' ');
}
private static string FormatOption(OptionSpecification spec, object value, UnParserSettings settings)
{
return new StringBuilder()
.Append(spec.FormatName(settings))
.AppendWhen(spec.TargetType != TargetType.Switch, FormatValue(spec, value))
.ToString();
}
private static string FormatName(this OptionSpecification optionSpec, UnParserSettings settings)
{
// Have a long name and short name not preferred? Go with long!
// No short name? Has to be long!
var longName = (optionSpec.LongName.Length > 0 && !settings.PreferShortName)
|| optionSpec.ShortName.Length == 0;
return
new StringBuilder(longName
? "--".JoinTo(optionSpec.LongName)
: "-".JoinTo(optionSpec.ShortName))
.AppendWhen(optionSpec.TargetType != TargetType.Switch, longName && settings.UseEqualToken ? "=" : " ")
.ToString();
}
private static object NormalizeValue(this object value)
{
#if !SKIP_FSHARP
if (value != null
&& ReflectionHelper.IsFSharpOptionType(value.GetType())
&& FSharpOptionHelper.IsSome(value))
{
return FSharpOptionHelper.ValueOf(value);
}
#endif
return value;
}
private static bool IsEmpty(this object value)
{
if (value == null) return true;
#if !SKIP_FSHARP
if (ReflectionHelper.IsFSharpOptionType(value.GetType()) && !FSharpOptionHelper.IsSome(value)) return true;
#endif
if (value is ValueType && value.Equals(value.GetType().GetDefaultValue())) return true;
if (value is string && ((string)value).Length == 0) return true;
if (value is IEnumerable && !((IEnumerable)value).GetEnumerator().MoveNext()) return true;
return false;
}
}
}