< Summary

Information
Class: NexusLabs.Needlr.Generators.HttpClientOptionsAttributeHelper
Assembly: NexusLabs.Needlr.Generators
File(s): /home/runner/work/needlr/needlr/src/NexusLabs.Needlr.Generators/HttpClientOptionsAttributeHelper.cs
Line coverage
98%
Covered lines: 98
Uncovered lines: 1
Coverable lines: 99
Total lines: 318
Line coverage: 98.9%
Branch coverage
95%
Covered branches: 97
Total branches: 102
Branch coverage: 95%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%11100%
.ctor(...)100%11100%
get_SectionName()100%11100%
get_Name()100%11100%
get_AttributeLocation()100%11100%
GetHttpClientOptionsAttribute(...)93.75%1616100%
DetectCapabilities(...)92.85%1414100%
ImplementsNamedHttpClientOptions(...)87.5%88100%
TryResolveClientName(...)100%66100%
InferClientNameFromTypeName(...)100%44100%
TryGetClientNameProperty(...)100%4242100%
ResolveSectionName(...)100%22100%
GetClientNamePropertySymbol(...)100%44100%
IsHttpClientOptionsAttribute(...)66.66%7675%

File(s)

/home/runner/work/needlr/needlr/src/NexusLabs.Needlr.Generators/HttpClientOptionsAttributeHelper.cs

