chr
2026-04-05 fe750b791d5b517cc4e9bc8e99a9a75139a0cfba
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
//            Copyright Keysight Technologies 2012-2019
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, you can obtain one at http://mozilla.org/MPL/2.0/.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace OpenTap.Cli
{
    /// <summary>
    /// Parser for command line arguments. Supports --,-,/ based argument options 
    /// as well as unnamed options mixed with named ones.
    /// </summary>
    internal class ArgumentsParser
    {
        public ArgumentCollection AllOptions = new ArgumentCollection();
 
        struct optionFindResult
        {
            public Argument FoundOption;
            public bool IsUnknown;
            public string InlineArg;
        }
 
        optionFindResult findOption(string st, ArgumentCollection options)
        {
            optionFindResult opt = new optionFindResult { IsUnknown = false };
            int len = 0;
            if (st.StartsWith("--"))
            {
                len = 2;
            }
            else if (st.StartsWith("-")) // Removed check for starting with '\'. It breaks installing a package from network drive because it starts with \\.
            {
                len = 1;
            }
            if (len == 0)
            {
                return opt;
            }
 
            st = st.Substring(len);
            var idx = st.IndexOf('=');
            if (idx > 0)
            {
                opt.InlineArg = st.Substring(idx + 1);
                st = st.Substring(0, idx);
            }
            opt.FoundOption = options
                .FirstOrDefault(o => o.Value.CompareTo(st)).Value;
 
            if (opt.FoundOption == null)
            {
                opt.FoundOption = AllOptions
                    .FirstOrDefault(o => o.Value.CompareTo(st)).Value;
            }
 
            if (opt.FoundOption == null)
            {
                opt.IsUnknown = true;
            }
            else
            {
                opt.FoundOption = opt.FoundOption.Clone();
            }
            return opt;
        }
 
        public ArgumentCollection Parse(string[] rawArgs)
        {
            ArgumentCollection options = AllOptions.CreateDefault();
            List<string> restList = options.UnnamedArguments.ToList();
            for (int i = 0; i < rawArgs.Length; i++)
            {
                string arg = rawArgs[i];
                optionFindResult optResult = findOption(arg, options);
                Argument opt = optResult.FoundOption;
                if (opt == null)
                {
                    if (optResult.IsUnknown == false)
                    {
                        restList.Add(arg);
                    }
                    else
                    {
                        options.UnknownsOptions.Add(arg);
                    }
                    continue;
                }
 
                if (opt.NeedsArgument)
                {
                    if (optResult.InlineArg != null)
                    {
                        opt.Values.Add(optResult.InlineArg);
                    }
                    else if (i + 1 < rawArgs.Length)
                    {
                        opt.Values.Add(rawArgs[++i]);
                    }
                    else
                    {
                        options.MissingArguments.Add(opt);
                        continue;
                    }
                }
                else
                {
                    if (optResult.InlineArg != null)
                    {
                        // Add the value of the inline arg, even if NeedsArgument was not specified
                        opt.Values.Add(optResult.InlineArg);
                    }
                }
                options.Add(opt);
            }
            options.UnnamedArguments = restList.ToArray();
            return options;
        }
    }
 
    internal class Argument
    {
        /// <summary>
        /// Optional. Used with one '-' or a '/'.
        /// </summary>
        public char ShortName { get; private set; }
        /// <summary>
        /// Non optional. used with '--' or '/'. Also used for argument lookup.
        /// </summary>
        public string LongName { get; private set; }
        /// <summary>
        /// If an argument is required for this option.
        /// </summary>
        public bool NeedsArgument { get; private set; }
        /// <summary>
        /// Argument given to this option.
        /// </summary>
        public string Value { get { return Values.FirstOrDefault(); } }
        /// <summary>
        /// Argument given to this option. Also used as a default.
        /// </summary>
        public List<string> Values { get; private set; }
        /// <summary>
        /// Short description for this option.
        /// </summary>
        public string Description { get; set; }
        /// <summary>
        /// Indicates if an argument should be shown in "--help" output.
        /// </summary>
        public bool IsVisible { get; set; } = true;
        /// <summary>
        /// Initializes a new instance of the Option class.
        /// </summary>
        public Argument(string longName, char shortName = default(char), bool needsArgument = true, string description = "", string defaultArg = null)
        {
            ShortName = shortName;
            LongName = longName;
            NeedsArgument = needsArgument;
            Description = description;
            Values = new List<string>();
            if (String.IsNullOrWhiteSpace(defaultArg) == false)
            {
                Values.Add(defaultArg);
            }
        }
 
        /// <summary>
        /// Clones the option with a new argument
        /// </summary>
        /// <param name="argument"></param>
        /// <returns></returns>
        public Argument Clone(string argument)
        {
            var opt = Clone();
            opt.Values = new List<string> { argument };
            return opt;
        }
 
        public Argument Clone()
        {
            return new Argument(LongName, ShortName, NeedsArgument)
            {
                Values = new List<string>(Values),
                Description = Description
            };
        }
 
        public bool CompareTo(string arg)
        {
            if (arg.Length == 1 && ShortName != default(char))
            {
                return arg[0] == ShortName;
            }
            return arg == LongName;
        }
    }
 
    /// <summary>
    /// A collection of options optionally with arguments.
    /// Also includes Unnamed arguments and in case of errors unknown options and missing arguments
    /// This class is used both as and input and output to option parsing.
    /// </summary>
    internal class ArgumentCollection : Dictionary<string, Argument>
    {
        public string[] UnnamedArguments { get; set; }
        public List<IMemberData> UnnamedArgumentData { get; set; }
 
        public List<string> UnknownsOptions { get; set; }
        public List<Argument> MissingArguments { get; set; }
 
        public ArgumentCollection()
        {
            UnnamedArguments = new string[0];
            UnknownsOptions = new List<string>();
            MissingArguments = new List<Argument>();
        }
 
        public Argument Add(Argument option)
        {
            this[option.LongName] = option;
            return option;
        }
 
        public Argument Add(string longName, char shortName = default(char),
            bool needsArgument = true, string description = "", string defaultArgument = null)
        {
            var option = new Argument(longName, shortName, needsArgument, description, defaultArgument);
            return Add(option);
        }
 
        public bool Contains(string optionName)
        {
            return ContainsKey(optionName);
        }
 
        public Argument GetOrDefault(string optionLongName)
        {
            if (Contains(optionLongName))
            {
                return this[optionLongName];
            }
            return null;
        }
 
        public string Argument(string optionLongName)
        {
            return this[optionLongName].Value;
        }
 
        public string GetArgumentOrDefault(string optionLongName, string def = default(string))
        {
            var opt = GetOrDefault(optionLongName);
            if (opt != null)
            {
                return opt.Value;
            }
            return def;
        }
        /// <summary>
        /// Transfers an option from one
        /// </summary>
        /// <param name="optionName"></param>
        /// <param name="from"></param>
        /// <returns></returns>
        public Argument TakeOption(string optionName, ArgumentCollection from)
        {
            if (from.Contains(optionName))
            {
                this[optionName] = from[optionName].Clone();
                return this[optionName];
            }
            return null;
        }
 
        public ArgumentCollection CreateDefault()
        {
            ArgumentCollection opt = new ArgumentCollection { UnnamedArguments = UnnamedArguments };
            foreach (var key in Keys)
            {
                if (this[key].Value != null)
                {
                    opt[key] = this[key];
                }
            }
            return opt;
        }
 
        /// <summary>
        /// This is a simple abstraction over unnamed and named arguments to simplify output formatting.
        /// </summary>
        /// <returns></returns>
        class OptionWrapper
        {
            public UnnamedCommandLineArgument Positional { get; }
            public Argument Argument { get; }
 
            public OptionWrapper(Argument argument)
            {
                Argument = argument;
            }
 
            public OptionWrapper(UnnamedCommandLineArgument positional)
            {
                Positional = positional;
            }
 
            public string Description()
            {
                return Positional != null ? Positional.Description : Argument.Description;
            }
 
            public override string ToString()
            {
                if (Positional != null)
                {
                    return "  " + (Positional.Required ? $"<{Positional.Name}>" : $"[{Positional.Name}]");
                }
                else
                {
                    var result = "  ";
                    if (Argument.ShortName != default(char))
                    {
                        result += $"-{Argument.ShortName}, ";
                    }
                    result += $"--{Argument.LongName}";
                    return result;
                }
            }
        }
 
        /// <summary>
        /// Converts the ArgumentCollection to a help-string.
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            StringBuilder output = new StringBuilder();
            var wrappers = new List<OptionWrapper>();
 
            if (UnnamedArgumentData?.Any() == true)
            {
                foreach (var u in UnnamedArgumentData)
                {
                    if (u.GetAttribute<UnnamedCommandLineArgument>() is { } a)
                    {
                        wrappers.Add(new OptionWrapper(a));
                    }
                }
            }
            wrappers.AddRange(this.Values.Where(v => v.IsVisible).Select(k => new OptionWrapper(k)));
 
            // Compute the options' width
            int width = wrappers.Select(w => w.ToString().Length).Max() + 3;
 
            foreach (var wrapper in wrappers)
            {
                var arg = wrapper.ToString();
                var description = wrapper.Description();
                if (!string.IsNullOrEmpty(description))
                {
                    output.Append(arg);
                    // Offst by the arument length in the first iteration
                    var offset = arg.Length;
                    foreach (var descSplit in description.Split('\n'))
                    {
                        output.AppendLine(descSplit.PadLeft(descSplit.Length + width - offset));
                        offset = 0;
                    }
                }
                else
                {
                    output.AppendLine(arg);
                }
            }
            return output.ToString();
        }
    }
}