openai/openai-dotnet

Public

mirrored from https://github.com/openai/openai-dotnetAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
OpenAI_2.4.0

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

codegen/generator/src/Visitors/ProhibitedNamespaceVisitor.cs

41lines · modecode

1using Microsoft.TypeSpec.Generator.ClientModel;
2using Microsoft.TypeSpec.Generator.EmitterRpc;
3using Microsoft.TypeSpec.Generator.Primitives;
4using Microsoft.TypeSpec.Generator.Providers;
5using System.Collections.Generic;
6using System.Text;
7
8namespace 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>
15public 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}