#LineLine coverage
 1using Microsoft.CodeAnalysis;
 2using Microsoft.CodeAnalysis.CSharp;
 3using Microsoft.CodeAnalysis.CSharp.Syntax;
 4
 5using NexusLabs.Needlr.Generators.Models;
 6
 7namespace NexusLabs.Needlr.Generators;
 8
 9/// <summary>
 10/// Helper for discovering <c>[HttpClientOptions]</c> attributes and the associated
 11/// capability interfaces on Roslyn symbols. Also resolves the HttpClient name from the
 12/// three supported sources (attribute argument, <c>ClientName</c> property, type-name
 13/// inference).
 14/// </summary>
 15internal static class HttpClientOptionsAttributeHelper
 16{
 17    private const string HttpClientOptionsAttributeName = "HttpClientOptionsAttribute";
 18    private const string GeneratorsNamespace = "NexusLabs.Needlr.Generators";
 19
 20    private const string INamedHttpClientOptionsName = "INamedHttpClientOptions";
 21    private const string IHttpClientTimeoutName = "IHttpClientTimeout";
 22    private const string IHttpClientUserAgentName = "IHttpClientUserAgent";
 23    private const string IHttpClientBaseAddressName = "IHttpClientBaseAddress";
 24    private const string IHttpClientDefaultHeadersName = "IHttpClientDefaultHeaders";
 25
 26    /// <summary>Suffixes stripped from the type name (in order) when inferring the client name.</summary>
 127    private static readonly string[] ClientNameSuffixes = ["HttpClientOptions", "HttpClientSettings", "HttpClient"];
 28
 29    /// <summary>
 30    /// Extracted state from an <c>[HttpClientOptions]</c> attribute on a type.
 31    /// </summary>
 32    public readonly struct HttpClientOptionsAttributeInfo
 33    {
 34        public HttpClientOptionsAttributeInfo(string? sectionName, string? name, Location? attributeLocation)
 35        {
 3536            SectionName = sectionName;
 3537            Name = name;
 3538            AttributeLocation = attributeLocation;
 3539        }
 40
 41        /// <summary>Explicit section name from the attribute, or null to infer.</summary>
 1142        public string? SectionName { get; }
 43
 44        /// <summary>Explicit client name override from the attribute, or null to fall through.</summary>
 7145        public string? Name { get; }
 46
 47        /// <summary>Source location of the attribute, used for analyzer diagnostics.</summary>
 2448        public Location? AttributeLocation { get; }
 49    }
 50
 51    /// <summary>
 52    /// Extracts the <c>[HttpClientOptions]</c> attribute info from a type, or <c>null</c>
 53    /// if the attribute is not present.
 54    /// </summary>
 55    public static HttpClientOptionsAttributeInfo? GetHttpClientOptionsAttribute(INamedTypeSymbol typeSymbol)
 56    {
 760122957        foreach (var attribute in typeSymbol.GetAttributes())
 58        {
 221866559            if (!IsHttpClientOptionsAttribute(attribute.AttributeClass))
 60                continue;
 61
 3562            string? sectionName = null;
 3563            if (attribute.ConstructorArguments.Length > 0 &&
 3564                attribute.ConstructorArguments[0].Value is string section)
 65            {
 166                sectionName = section;
 67            }
 68
 3569            string? name = null;
 9470            foreach (var namedArg in attribute.NamedArguments)
 71            {
 1272                if (namedArg.Key == "Name" && namedArg.Value.Value is string n)
 73                {
 1274                    name = n;
 75                }
 76            }
 77
 3578            var location = attribute.ApplicationSyntaxReference?.GetSyntax().GetLocation();
 3579            return new HttpClientOptionsAttributeInfo(sectionName, name, location);
 80        }
 81
 158193282        return null;
 83    }
 84
 85    /// <summary>
 86    /// Detects which v1 capability interfaces the type implements. Returns a bit flag set
 87    /// which drives the conditional emission in <c>HttpClientCodeGenerator</c>.
 88    /// </summary>
 89    public static HttpClientCapabilities DetectCapabilities(INamedTypeSymbol typeSymbol)
 90    {
 1091        var caps = HttpClientCapabilities.None;
 92
 5093        foreach (var iface in typeSymbol.AllInterfaces)
 94        {
 1595            if (iface.ContainingNamespace?.ToDisplayString() != GeneratorsNamespace)
 96                continue;
 97
 1598            switch (iface.Name)
 99            {
 100                case IHttpClientTimeoutName:
 1101                    caps |= HttpClientCapabilities.Timeout;
 1102                    break;
 103                case IHttpClientUserAgentName:
 1104                    caps |= HttpClientCapabilities.UserAgent;
 1105                    break;
 106                case IHttpClientBaseAddressName:
 1107                    caps |= HttpClientCapabilities.BaseAddress;
 1108                    break;
 109                case IHttpClientDefaultHeadersName:
 1110                    caps |= HttpClientCapabilities.Headers;
 111                    break;
 112            }
 113        }
 114
 10115        return caps;
 116    }
 117
 118    /// <summary>
 119    /// Returns <c>true</c> if the type implements <c>INamedHttpClientOptions</c>.
 120    /// </summary>
 121    public static bool ImplementsNamedHttpClientOptions(INamedTypeSymbol typeSymbol)
 122    {
 70123        foreach (var iface in typeSymbol.AllInterfaces)
 124        {
 22125            if (iface.Name == INamedHttpClientOptionsName &&
 22126                iface.ContainingNamespace?.ToDisplayString() == GeneratorsNamespace)
 127            {
 22128                return true;
 129            }
 130        }
 131
 2132        return false;
 133    }
 134
 135    /// <summary>
 136    /// Resolves the HttpClient name from the three allowed sources, in precedence order:
 137    /// (1) attribute <c>Name</c>, (2) <c>ClientName</c> property literal body,
 138    /// (3) inferred from type name with suffix stripping.
 139    /// </summary>
 140    /// <param name="typeSymbol">The options type.</param>
 141    /// <param name="attributeInfo">The extracted attribute info for the type.</param>
 142    /// <param name="propertyNameFromType">
 143    /// The literal <c>ClientName</c> property value if present and resolvable, or <c>null</c>.
 144    /// </param>
 145    /// <param name="resolvedName">The resolved client name on success.</param>
 146    /// <returns><c>true</c> if a non-empty name could be resolved; otherwise <c>false</c>.</returns>
 147    public static bool TryResolveClientName(
 148        INamedTypeSymbol typeSymbol,
 149        HttpClientOptionsAttributeInfo attributeInfo,
 150        string? propertyNameFromType,
 151        out string resolvedName)
 152    {
 35153        if (!string.IsNullOrWhiteSpace(attributeInfo.Name))
 154        {
 12155            resolvedName = attributeInfo.Name!;
 12156            return true;
 157        }
 158
 23159        if (!string.IsNullOrWhiteSpace(propertyNameFromType))
 160        {
 6161            resolvedName = propertyNameFromType!;
 6162            return true;
 163        }
 164
 17165        var inferred = InferClientNameFromTypeName(typeSymbol.Name);
 17166        if (!string.IsNullOrWhiteSpace(inferred))
 167        {
 10168            resolvedName = inferred;
 10169            return true;
 170        }
 171
 7172        resolvedName = string.Empty;
 7173        return false;
 174    }
 175
 176    /// <summary>
 177    /// Strips known suffixes from a type name to infer a client name.
 178    /// Returns the original name if no suffix matches.
 179    /// </summary>
 180    public static string InferClientNameFromTypeName(string typeName)
 181    {
 94182        foreach (var suffix in ClientNameSuffixes)
 183        {
 36184            if (typeName.EndsWith(suffix, System.StringComparison.Ordinal))
 185            {
 12186                return typeName.Substring(0, typeName.Length - suffix.Length);
 187            }
 188        }
 189
 5190        return typeName;
 191    }
 192
 193    /// <summary>
 194    /// Attempts to read a <c>ClientName</c> property from the type and extract its literal
 195    /// expression value. Returns a tri-state:
 196    /// <list type="bullet">
 197    /// <item><description><c>Absent</c> — no <c>ClientName</c> property declared</description></item>
 198    /// <item><description><c>Literal</c> — <c>ClientName</c> exists with a string literal expression body; value is in 
 199    /// <item><description><c>NonLiteral</c> — <c>ClientName</c> exists but its body is not a simple literal (e.g., comp
 200    /// </list>
 201    /// </summary>
 202    public static ClientNamePropertyResult TryGetClientNameProperty(
 203        INamedTypeSymbol typeSymbol,
 204        out string? literalValue)
 205    {
 35206        literalValue = null;
 35207        IPropertySymbol? clientNameProp = null;
 208
 83209        foreach (var member in typeSymbol.GetMembers("ClientName"))
 210        {
 13211            if (member is IPropertySymbol p)
 212            {
 13213                clientNameProp = p;
 13214                break;
 215            }
 216        }
 217
 35218        if (clientNameProp is null)
 22219            return ClientNamePropertyResult.Absent;
 220
 221        // Must be a string-typed, readable, instance property — otherwise treat as non-literal
 222        // and let the analyzer handle it (NDLRHTTP006 fires on shape violations).
 13223        if (clientNameProp.Type.SpecialType != SpecialType.System_String || clientNameProp.IsStatic)
 2224            return ClientNamePropertyResult.NonLiteral;
 225
 36226        foreach (var declRef in clientNameProp.DeclaringSyntaxReferences)
 227        {
 11228            var syntax = declRef.GetSyntax();
 11229            if (syntax is not PropertyDeclarationSyntax propSyntax)
 230                continue;
 231
 232            // Expression-bodied arrow form: public string ClientName => "WebFetch";
 11233            if (propSyntax.ExpressionBody is ArrowExpressionClauseSyntax arrow &&
 11234                arrow.Expression is LiteralExpressionSyntax exprLit &&
 11235                exprLit.IsKind(SyntaxKind.StringLiteralExpression))
 236            {
 4237                literalValue = exprLit.Token.ValueText;
 4238                return ClientNamePropertyResult.Literal;
 239            }
 240
 241            // Getter-only body form: public string ClientName { get { return "WebFetch"; } }
 7242            if (propSyntax.AccessorList is { } accessors)
 243            {
 12244                foreach (var accessor in accessors.Accessors)
 245                {
 4246                    if (!accessor.IsKind(SyntaxKind.GetAccessorDeclaration))
 247                        continue;
 248
 249                    // Expression body on getter
 4250                    if (accessor.ExpressionBody is ArrowExpressionClauseSyntax getArrow &&
 4251                        getArrow.Expression is LiteralExpressionSyntax getExprLit &&
 4252                        getExprLit.IsKind(SyntaxKind.StringLiteralExpression))
 253                    {
 2254                        literalValue = getExprLit.Token.ValueText;
 2255                        return ClientNamePropertyResult.Literal;
 256                    }
 257
 258                    // Single-return block body
 2259                    if (accessor.Body is { } block &&
 2260                        block.Statements.Count == 1 &&
 2261                        block.Statements[0] is ReturnStatementSyntax ret &&
 2262                        ret.Expression is LiteralExpressionSyntax retLit &&
 2263                        retLit.IsKind(SyntaxKind.StringLiteralExpression))
 264                    {
 2265                        literalValue = retLit.Token.ValueText;
 2266                        return ClientNamePropertyResult.Literal;
 267                    }
 268                }
 269            }
 270        }
 271
 3272        return ClientNamePropertyResult.NonLiteral;
 273    }
 274
 275    /// <summary>
 276    /// Computes the configuration section name from the attribute (if explicit) or by inference
 277    /// from the resolved client name.
 278    /// </summary>
 279    public static string ResolveSectionName(HttpClientOptionsAttributeInfo attributeInfo, string clientName)
 280    {
 10281        if (!string.IsNullOrWhiteSpace(attributeInfo.SectionName))
 1282            return attributeInfo.SectionName!;
 283
 9284        return $"HttpClients:{clientName}";
 285    }
 286
 287    /// <summary>
 288    /// Returns the symbol for the <c>ClientName</c> property if present, for analyzer shape checks.
 289    /// </summary>
 290    public static IPropertySymbol? GetClientNamePropertySymbol(INamedTypeSymbol typeSymbol)
 291    {
 58292        foreach (var member in typeSymbol.GetMembers("ClientName"))
 293        {
 10294            if (member is IPropertySymbol p)
 10295                return p;
 296        }
 14297        return null;
 298    }
 299
 300    private static bool IsHttpClientOptionsAttribute(INamedTypeSymbol? attributeClass)
 301    {
 2218665302        if (attributeClass is null)
 0303            return false;
 304
 2218665305        return attributeClass.Name == HttpClientOptionsAttributeName &&
 2218665306               attributeClass.ContainingNamespace?.ToDisplayString() == GeneratorsNamespace;
 307    }
 308}
 309
 310/// <summary>
 311/// Tri-state result from probing a type for a <c>ClientName</c> property.
 312/// </summary>
 313internal enum ClientNamePropertyResult
 314{
 315    Absent,
 316    Literal,
 317    NonLiteral,
 318}