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
//            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.ComponentModel;
using System.Diagnostics;
using System.Linq;
 
namespace OpenTap.Cli
{
    /// <summary>
    /// Helper class that enhances the <see cref="ICliAction">ICliAction</see> with extra extensions methods.
    /// </summary>
    internal static class ICliActionExtensions
    {
        /// <summary>
        /// Executes the action with the given parameters.
        /// </summary>
        /// <param name="action">The action to be executed.</param>
        /// <param name="parameters">The parameters for the action.</param>
        /// <returns></returns>
        public static int PerformExecute(this ICliAction action, string[] parameters)
        {
            ArgumentsParser ap = new ArgumentsParser();
            var td = TypeData.GetTypeData(action);
            if (td == null)
                throw new Exception("Type data is null for action: " + action.GetType().Name);
            var props = td.GetMembers();
 
            ap.AllOptions.Add("help", 'h', false, "Write help information.");
            ap.AllOptions.Add("verbose", 'v', false, "Show verbose/debug-level log messages.");
            ap.AllOptions.Add("color", 'c', false, "Color messages according to their severity.");
            ap.AllOptions.Add("quiet", 'q', false, "Quiet console logging.");
            ap.AllOptions.Add("log", description: "Specify log file location. Default is ./SessionLogs.");
 
            var argToProp = new Dictionary<string, IMemberData>();
            var unnamedArgToProp = new List<IMemberData>();
 
            var overrides = new HashSet<string>();
 
            foreach (var prop in props)
            {
                if (prop.Readable == false || prop.Writable == false)
                    continue;
 
                if (prop.HasAttribute<UnnamedCommandLineArgument>())
                {
                    unnamedArgToProp.Add(prop);
                    continue;
                }
 
                if (!prop.HasAttribute<CommandLineArgumentAttribute>())
                    continue;
 
                var attr = prop.GetAttribute<CommandLineArgumentAttribute>();
 
                var needsArg = prop.TypeDescriptor != TypeData.FromType(typeof(bool));
 
                string description = "";
                if (prop.HasAttribute<ObsoleteAttribute>())
                {
                    var obsoleteAttribute = prop.GetAttribute<ObsoleteAttribute>();
                    description = $"[OBSOLETE: {obsoleteAttribute.Message}] {attr.Description}";
                }
                else
                {
                    description = attr.Description;
                }
 
                if (ap.AllOptions.Contains(attr.Name))
                {
                    overrides.Add(attr.Name);
                }
 
                if (!string.IsNullOrWhiteSpace(attr.ShortName))
                {
                    var overriden = ap.AllOptions.FirstOrDefault(opt => opt.Value?.ShortName == attr.ShortName[0])
                        .Value;
                    if (overriden != null)
                    {
                        overrides.Add(overriden.ShortName.ToString());
                        // Set the ShortName of the overriden option to '\0' so the argument parser will resolve this ShortName to the overriding option
                        // The overriden option can still be accessed by its LongName, provided that is not also overriden
                        ap.AllOptions.Add(overriden.LongName, '\0', overriden.NeedsArgument, overriden.Description);
                    }
                }
 
                var arg = ap.AllOptions.Add(attr.Name, attr.ShortName?.FirstOrDefault() ?? '\0', needsArg, description);
                // attr.Visible has been obsoleted but is still considered for backward compatibility.
#pragma warning disable CS0618
                arg.IsVisible = attr.Visible && (prop.GetAttribute<BrowsableAttribute>()?.Browsable ?? true);
#pragma warning restore CS0618
                argToProp.Add(arg.LongName, prop);
            }
 
            var args = ap.Parse(parameters);
 
            if (args.MissingArguments.Any())
                throw new Exception(
                    $"Command line argument '{args.MissingArguments.FirstOrDefault().LongName}' is missing an argument.");
 
            foreach (var @override in overrides)
            {
                if (args.Contains(@override))
                    log.Debug(
                        $"The CLI option '--{@override}' from '{action}' overrides a common CLI option from OpenTAP.");
                else if (@override.Length == 1)
                {
                    var shortName = @override[0];
                    var isUsed = args.Any(a => a.Value?.ShortName == shortName);
                    if (isUsed)
                        log.Debug(
                            $"The CLI option '-{@override}' from '{action}' overrides a common CLI option from OpenTAP.");
                }
            }
 
            if (!overrides.Contains("help") && args.Contains("help"))
            {
                printOptions(action.GetType().GetDisplayAttribute().Name, ap.AllOptions, unnamedArgToProp);
                return (int)ExitCodes.Success;
            }
 
            if (!overrides.Contains("log") && args.Contains("log"))
            {
                SessionLogs.Rename(args.Argument("log"));
            }
 
            foreach (var opts in args)
            {
                if (argToProp.ContainsKey(opts.Key) == false) continue;
                var prop = argToProp[opts.Key];
 
                if (prop.TypeDescriptor is TypeData propTd)
                {
                    Type propType2 = propTd.Load();
 
                    object getValue(string src, Type propType)
                    {
                        if (propType == typeof(string)) return src;
                        if (propType == typeof(bool)) return true;
                        if (propType.IsEnum)
                            return parseArbitrary(opts.Key, src, propType);
                        if (propType == typeof(int)
                            || propType == typeof(long)
                            || propType == typeof(uint)
                            || propType == typeof(ushort)
                            || propType == typeof(short)
                            || propType == typeof(byte)
                            || propType == typeof(sbyte)
                            || propType == typeof(ulong)
                            || propType == typeof(double)
                            || propType == typeof(float))
                            return Convert.ChangeType(src, propType);
                        throw new Exception(
                            $"Command line option '{opts.Key}' is of an unsupported type '{propType.Name}'.");
                    }
 
                    if (propType2 != typeof(string) && propType2.IsArray)
                    {
                        var array = Array.CreateInstance(propType2.GetElementType(), opts.Value.Values.Count);
                        var elemType = propType2.GetElementType();
                        for (int i = 0; i < array.Length; i++)
                            array.SetValue(getValue(opts.Value.Values[i], elemType), i);
                        prop.SetValue(action, array);
                    }
                    else
                    {
                        prop.SetValue(action, getValue(opts.Value.Value, propType2));
                    }
                }
                else
                    throw new Exception(
                        $"Command line option '{opts.Key}' is of an unsupported type '{prop.TypeDescriptor.Name}'.");
            }
 
            unnamedArgToProp = unnamedArgToProp.OrderBy(p => p.GetAttribute<UnnamedCommandLineArgument>().Order)
                .ToList();
            var requiredArgs = unnamedArgToProp.Where(x => x.GetAttribute<UnnamedCommandLineArgument>().Required)
                .ToHashSet();
            int idx = 0;
 
            for (int i = 0; i < unnamedArgToProp.Count; i++)
            {
                var p = unnamedArgToProp[i];
 
                if (p.TypeDescriptor.IsA(typeof(string)))
                {
                    if (idx < args.UnnamedArguments.Length)
                    {
                        p.SetValue(action, args.UnnamedArguments[idx++]);
                        requiredArgs.Remove(p);
                    }
                }
                else if (p.TypeDescriptor.IsA(typeof(string[])))
                {
                    if (idx < args.UnnamedArguments.Length)
                    {
                        p.SetValue(action, args.UnnamedArguments.Skip(idx).ToArray());
                        requiredArgs.Remove(p);
                    }
 
                    idx = args.UnnamedArguments.Length;
                }
                else if (p.TypeDescriptor is TypeData td2 && td2.Type.IsEnum)
                {
                    if (idx < args.UnnamedArguments.Length)
                    {
                        var name = p.GetAttribute<UnnamedCommandLineArgument>()?.Name ?? p.Name;
                        p.SetValue(action, parseArbitrary($"<{name}>", args.UnnamedArguments[idx++], td2.Type));
                        requiredArgs.Remove(p);
                    }
                }
            }
 
            if (args.UnknownsOptions.Any() || requiredArgs.Any())
            {
                if (args.UnknownsOptions.Any())
                    Console.WriteLine("Unknown options: " + string.Join(" ", args.UnknownsOptions));
 
                if (requiredArgs.Any())
                    Console.WriteLine("Missing argument: " + string.Join(" ",
                        requiredArgs.Select(p => p.GetAttribute<UnnamedCommandLineArgument>().Name)));
 
                printOptions(action.GetType().GetDisplayAttribute().Name, ap.AllOptions, unnamedArgToProp);
                return (int)ExitCodes.ArgumentParseError;
            }
 
            var actionFullName = td.GetDisplayAttribute().GetFullName();
            bool isUpdate = "package \\ check-updates" == actionFullName;
 
            if (isUpdate)
            { 
                // Avoid logging debug information for check-updates, since this is potentially confusing.
                return action.Execute(TapThread.Current.AbortToken);
            }
 
            log.Debug($"Executing CLI action: {actionFullName}");
            var sw = Stopwatch.StartNew();
            int exitCode = action.Execute(TapThread.Current.AbortToken);
            log.Debug(sw, "CLI action returned exit code: {0}", exitCode);
            return exitCode;
        }
 
