Skip to content

Commit 9ed8697

Browse files
committed
Feat: Enhance optional parameter handling in CLI args parser
Added fallback value support for optional parameters when the property type isn't boolean. This ensures proper handling of defaults using property initializers or a defined "default" value. Updated logic improves robustness and clarity in optional parameter handling.
1 parent 8c5275e commit 9ed8697

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

src/CodeOfChaos.CliArgsParser.Generators/ParameterDto.cs

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using CodeOfChaos.CliArgsParser.Generators.Helpers;
55
using JetBrains.Annotations;
66
using Microsoft.CodeAnalysis;
7+
using Microsoft.CodeAnalysis.CSharp.Syntax;
78
using System;
89
using System.Collections.Immutable;
910
using System.Linq;
@@ -49,8 +50,15 @@ private static string GetShortName(IPropertySymbol symbol) {
4950

5051

5152
public string GetWithPropertyDictionary() {
52-
return IsRequired
53-
? $"parameterDictionary.GetParameterByPossibleNames<{PropertyType}>({Name}, {ShortName})"
54-
: $"parameterDictionary.GetOptionalParameterByPossibleNames<{PropertyType}>({Name}, {ShortName})";
53+
if (IsRequired) return $"parameterDictionary.GetParameterByPossibleNames<{PropertyType}>({Name}, {ShortName})";
54+
55+
if (PropertyType == "bool") return $"parameterDictionary.GetOptionalParameterByPossibleNames<{PropertyType}>({Name}, {ShortName})";
56+
57+
string fallback = Symbol.DeclaringSyntaxReferences
58+
.Select(r => r.GetSyntax())
59+
.OfType<PropertyDeclarationSyntax>()
60+
.FirstOrDefault()?.Initializer?.Value.ToString() ?? "default";
61+
62+
return $"parameterDictionary.GetOptionalParameterByPossibleNames<{PropertyType}>({Name}, {ShortName}) ?? {fallback}";
5563
}
5664
}

0 commit comments

Comments
 (0)