public static IValueNode CreateDefaultValue( ICompletionContext context, ArgumentDefinition definition, IInputType fieldType) { try { if (definition.NativeDefaultValue != null) { return(fieldType.ParseValue( definition.NativeDefaultValue)); } return(definition.DefaultValue.IsNull() ? NullValueNode.Default : definition.DefaultValue); } catch (Exception ex) { // TODO : RESOURCES context.ReportError(SchemaErrorBuilder.New() .SetMessage( "Could not parse the native value of input field " + $"`{context.Type.Name}.{definition.Name}`.") .SetCode(TypeErrorCodes.MissingType) .SetTypeSystemObject(context.Type) .AddSyntaxNode(definition.SyntaxNode) .SetException(ex) .Build()); return(NullValueNode.Default); } }
public static IValueNode CreateDefaultValue( ICompletionContext context, ArgumentDefinition definition, IInputType fieldType) { try { if (definition.NativeDefaultValue != null) { return(fieldType.ParseValue( definition.NativeDefaultValue)); } return(definition.DefaultValue.IsNull() ? NullValueNode.Default : definition.DefaultValue); } catch (Exception ex) { context.ReportError(SchemaErrorBuilder.New() .SetMessage(TypeResources.FieldInitHelper_InvalidDefaultValue) .SetCode(TypeErrorCodes.MissingType) .SetTypeSystemObject(context.Type) .AddSyntaxNode(definition.SyntaxNode) .SetException(ex) .Build()); return(NullValueNode.Default); } }
private ArgumentSummary Summarize(ArgumentDefinition arg) { var attrib = arg.Attribute; var namedAttrib = arg.Attribute as NamedArgumentAttribute; var enumType = arg.ArgumentType as IEnumArgumentType; var isCommand = false; var type = arg.ArgumentType.Type; if (type.GetTypeInfo().IsGenericType&& type.GetGenericTypeDefinition().Name == "CommandGroup`1") { enumType = ArgumentType.GetType(type.GetGenericArguments().First()) as IEnumArgumentType; isCommand = true; } return(new ArgumentSummary { name = attrib.LongName, short_name = namedAttrib?.ShortName, required = arg.IsRequired, command = isCommand, takes_rest_of_line = arg.TakesRestOfLine, type = arg.ArgumentType.DisplayName, description = attrib.Description, default_value = arg.HasDefaultValue ? attrib.DefaultValue : null, possible_values = enumType?.GetValues() .Where(value => !value.Hidden && !value.Disallowed) .Select(value => Summarize(arg, value)) .ToArray(), }); }
internal static IValueNode?CompleteDefaultValue( ITypeCompletionContext context, ArgumentDefinition argumentDefinition, IInputType argumentType, FieldCoordinate argumentCoordinate) { try { return(argumentDefinition.RuntimeDefaultValue != null ? context.DescriptorContext.InputFormatter.FormatValue( argumentDefinition.RuntimeDefaultValue, argumentType, Path.Root) : argumentDefinition.DefaultValue); } catch (Exception ex) { context.ReportError(SchemaErrorBuilder.New() .SetMessage( TypeResources.FieldInitHelper_InvalidDefaultValue, argumentCoordinate) .SetCode(ErrorCodes.Schema.MissingType) .SetTypeSystemObject(context.Type) .AddSyntaxNode(argumentDefinition.SyntaxNode) .SetException(ex) .Build()); return(NullValueNode.Default); } }
public static int Main(string[] Args) { var definition = new ArgumentDefinition(new HtmlReportArguments().GetType()); var parser = new GNUArgumentParser(); int exitCode = 0; try { var arguments = parser.Parse <HtmlReportArguments>(definition, Args); string cssCode = ReadAllText(arguments.CssPath); var reports = new List <TestReport>(); foreach (var reportPath in arguments.ReportPaths) { reports.Add(ParseReport(reportPath)); } var htmlDoc = CreateComparisonHtml(cssCode, reports); htmlDoc.Save(Console.Out); Console.WriteLine(); } catch (Exception ex) { Console.Error.WriteLine("error: {0}", ex.Message); Console.Error.Write("usage: {0}", parser.GenerateUsageString(definition)); exitCode = 1; } return(exitCode); }
private static void AddSerializerToInputField( ITypeCompletionContext completionContext, ArgumentDefinition definition, NameString typeName) { ITypeInspector typeInspector = completionContext.TypeInspector; IExtendedType? resultType; if (definition is InputFieldDefinition inputField) { resultType = typeInspector.GetReturnType(inputField.Property, true); } else if (definition.Parameter is not null) { resultType = typeInspector.GetArgumentType(definition.Parameter, true); } else if (definition.Type is ExtendedTypeReference typeReference) { resultType = typeReference.Type; } else { throw new SchemaException(SchemaErrorBuilder.New() .SetMessage("Unable to resolve type from field `{0}`.", definition.Name) .SetTypeSystemObject(completionContext.Type) .Build()); } definition.Formatters.Add(CreateSerializer(completionContext, resultType, typeName)); }
public static void DiscoverArguments( IDescriptorContext context, ICollection <ArgumentDefinition> arguments, MemberInfo?member) { if (arguments == null) { throw new ArgumentNullException(nameof(arguments)); } if (member is MethodInfo method) { var processed = new HashSet <NameString>( arguments.Select(t => t.Name)); foreach (ParameterInfo parameter in method.GetParameters()) { if (IsArgumentType(method, parameter)) { ArgumentDefinition argumentDefinition = ArgumentDescriptor .New(context, parameter) .CreateDefinition(); if (processed.Add(argumentDefinition.Name)) { arguments.Add(argumentDefinition); } } } } }
public static string GetUsageString() { var definition = new ArgumentDefinition(typeof(CommandLineArguments)); var parser = new GNUArgumentParser(); return($"Usage: {parser.GenerateUsageString(definition)}"); }
private static void InsertFormatter( ITypeCompletionContext completionContext, ArgumentDefinition definition, NameString typeName, Type idRuntimeType) { var formatter = new PolymorphicGlobalIdInputValueFormatter( typeName, idRuntimeType, GetIdSerializer(completionContext)); IInputValueFormatter?defaultFormatter = definition.Formatters .FirstOrDefault(f => f is GlobalIdInputValueFormatter); if (defaultFormatter == null) { definition.Formatters.Add(formatter); } else { definition.Formatters.Insert( definition.Formatters.IndexOf(defaultFormatter) - 1, formatter); } }
public static IValueNode CreateDefaultValue( ITypeCompletionContext context, ArgumentDefinition argumentDefinition, IInputType argumentType, FieldCoordinate argumentCoordinate) { try { return(argumentDefinition.NativeDefaultValue != null ? argumentType.ParseValue(argumentDefinition.NativeDefaultValue) : argumentDefinition.DefaultValue); } catch (Exception ex) { context.ReportError(SchemaErrorBuilder.New() .SetMessage( TypeResources.FieldInitHelper_InvalidDefaultValue, argumentCoordinate) .SetCode(ErrorCodes.Schema.MissingType) .SetTypeSystemObject(context.Type) .AddSyntaxNode(argumentDefinition.SyntaxNode) .SetException(ex) .Build()); return(NullValueNode.Default); } }
public async Task OrdinalIndexReturnsNullForNamedArgument() { var node = await TestNode.FindNode <AttributeArgumentSyntax>(ArgumentDefinitionCode.NamedArgument) .ConfigureAwait(false); var sut = new ArgumentDefinition(node, 1); sut.OrdinalIndex.Should().NotHaveValue(); }
internal void CopyTo(ArgumentDefinition target) { base.CopyTo(target); target._formatters = _formatters; target.DefaultValue = DefaultValue; target.RuntimeDefaultValue = RuntimeDefaultValue; target.Parameter = Parameter; }
public async Task ArgumentTypeReturnsNamedForNamedArgument() { var node = await TestNode.FindNode <AttributeArgumentSyntax>(ArgumentDefinitionCode.NamedArgument) .ConfigureAwait(false); var sut = new ArgumentDefinition(node, null); sut.ArgumentType.Should().Be(ArgumentType.Named); }
public async Task ParameterNameReturnsEmptyForOrdinalArgument() { var node = await TestNode.FindNode <AttributeArgumentSyntax>(ArgumentDefinitionCode.OrdinalArgument) .ConfigureAwait(false); var sut = new ArgumentDefinition(node, 1); sut.ParameterName.Should().BeEmpty(); }
static List <string> GetEnumerationTypes(ArgumentDefinition argument) { var regex = new Regex("\\((\"[\\w+-]+\"(?:\\|\"[\\w+-]+\")+)\\)"); var match = regex.Match(argument.Description); return(!match.Success ? new List <string>() : match.Groups[groupnum : 1].Value.Split(separator : '|').Select(x => x.Trim(trimChars : '"')).ToList()); }
public async Task NameReturnsValueForOrdinalArgument() { var node = await TestNode.FindNode <AttributeArgumentSyntax>(ArgumentDefinitionCode.OrdinalArgument) .ConfigureAwait(false); var sut = new ArgumentDefinition(node, 1); sut.Name.Should().Be("123"); }
public async Task NameReturnsParameterNameForNamedArgument() { var node = await TestNode.FindNode <AttributeArgumentSyntax>(ArgumentDefinitionCode.NamedArgument) .ConfigureAwait(false); var sut = new ArgumentDefinition(node, null); sut.Name.Should().Be("first"); }
void AddProperty(DataClass settingsClass, ArgumentDefinition argument) { //Todo improve if (argument.Name == "password-stdin") { return; } var propertyName = argument.Name.ToPascalCase(separator: '-'); var enumerations = GetEnumerationTypes(argument); var isEnumeration = enumerations.Any(); var property = new Property { Name = propertyName, Help = argument.Description.RemoveNewLines().FormatForXmlDoc(), DataClass = settingsClass, Format = $"--{argument.Name} {{value}}" }; if (isEnumeration) { if (!_enumerations.ContainsKey(propertyName)) { _enumerations.Add(propertyName, enumerations); } property.Type = property.Name; } else if (new[] { "list,stringSlice" }.Contains(argument.ValueType)) { property.Type = "List<string>"; } else if (argument.ValueType == "map") { property.Type = GetNukeType(argument); property.ItemFormat = "{key}:{value}"; } else { property.Type = GetNukeType(argument); } if (property.Type == "bool") { property.Format = $"--{argument.Name}"; } if (property.Name == "Password") { property.Secret = true; } settingsClass.Properties.Add(property); }
private static (string NodeTypeName, Type IdRuntimeType)? GetIdInfo( ITypeCompletionContext completionContext, ArgumentDefinition definition) { ITypeInspector typeInspector = completionContext.TypeInspector; IDAttribute? idAttribute = null; IExtendedType? idType = null; if (definition is InputFieldDefinition inputField) { idAttribute = (IDAttribute?)inputField.Property .GetCustomAttributes(inherit: true) .SingleOrDefault(a => a is IDAttribute); if (idAttribute == null) { return(null); } idType = typeInspector.GetReturnType(inputField.Property, true); } else if (definition.Parameter is not null) { idAttribute = (IDAttribute?)definition.Parameter .GetCustomAttributes(inherit: true) .SingleOrDefault(a => a is IDAttribute); if (idAttribute == null) { return(null); } idType = typeInspector.GetArgumentType(definition.Parameter, true); } else if (definition.Type is ExtendedTypeReference typeReference) { if (typeReference.Type.Kind == ExtendedTypeKind.Schema) { return(null); } } if (idAttribute is null || idType is null) { throw new SchemaException(SchemaErrorBuilder.New() .SetMessage("Unable to resolve type from field `{0}`.", definition.Name) .SetTypeSystemObject(completionContext.Type) .Build()); } Type idRuntimeType = idType.ElementType?.Source ?? idType.Source; string nodeTypeName = idAttribute?.TypeName.HasValue ?? false ? idAttribute.TypeName : completionContext.Type.Name; return(nodeTypeName, idRuntimeType); }
private static TypeDependencyKind GetDefaultValueDependencyKind( ArgumentDefinition argumentDefinition) { var hasDefaultValue = argumentDefinition.DefaultValue is not null and not NullValueNode || argumentDefinition.RuntimeDefaultValue is not null; return(hasDefaultValue ? TypeDependencyKind.Completed : TypeDependencyKind.Default); }
public async Task OrdinalIndexReturnsParameterValueForOrdinalArgument() { var index = Environment.TickCount; var node = await TestNode.FindNode <AttributeArgumentSyntax>(ArgumentDefinitionCode.OrdinalArgument) .ConfigureAwait(false); var sut = new ArgumentDefinition(node, index); sut.OrdinalIndex.Should().Be(index); }
private static void AddSerializerToInputField( ITypeCompletionContext completionContext, ArgumentDefinition definition, NameString typeName) { ITypeInspector typeInspector = completionContext.TypeInspector; IExtendedType? resultType; if (definition is InputFieldDefinition { RuntimeType : { } runtimeType })
/// <summary> /// Tries to find the argument's default value. /// </summary> /// <param name="arg">The argument to retrieve a default value from.</param> /// <param name="onlyReturnExplicitDefaults">True to only return /// a default if it was explicitly specified; false to report on /// the default, even if it was defaulted itself.</param> /// <param name="value">On success, receives the default value /// for this argument; otherwise, receives null.</param> /// <returns>True on success, false otherwise.</returns> public static bool TryGetDefaultValue(ArgumentDefinition arg, bool onlyReturnExplicitDefaults, out object value) { // Firstly, if the argument is required, then there's no need to // indicate any default value. if (arg.IsRequired) { value = null; return(false); } // Next, go check for the actual *effective* default value for the // argument; we may still receive back a value here even if one // wasn't explicitly declared, as we will have consulted with the // argument's type to determine its default value. if (onlyReturnExplicitDefaults && !arg.HasDefaultValue) { value = null; return(false); } // If the default value is null, then that's not useful to show the // user. var defaultValue = arg.EffectiveDefaultValue; if (defaultValue == null) { value = null; return(false); } // Special case: if the argument type is bool, then the argument // will be like a switch, and that's typically assumed to be false // if not present. So if the default value is indeed 'false', then // don't bother displaying it; but if it's 'true', then it's // important to indicate that. if ((defaultValue is bool) && !((bool)defaultValue)) { value = null; return(false); } // Special case: if the argument type is string, then it's safe // to assume that its default value is an empty string. if ((defaultValue is string stringDefaultValue) && string.IsNullOrEmpty(stringDefaultValue)) { value = null; return(false); } // Okay, we have the value. value = defaultValue; return(true); }
public void GetNameAndType() { // act var descriptor = new ArgumentDescriptor( Context, "args", typeof(string)); // assert ArgumentDefinition description = descriptor.CreateDefinition(); Assert.Equal("args", description.Name); Assert.Equal(typeof(string), Assert.IsType <ExtendedTypeReference>(description.Type).Type.Source); }
private ArgumentValueSummary Summarize(ArgumentDefinition arg, IArgumentValue value) { var commandAttrib = value.GetAttributes <CommandAttribute>().SingleOrDefault(); var commandType = commandAttrib?.GetImplementingType(arg.ArgumentType.Type); return(new ArgumentValueSummary { description = value.Description, name = value.LongName, short_name = value.ShortName, command_type = commandType.Name, command_argument_set = Summarize(GetArgumentSetFor(commandType)) }); }
public void SetDefaultValueNull() { // arrange var descriptor = new ArgumentDescriptor(Context, "args"); // act descriptor.DefaultValue(null); // assert ArgumentDefinition description = descriptor.CreateDefinition(); Assert.Equal(NullValueNode.Default, description.DefaultValue); Assert.Null(description.NativeDefaultValue); }
private static Type?TryGetArgRuntimeType( ArgumentDefinition argDef) { if (argDef.Parameter?.ParameterType is { } argRuntimeType) { return(argRuntimeType); } if (argDef.Type is ExtendedTypeReference extTypeRef) { return(TryGetRuntimeType(extTypeRef.Type)); } return(null); }
public void SetTypeInstance() { // arrange var descriptor = new ArgumentDescriptor(Context, "Type"); // act descriptor.Type(new StringType()); // assert ArgumentDefinition description = descriptor.CreateDefinition(); ITypeReference typeRef = description.Type; Assert.IsType <StringType>( Assert.IsType <SchemaTypeReference>(typeRef).Type); }
static string GetNukeType(ArgumentDefinition argument) { //Todo improve switch (argument.ValueType) { case "string": case "bool": case "int": case "float": return(argument.ValueType); case "decimal": return(argument.ValueType + "?"); case "int64": case "bytes": return("long?"); case "list": case "stringSlice": return("List<string>"); case "map": return("Dictionary<string,string>"); case "uint16": case "uint64": case "uint": return("int"); case "mount": case "credential-spec": case "command": case "network": case "pref": case "port": case "secret": case "pem-file": case "external-ca": case "node-addr": case "ulimit": case "filter": case "duration": case "config": default: return("string"); } }
public void SetNonGenericType() { // arrange var descriptor = new ArgumentDescriptor(Context, "Type"); // act descriptor.Type(typeof(StringType)); // assert ArgumentDefinition description = descriptor.CreateDefinition(); ITypeReference typeRef = description.Type; Assert.Equal( typeof(StringType), Assert.IsType <ExtendedTypeReference>(typeRef).Type.Source); }