        static TraceSource log = Log.CreateSource("CLI");
 
        private static void printOptions(string passName, ArgumentCollection options, List<IMemberData> unnamed)
        {
            var namedArguments = string.Join(" ", options.Values.Where(x => x.IsVisible)
                .Select(x =>
                {
                    var str = x.ShortName != 0 ? $"-{x.ShortName}" : "--" + x.LongName;
                    if (x.NeedsArgument)
                        str += " <arg>";
 
                    return '[' + str + ']';
                }));
            var unnamedArguments = string.Join(" ", unnamed.Select(x =>
            {
                var attr = x.GetAttribute<UnnamedCommandLineArgument>();
                var str = attr.Name;
 
                if (attr.Required == false)
                    str = "[<" + str + ">]";
                else
                    str = "<" + str + ">";
 
                return str;
            }));
            Console.WriteLine($"Usage: {passName} {namedArguments} {unnamedArguments}"); 
            options.UnnamedArgumentData = unnamed;
            Console.Write(options);
        }
 
        private static object parseArbitrary(string name, string value, Type propertyType)
        {
            var obj = StringConvertProvider.FromString(value, TypeData.FromType(propertyType), null,
                System.Globalization.CultureInfo.InvariantCulture);
 
            if (obj == null)
                throw new Exception(string.Format(
                    "Could not parse argument '{0}'. Argument given: '{1}'. Valid arguments: {2}", name, value,
                    string.Join(", ", propertyType.GetEnumNames())));
 
            return obj;
        }
    }
}