| | | 1 | | namespace NexusLabs.Needlr.Generators.Helpers; |
| | | 2 | | |
| | | 3 | | /// <summary> |
| | | 4 | | /// Helper methods for inferring configuration section names from options class names. |
| | | 5 | | /// </summary> |
| | | 6 | | public static class OptionsNamingHelper |
| | | 7 | | { |
| | | 8 | | /// <summary> |
| | | 9 | | /// Common suffixes that are stripped when inferring section names. |
| | | 10 | | /// </summary> |
| | 1 | 11 | | private static readonly string[] Suffixes = ["Options", "Settings", "Config"]; |
| | | 12 | | |
| | | 13 | | /// <summary> |
| | | 14 | | /// Infers the configuration section name from a class name. |
| | | 15 | | /// Strips common suffixes (Options, Settings, Config) if present and the result is non-empty. |
| | | 16 | | /// </summary> |
| | | 17 | | /// <param name="className">The options class name.</param> |
| | | 18 | | /// <returns>The inferred section name.</returns> |
| | | 19 | | /// <example> |
| | | 20 | | /// <code> |
| | | 21 | | /// InferSectionName("DatabaseOptions") // returns "Database" |
| | | 22 | | /// InferSectionName("CacheSettings") // returns "Cache" |
| | | 23 | | /// InferSectionName("RedisConfig") // returns "Redis" |
| | | 24 | | /// InferSectionName("FeatureFlags") // returns "FeatureFlags" (no suffix match) |
| | | 25 | | /// InferSectionName("Options") // returns "Options" (would be empty after stripping) |
| | | 26 | | /// </code> |
| | | 27 | | /// </example> |
| | | 28 | | public static string InferSectionName(string className) |
| | | 29 | | { |
| | 443 | 30 | | foreach (var suffix in Suffixes) |
| | | 31 | | { |
| | 161 | 32 | | if (className.EndsWith(suffix, System.StringComparison.Ordinal) && |
| | 161 | 33 | | className.Length > suffix.Length) |
| | | 34 | | { |
| | 75 | 35 | | return className.Substring(0, className.Length - suffix.Length); |
| | | 36 | | } |
| | | 37 | | } |
| | 23 | 38 | | return className; |
| | | 39 | | } |
| | | 40 | | |
| | | 41 | | /// <summary> |
| | | 42 | | /// Gets the suffix that was matched and would be stripped from the class name, if any. |
| | | 43 | | /// </summary> |
| | | 44 | | /// <param name="className">The options class name.</param> |
| | | 45 | | /// <returns>The matched suffix, or null if no suffix matches.</returns> |
| | | 46 | | public static string? GetMatchedSuffix(string className) |
| | | 47 | | { |
| | 31 | 48 | | foreach (var suffix in Suffixes) |
| | | 49 | | { |
| | 12 | 50 | | if (className.EndsWith(suffix, System.StringComparison.Ordinal) && |
| | 12 | 51 | | className.Length > suffix.Length) |
| | | 52 | | { |
| | 3 | 53 | | return suffix; |
| | | 54 | | } |
| | | 55 | | } |
| | 2 | 56 | | return null; |
| | | 57 | | } |
| | | 58 | | } |