| | | 1 | | using System.Management.Automation; |
| | | 2 | | using System.Management.Automation.Language; |
| | | 3 | | |
| | | 4 | | namespace Kestrun.OpenApi; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// Extension methods for FunctionInfo. |
| | | 8 | | /// </summary> |
| | | 9 | | public static class FunctionInfoExtensions |
| | | 10 | | { |
| | | 11 | | /// <summary> |
| | | 12 | | /// Gets the default value of a parameter in a FunctionInfo, if it has one. |
| | | 13 | | /// </summary> |
| | | 14 | | /// <param name="func">The FunctionInfo to inspect.</param> |
| | | 15 | | /// <param name="paramName">The name of the parameter.</param> |
| | | 16 | | /// <returns>The default value of the parameter, or null if none exists.</returns> |
| | | 17 | | public static object? GetDefaultParameterValue(this FunctionInfo func, string paramName) |
| | | 18 | | { |
| | 17 | 19 | | if (func.ScriptBlock?.Ast is not FunctionDefinitionAst fa) |
| | | 20 | | { |
| | 0 | 21 | | return null; |
| | | 22 | | } |
| | 17 | 23 | | if (fa.Body is not ScriptBlockAst scriptAst) |
| | | 24 | | { |
| | 0 | 25 | | return null; |
| | | 26 | | } |
| | | 27 | | // Find the ParameterAst for the given parameter name |
| | 17 | 28 | | var paramAst = scriptAst.ParamBlock?.Parameters |
| | 17 | 29 | | .OfType<ParameterAst>() |
| | 17 | 30 | | .FirstOrDefault(p => |
| | 37 | 31 | | p.Name?.VariablePath?.UserPath != null && |
| | 37 | 32 | | p.Name.VariablePath.UserPath.Equals(paramName, StringComparison.OrdinalIgnoreCase)); |
| | | 33 | | |
| | 17 | 34 | | if (paramAst?.DefaultValue is null) |
| | | 35 | | { |
| | 2 | 36 | | return null; // no default |
| | | 37 | | } |
| | | 38 | | |
| | 15 | 39 | | var defaultExpr = paramAst.DefaultValue; |
| | | 40 | | |
| | | 41 | | // Common cases: constant or array of constants |
| | 15 | 42 | | return defaultExpr switch |
| | 15 | 43 | | { |
| | 9 | 44 | | ConstantExpressionAst c => c.Value, |
| | 15 | 45 | | |
| | 0 | 46 | | ArrayLiteralAst a when a.Elements.All(e => e is ConstantExpressionAst) => |
| | 0 | 47 | | a.Elements.Cast<ConstantExpressionAst>() |
| | 0 | 48 | | .Select(e => e.Value) |
| | 0 | 49 | | .ToArray(), |
| | 15 | 50 | | |
| | 15 | 51 | | // Fallback β return the textual expression if itβs something more complex |
| | 6 | 52 | | _ => defaultExpr.Extent.Text |
| | 15 | 53 | | }; |
| | | 54 | | } |
| | | 55 | | } |