public override void Refine(CodeNamespace generatedCode) { ReplaceIndexersByMethodsWithParameter(generatedCode, generatedCode, false, "_by_id"); AddPropertiesAndMethodTypesImports(generatedCode, false, false, false); RemoveCancellationParameter(generatedCode); AddParsableImplementsForModelClasses(generatedCode, "MicrosoftKiotaAbstractions::Parsable"); AddInheritedAndMethodTypesImports(generatedCode); AddDefaultImports(generatedCode, defaultUsingEvaluators); CorrectCoreType(generatedCode, null, CorrectPropertyType); AddGetterAndSetterMethods(generatedCode, new() { CodePropertyKind.Custom, CodePropertyKind.AdditionalData, CodePropertyKind.BackingStore, }, _configuration.UsesBackingStore, true, string.Empty, string.Empty); ReplaceReservedNames(generatedCode, new RubyReservedNamesProvider(), x => $"{x}_escaped"); AddNamespaceModuleImports(generatedCode, _configuration.ClientNamespaceName); FixInheritedEntityType(generatedCode); var defaultConfiguration = new GenerationConfiguration(); ReplaceDefaultSerializationModules( generatedCode, defaultConfiguration.Serializers, new (StringComparer.OrdinalIgnoreCase) { "microsoft_kiota_serialization.JsonSerializationWriterFactory" });
public static CodeRenderer GetCodeRender(GenerationConfiguration config) { return(config.Language switch { GenerationLanguage.TypeScript => new TypeScriptCodeRenderer(config), _ => new CodeRenderer(config), });
public void TestSetup() { IEngineConfiguration configuration = new EngineConfiguration(); IEngineConventionProvider conventionProvider = new Mock <IEngineConventionProvider>().Object; GenerationConfiguration repository = new GenerationConfiguration(configuration, conventionProvider, 10); configuration.RegisterType(typeof(SimpleUser)); mGenerationSession = new GenerationContext(repository); }
private static void Main(string[] args) { Console.WriteLine("==============" + AppDomain.CurrentDomain.BaseDirectory); Console.WriteLine("TypeScriptGenerator DOTNET4.5 Stated: " + DateTime.Now.ToString("HH:mm:ss")); Console.WriteLine("CommandLine: " + string.Join(" ", args)); var options = new Options(); if (Parser.Default.ParseArguments(args, options)) { Console.WriteLine("Assemblies: "); foreach (var a in options.Assemblies) { Console.WriteLine(" - " + a); } Console.WriteLine("OutputPath: " + options.OutputFilePath); if (options.AttachDebugger) { Debugger.Launch(); Debugger.Break(); } var configuration = new GenerationConfiguration(); configuration.ControllerPredicate = t => typeof(ApiController).IsAssignableFrom(t); configuration.ActionsPredicate = m => m.IsPublic; configuration.SignalRGenerator = new SignalRGenerator(); configuration.GetActionParameters = GetActionParameters; configuration.UrlGenerator = new WebApiUrlGenerator(); var mainGenerator = new MainGenerator(options, configuration); mainGenerator.SetupWorkingFolder(); mainGenerator.GenerateTypeScriptContracts(); mainGenerator.GenerateSignalrHubs(); if (options.GenerateWebApiActions) { switch (options.ActionsStyle) { case ActionsStyle.Default: mainGenerator.GenerateWebApiActions(); break; case ActionsStyle.Aurelia: mainGenerator.GenerateAureliWebApiActions(); break; default: throw new ArgumentOutOfRangeException(); } } } else { Console.WriteLine("TypeScriptGenerator: Could not parse args: " + string.Join(" ", args)); } Console.WriteLine("TypeScriptGenerator Finished: " + DateTime.Now.ToString("HH:mm:ss")); }
public async Task GeneratesTodo(GenerationLanguage language, bool backingStore) { var logger = LoggerFactory.Create((builder) => { }).CreateLogger <KiotaBuilder>(); var backingStoreSuffix = backingStore ? string.Empty : "BackingStore"; var configuration = new GenerationConfiguration { Language = language, OpenAPIFilePath = "ToDoApi.yaml", OutputPath = $".\\Generated\\Todo\\{language}{backingStoreSuffix}", UsesBackingStore = backingStore, }; await new KiotaBuilder(logger, configuration).GenerateSDK(new()); }
public async Task GeneratesResponseWithMultipleReturnFormats(GenerationLanguage language, bool backingStore) { var logger = LoggerFactory.Create((builder) => { }).CreateLogger <KiotaBuilder>(); var backingStoreSuffix = backingStore ? "BackingStore" : string.Empty; var configuration = new GenerationConfiguration { Language = language, OpenAPIFilePath = "ResponseWithMultipleReturnFormats.yaml", OutputPath = $".\\Generated\\ResponseWithMultipleReturnFormats\\{language}{backingStoreSuffix}", UsesBackingStore = backingStore, }; await new KiotaBuilder(logger, configuration).GenerateSDK(new()); }
public void GetsResponseSchema() { var operation = new OpenApiOperation { Responses = new() { { "200", new() { Content = new Dictionary <string, OpenApiMediaType> { { "application/json", new() { Schema = new() } } } } } } }; var operation2 = new OpenApiOperation { Responses = new() { { "400", new() { Content = new Dictionary <string, OpenApiMediaType> { { "application/json", new() { Schema = new() } } } } } } }; var operation3 = new OpenApiOperation { Responses = new() { { "200", new() { Content = new Dictionary <string, OpenApiMediaType> { { "application/invalid", new() { Schema = new() } } } } } } }; var defaultConfiguration = new GenerationConfiguration(); Assert.NotNull(operation.GetResponseSchema(defaultConfiguration.StructuredMimeTypes)); Assert.Null(operation2.GetResponseSchema(defaultConfiguration.StructuredMimeTypes)); Assert.Null(operation3.GetResponseSchema(defaultConfiguration.StructuredMimeTypes)); }
public override void Refine(CodeNamespace generatedCode) { ReplaceIndexersByMethodsWithParameter(generatedCode, generatedCode, false, "ById"); RemoveCancellationParameter(generatedCode); CorrectCoreType(generatedCode, CorrectMethodType, CorrectPropertyType, CorrectImplements); CorrectCoreTypesForBackingStore(generatedCode, "BackingStoreFactorySingleton.instance.createBackingStore()"); AddInnerClasses(generatedCode, true, string.Empty, true); // `AddInnerClasses` will have inner classes moved to their own files, so we add the imports after so that the files don't miss anything. // This is because imports are added at the file level so nested classes would potentially use the higher level imports. AddDefaultImports(generatedCode, defaultUsingEvaluators); DisableActionOf(generatedCode, CodeParameterKind.RequestConfiguration); AddPropertiesAndMethodTypesImports(generatedCode, true, true, true); AliasUsingsWithSameSymbol(generatedCode); AddParsableImplementsForModelClasses(generatedCode, "Parsable"); ReplaceBinaryByNativeType(generatedCode, "ArrayBuffer", null); ReplaceReservedNames(generatedCode, new TypeScriptReservedNamesProvider(), x => $"{x}_escaped"); AddGetterAndSetterMethods(generatedCode, new() { CodePropertyKind.Custom, CodePropertyKind.AdditionalData, }, _configuration.UsesBackingStore, false, string.Empty, string.Empty); AddConstructorsForDefaultValues(generatedCode, true); var defaultConfiguration = new GenerationConfiguration(); ReplaceDefaultSerializationModules( generatedCode, defaultConfiguration.Serializers, new (StringComparer.OrdinalIgnoreCase) { "@microsoft/kiota-serialization-json.JsonSerializationWriterFactory", "@microsoft/kiota-serialization-text.TextSerializationWriterFactory" }
public override void Refine(CodeNamespace generatedCode) { LowerCaseNamespaceNames(generatedCode); AddInnerClasses(generatedCode, false, string.Empty); InsertOverrideMethodForRequestExecutorsAndBuildersAndConstructors(generatedCode); ReplaceIndexersByMethodsWithParameter(generatedCode, generatedCode, true); RemoveCancellationParameter(generatedCode); ConvertUnionTypesToWrapper(generatedCode, _configuration.UsesBackingStore); AddRawUrlConstructorOverload(generatedCode); CorrectCoreType(generatedCode, CorrectMethodType, CorrectPropertyType, CorrectImplements); ReplaceBinaryByNativeType(generatedCode, "InputStream", "java.io", true); AddGetterAndSetterMethods(generatedCode, new() { CodePropertyKind.Custom, CodePropertyKind.AdditionalData, CodePropertyKind.BackingStore, }, _configuration.UsesBackingStore, true, "get", "set" ); ReplaceReservedNames(generatedCode, new JavaReservedNamesProvider(), x => $"{x}_escaped"); AddPropertiesAndMethodTypesImports(generatedCode, true, false, true); AddDefaultImports(generatedCode, defaultUsingEvaluators); AddParsableImplementsForModelClasses(generatedCode, "Parsable"); AddEnumSetImport(generatedCode); SetSetterParametersToNullable(generatedCode, new Tuple <CodeMethodKind, CodePropertyKind>(CodeMethodKind.Setter, CodePropertyKind.AdditionalData)); AddConstructorsForDefaultValues(generatedCode, true); CorrectCoreTypesForBackingStore(generatedCode, "BackingStoreFactorySingleton.instance.createBackingStore()"); var defaultConfiguration = new GenerationConfiguration(); ReplaceDefaultSerializationModules( generatedCode, defaultConfiguration.Serializers, new (StringComparer.OrdinalIgnoreCase) { "com.microsoft.kiota.serialization.JsonSerializationWriterFactory", "com.microsoft.kiota.serialization.TextSerializationWriterFactory" }
static void Main(string[] args) { Console.WriteLine("==============" + AppDomain.CurrentDomain.BaseDirectory); Console.WriteLine("TypeScriptGenerator.Core Stated: " + DateTime.Now.ToString("HH:mm:ss")); Console.WriteLine("CommandLine: " + string.Join(" ", args)); var options = new Options(); if (CommandLine.Parser.Default.ParseArguments(args, options)) { Console.WriteLine("Assemblies: "); foreach (var a in options.Assemblies) { Console.WriteLine(" - " + a); } Console.WriteLine("OutputPath: " + options.OutputFilePath); if (options.AttachDebugger) { Debugger.Launch(); Debugger.Break(); } var configuration = new GenerationConfiguration(); configuration.ControllerPredicate = t => typeof(ControllerBase).IsAssignableFrom(t); configuration.ActionsPredicate = m => m.IsPublic && !typeof(IActionResult).IsAssignableFrom(m.ReturnType) && !typeof(Task <IActionResult>).IsAssignableFrom(m.ReturnType) && !typeof(Task <ActionResult>).IsAssignableFrom(m.ReturnType) && !typeof(HttpResponseMessage).IsAssignableFrom(m.ReturnType) && !typeof(Task <HttpResponseMessage>).IsAssignableFrom(m.ReturnType); configuration.SignalRGenerator = new SignalRGenerator(); configuration.GetActionParameters = GetActionParameters; configuration.UrlGenerator = new WebApiUrlGenerator(); var mainGenerator = new MainGenerator(options, configuration); mainGenerator.SetupWorkingFolder(); try { // TODO: Inspect the <assembly>.runtimeconfig.dev.json file to find places where packages can be loaded (see DependencyContext API?) mainGenerator.GenerateTypeScriptContracts(); } catch (ReflectionTypeLoadException ex) { Console.WriteLine("Reflection errors:"); foreach (var x in ex.LoaderExceptions) { Console.WriteLine(x.Message); } Console.WriteLine("***You might be able to fix this by adding: <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> to your csproj file, until I figure out how to " + "use the deps.json / runtimeconfig.json files to load referenced assemblies automatically."); throw; } mainGenerator.GenerateSignalrHubs(); if (options.GenerateWebApiActions) { switch (options.ActionsStyle) { case ActionsStyle.Default: mainGenerator.GenerateWebApiActions(); break; case ActionsStyle.Aurelia: mainGenerator.GenerateAureliWebApiActions(); break; default: throw new ArgumentOutOfRangeException(); } } } else { Console.WriteLine("TypeScriptGenerator: Could not parse args: " + string.Join(" ", args)); } Console.WriteLine("TypeScriptGenerator Finished: " + DateTime.Now.ToString("HH:mm:ss")); }
public SwiftRefiner(GenerationConfiguration configuration) : base(configuration) { }
public RootCommand GetRootCommand() { var kiotaInContainerRaw = Environment.GetEnvironmentVariable("KIOTA_CONTAINER"); var defaultConfiguration = new GenerationConfiguration(); var runsInContainer = !string.IsNullOrEmpty(kiotaInContainerRaw) && bool.TryParse(kiotaInContainerRaw, out var kiotaInContainer) && kiotaInContainer; var descriptionOption = new Option <string>("--openapi", "The path to the OpenAPI description file used to generate the code files."); if (runsInContainer) { descriptionOption.SetDefaultValue(defaultConfiguration.OpenAPIFilePath); } else { descriptionOption.IsRequired = true; } descriptionOption.AddAlias("-d"); descriptionOption.ArgumentHelpName = "path"; var outputOption = new Option <string>("--output", () => defaultConfiguration.OutputPath, "The output directory path for the generated code files."); outputOption.AddAlias("-o"); outputOption.ArgumentHelpName = "path"; var languageOption = new Option <GenerationLanguage>("--language", "The target language for the generated code files."); languageOption.AddAlias("-l"); languageOption.IsRequired = true; AddEnumValidator(languageOption, "language"); var classOption = new Option <string>("--class-name", () => defaultConfiguration.ClientClassName, "The class name to use for the core client class."); classOption.AddAlias("-c"); classOption.ArgumentHelpName = "name"; AddStringRegexValidator(classOption, @"^[a-zA-Z_][\w_-]+", "class name"); var namespaceOption = new Option <string>("--namespace-name", () => defaultConfiguration.ClientNamespaceName, "The namespace to use for the core client class specified with the --class-name option."); namespaceOption.AddAlias("-n"); namespaceOption.ArgumentHelpName = "name"; AddStringRegexValidator(namespaceOption, @"^[\w][\w\._-]+", "namespace name"); var logLevelOption = new Option <LogLevel>("--log-level", () => LogLevel.Warning, "The log level to use when logging messages to the main output."); logLevelOption.AddAlias("--ll"); AddEnumValidator(logLevelOption, "log level"); var backingStoreOption = new Option <bool>("--backing-store", () => defaultConfiguration.UsesBackingStore, "Enables backing store for models."); backingStoreOption.AddAlias("-b"); var serializerOption = new Option <List <string> >( "--serializer", () => defaultConfiguration.Serializers.ToList(), "The fully qualified class names for serializers. Accepts multiple values."); serializerOption.AddAlias("-s"); serializerOption.ArgumentHelpName = "classes"; var deserializerOption = new Option <List <string> >( "--deserializer", () => defaultConfiguration.Deserializers.ToList(), "The fully qualified class names for deserializers. Accepts multiple values."); deserializerOption.AddAlias("--ds"); deserializerOption.ArgumentHelpName = "classes"; var cleanOutputOption = new Option <bool>("--clean-output", () => defaultConfiguration.CleanOutput, "Removes all files from the output directory before generating the code files."); cleanOutputOption.AddAlias("--co"); var structuredMimeTypesOption = new Option <List <string> >( "--structured-mime-types", () => defaultConfiguration.StructuredMimeTypes.ToList(), "The MIME types to use for structured data model generation. Accepts multiple values."); structuredMimeTypesOption.AddAlias("-m"); var command = new RootCommand { descriptionOption, outputOption, languageOption, classOption, namespaceOption, logLevelOption, backingStoreOption, serializerOption, deserializerOption, cleanOutputOption, structuredMimeTypesOption }; command.Description = "OpenAPI-based HTTP Client SDK code generator"; command.Handler = new KiotaCommandHandler { DescriptionOption = descriptionOption, OutputOption = outputOption, LanguageOption = languageOption, ClassOption = classOption, NamespaceOption = namespaceOption, LogLevelOption = logLevelOption, BackingStoreOption = backingStoreOption, SerializerOption = serializerOption, DeserializerOption = deserializerOption, CleanOutputOption = cleanOutputOption, StructuredMimeTypesOption = structuredMimeTypesOption }; return(command); }
public GoRefiner(GenerationConfiguration configuration) : base(configuration) { }
public override void Refine(CodeNamespace generatedCode) { _configuration.NamespaceNameSeparator = "/"; AddInnerClasses( generatedCode, true, null); ReplaceIndexersByMethodsWithParameter( generatedCode, generatedCode, false, "ById"); RemoveCancellationParameter(generatedCode); RemoveDiscriminatorMappingsTargetingSubNamespaces(generatedCode); ReplaceRequestBuilderPropertiesByMethods( generatedCode ); ConvertUnionTypesToWrapper( generatedCode, _configuration.UsesBackingStore ); AddRawUrlConstructorOverload( generatedCode ); RemoveModelPropertiesThatDependOnSubNamespaces( generatedCode ); ReplaceReservedNames( generatedCode, new GoReservedNamesProvider(), x => $"{x}_escaped", shouldReplaceCallback: x => x is not CodeProperty currentProp || !(currentProp.Parent is CodeClass parentClass && parentClass.IsOfKind(CodeClassKind.QueryParameters, CodeClassKind.ParameterSet) && currentProp.Access == AccessModifier.Public)); // Go reserved keywords are all lowercase and public properties are uppercased when we don't provide accessors (models) AddPropertiesAndMethodTypesImports( generatedCode, true, false, true); AddDefaultImports( generatedCode, defaultUsingEvaluators); CorrectCoreType( generatedCode, CorrectMethodType, CorrectPropertyType, CorrectImplements); InsertOverrideMethodForRequestExecutorsAndBuildersAndConstructors(generatedCode); DisableActionOf(generatedCode, CodeParameterKind.RequestConfiguration); AddGetterAndSetterMethods( generatedCode, new () { CodePropertyKind.AdditionalData, CodePropertyKind.Custom, CodePropertyKind.BackingStore }, _configuration.UsesBackingStore, false, "Get", "Set"); AddConstructorsForDefaultValues( generatedCode, true, true, //forcing add as constructors are required for by factories new CodeClassKind[] { CodeClassKind.RequestConfiguration }); MakeModelPropertiesNullable( generatedCode); AddErrorImportForEnums( generatedCode); var defaultConfiguration = new GenerationConfiguration(); ReplaceDefaultSerializationModules( generatedCode, defaultConfiguration.Serializers, new (StringComparer.OrdinalIgnoreCase) { "github.com/microsoft/kiota-serialization-json-go.JsonSerializationWriterFactory", "github.com/microsoft/kiota-serialization-text-go.TextSerializationWriterFactory" });
public ShellRefiner(GenerationConfiguration configuration) : base(configuration) { }
protected CommonLanguageRefiner(GenerationConfiguration configuration) { _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); }
public CSharpRefiner(GenerationConfiguration configuration) : base(configuration) { }
public TypeScriptRefiner(GenerationConfiguration configuration) : base(configuration) { }
static void Main(string[] args) { Console.WriteLine("==============" + AppDomain.CurrentDomain.BaseDirectory); Console.WriteLine("TypeScriptGenerator.Core Stated: " + DateTime.Now.ToString("HH:mm:ss")); Console.WriteLine("CommandLine: " + string.Join(" ", args)); var options = new Options(); if (CommandLine.Parser.Default.ParseArguments(args, options)) { Console.WriteLine("Assemblies: "); foreach (var a in options.Assemblies) { Console.WriteLine(" - " + a); } Console.WriteLine("OutputPath: " + options.OutputFilePath); if (options.AttachDebugger) { Debugger.Launch(); Debugger.Break(); } var configuration = new GenerationConfiguration(); configuration.ControllerPredicate = t => { // Dynamically check types, as might not be using AspNetCore (might be ServiceStack for example). Note that namespace moved in core v3 var controllerBaseType = Type.GetType("Microsoft.AspNetCore.Mvc.Core.ControllerBase, Microsoft.AspNetCore.Mvc.Core") ?? Type.GetType("Microsoft.AspNetCore.Mvc.ControllerBase, Microsoft.AspNetCore.Mvc.Core"); if (controllerBaseType == null) { return(false); } return(controllerBaseType.IsAssignableFrom(t)); }; configuration.ActionsPredicate = m => { var iActionResultType = Type.GetType("Microsoft.AspNetCore.Mvc.IActionResult, Microsoft.AspNetCore.Mvc.Abstractions"); if (iActionResultType == null) { return(false); } var genericTaskType = typeof(Task <>); var iActionResultTypeTask = genericTaskType.MakeGenericType(Type.GetType("Microsoft.AspNetCore.Mvc.IActionResult, Microsoft.AspNetCore.Mvc.Abstractions")); var actionResultTypeTask = genericTaskType.MakeGenericType(Type.GetType("Microsoft.AspNetCore.Mvc.ActionResult, Microsoft.AspNetCore.Mvc.Core")); var httpResponseMessageType = Type.GetType("System.Net.Http.HttpResponseMessage, System.Net.Http"); var httpResponseMessageTypeTask = genericTaskType.MakeGenericType(httpResponseMessageType); return(m.IsPublic && !iActionResultType.IsAssignableFrom(m.ReturnType) && !iActionResultTypeTask.IsAssignableFrom(m.ReturnType) && !actionResultTypeTask.IsAssignableFrom(m.ReturnType) && !httpResponseMessageType.IsAssignableFrom(m.ReturnType) && !httpResponseMessageTypeTask.IsAssignableFrom(m.ReturnType)); }; configuration.SignalRGenerator = new SignalRGenerator(options); configuration.GetActionParameters = WebApiUrlGenerator.GetActionParameters; configuration.UrlGenerator = new WebApiUrlGenerator(); options.SupportMomentJs = true; var mainGenerator = new MainGenerator(options, configuration); mainGenerator.SetupWorkingFolder(); try { // TODO: Inspect the <assembly>.runtimeconfig.dev.json file to find places where packages can be loaded (see DependencyContext API?) mainGenerator.GenerateTypeScriptContracts(); } catch (ReflectionTypeLoadException ex) { Console.WriteLine("Reflection errors:"); foreach (var x in ex.LoaderExceptions) { Console.WriteLine(x.Message); } Console.WriteLine("***You might be able to fix this by adding: <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> to your csproj file, until I figure out how to " + "use the deps.json / runtimeconfig.json files to load referenced assemblies automatically."); throw; } mainGenerator.GenerateSignalrHubs(); mainGenerator.GenerateServiceCallProxies(); } else { Console.WriteLine("TypeScriptGenerator: Could not parse args: " + string.Join(" ", args)); } Console.WriteLine("TypeScriptGenerator Finished: " + DateTime.Now.ToString("HH:mm:ss")); }
public CodeRenderer(GenerationConfiguration configuration) { _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); _rendererElementComparer = configuration.ShouldRenderMethodsOutsideOfClasses ? new CodeElementOrderComparerWithExternalMethods() : new CodeElementOrderComparer(); }
public TypeScriptCodeRenderer(GenerationConfiguration configuration) : base(configuration) { }