openai/openai-dotnet
Publicmirrored from https://github.com/openai/openai-dotnetAvailable
codegen/generator/src/Visitors/ProhibitedNamespaceVisitor.cs
41lines · modecode
| 1 | using Microsoft.TypeSpec.Generator.ClientModel; |
| 2 | using Microsoft.TypeSpec.Generator.EmitterRpc; |
| 3 | using Microsoft.TypeSpec.Generator.Primitives; |
| 4 | using Microsoft.TypeSpec.Generator.Providers; |
| 5 | using System.Collections.Generic; |
| 6 | using System.Text; |
| 7 | |
| 8 | namespace OpenAILibraryPlugin.Visitors; |
| 9 | |
| 10 | /// <summary> |
| 11 | /// A visitor that throws an exception if a generated namespace is prohibited. This happens when a newly introduced |
| 12 | /// type isn't emplaced into its appropriate namespace. Custom code definitions, including stubs that only emplace in |
| 13 | /// namespaces, are exempt and will cause the generated code to be accepted. |
| 14 | /// </summary> |
| 15 | public class ProhibitedNamespaceVisitor : ScmLibraryVisitor |
| 16 | { |
| 17 | protected override TypeProvider VisitType(TypeProvider type) |
| 18 | { |
| 19 | HashSet<TypeProvider> violatingTypes = []; |
| 20 | |
| 21 | bool isPublicType = type.DeclarationModifiers.HasFlag(TypeSignatureModifiers.Public); |
| 22 | bool isUnknownPrefixedType = type.Type.Name.StartsWith("Unknown"); |
| 23 | |
| 24 | if ((isPublicType || isUnknownPrefixedType) |
| 25 | && (type.Type.Namespace == "OpenAI" || type.Type.Namespace == "OpenAI.Models") |
| 26 | && string.IsNullOrEmpty(type.CustomCodeView?.Type.Namespace) |
| 27 | && type.Type.Name != "OpenAIContext" |
| 28 | && !violatingTypes.Contains(type)) |
| 29 | { |
| 30 | violatingTypes.Add(type); |
| 31 | StringBuilder builder = new(); |
| 32 | builder.Append($"[CodeGenType(\"{type.Name}\")] internal "); |
| 33 | builder.Append(type.Type.IsValueType |
| 34 | ? "readonly partial struct " |
| 35 | : "partial class "); |
| 36 | builder.AppendLine($"Internal{type.Name} {{}}"); |
| 37 | OpenAILibraryGenerator.Instance.Emitter.ReportDiagnostic("prohibited-namespace", builder.ToString(), severity: EmitterDiagnosticSeverity.Error); |
| 38 | } |
| 39 | return type; |
| 40 | } |
| 41 | } |