Skip to content

Commit d267ef1

Browse files
committed
fix class register can not use validate attribute, #116
1 parent 4de4cb8 commit d267ef1

File tree

3 files changed

+40
-168
lines changed

3 files changed

+40
-168
lines changed
Lines changed: 9 additions & 167 deletions
Original file line numberDiff line numberDiff line change
@@ -1,172 +1,14 @@
1-
using ConsoleAppFramework;
2-
using GeneratorSandbox;
3-
using Microsoft.Extensions.Configuration;
4-
using Microsoft.Extensions.DependencyInjection;
5-
using Microsoft.Extensions.Hosting;
6-
using Microsoft.Extensions.Logging;
7-
using Microsoft.Extensions.Options;
8-
using System.ComponentModel.DataAnnotations;
9-
using System.Numerics;
10-
using System.Text.Json;
11-
using System.Threading.Channels;
12-
using ZLogger;
1+
using System.ComponentModel.DataAnnotations;
2+
using System.Diagnostics.CodeAnalysis;
3+
using ConsoleAppFramework;
134

5+
args = ["show", "--aaa", "a", "--value", "10.2"];
146

15-
//args = "--first-arg invalid.email --second-arg 10".Split(' ');
7+
var app = ConsoleApp.Create();
8+
app.Add<Test>();
9+
app.Run(args);
1610

17-
//ConsoleApp.Timeout = Timeout.InfiniteTimeSpan;
18-
19-
20-
21-
22-
//ConsoleApp.Run(args, (
23-
// [Argument] DateTime dateTime, // Argument
24-
// [Argument] Guid guidvalue, //
25-
// int intVar, // required
26-
// bool boolFlag, // flag
27-
// MyEnum enumValue, // enum
28-
// int[] array, // array
29-
// MyClass obj, // object
30-
// string optional = "abcde", // optional
31-
// double? nullableValue = null, // nullable
32-
// params string[] paramsArray // params
33-
// ) => { });
34-
35-
36-
args = ["--mc", "{\"MyProperty\":100}"];
37-
38-
ConsoleApp.Run(args, (MyClass mc) =>
39-
{
40-
Console.WriteLine(mc.MyProperty);
41-
});
42-
43-
public enum MyEnum
44-
{
45-
46-
}
47-
48-
public class MyClass
49-
{
50-
public int MyProperty { get; set; }
51-
}
52-
53-
// inject logger
54-
public class MyCommand(ILogger<MyCommand> logger, IOptions<PositionOptions> options)
55-
{
56-
[Command("")]
57-
public void Echo(string msg)
58-
{
59-
logger.ZLogTrace($"Binded Option: {options.Value.Title} {options.Value.Name}");
60-
logger.ZLogInformation($"Message is {msg}");
61-
}
62-
}
63-
64-
65-
66-
public class PositionOptions
67-
{
68-
public string Title { get; set; } = "";
69-
public string Name { get; set; } = "";
70-
}
71-
72-
73-
74-
75-
76-
[AttributeUsage(AttributeTargets.Parameter)]
77-
public class Vector3ParserAttribute : Attribute, IArgumentParser<Vector3>
78-
{
79-
public static bool TryParse(ReadOnlySpan<char> s, out Vector3 result)
80-
{
81-
Span<Range> ranges = stackalloc Range[3];
82-
var splitCount = s.Split(ranges, ',');
83-
if (splitCount != 3)
84-
{
85-
result = default;
86-
return false;
87-
}
88-
89-
float x;
90-
float y;
91-
float z;
92-
if (float.TryParse(s[ranges[0]], out x) && float.TryParse(s[ranges[1]], out y) && float.TryParse(s[ranges[2]], out z))
93-
{
94-
result = new Vector3(x, y, z);
95-
return true;
96-
}
97-
98-
result = default;
99-
return false;
100-
}
101-
}
102-
103-
104-
internal class DIFilter(string foo, int bar, ConsoleAppFilter next)
105-
: ConsoleAppFilter(next)
106-
{
107-
public override Task InvokeAsync(ConsoleAppContext context, CancellationToken cancellationToken)
108-
{
109-
var newContext = context with { State = 100 };
110-
111-
Console.Write("invoke:");
112-
Console.Write(foo);
113-
Console.Write(bar);
114-
return Next.InvokeAsync(newContext, cancellationToken);
115-
}
116-
}
117-
118-
public class MiniDI : IServiceProvider
119-
{
120-
System.Collections.Generic.Dictionary<Type, object> dict = new();
121-
122-
public void Register(Type type, object instance)
123-
{
124-
dict[type] = instance;
125-
}
126-
127-
public object? GetService(Type serviceType)
128-
{
129-
return dict.TryGetValue(serviceType, out var instance) ? instance : null;
130-
}
131-
}
132-
133-
namespace ConsoleAppFramework
11+
public class Test
13412
{
135-
partial class ConsoleApp
136-
{
137-
static async Task RunWithFilterAsync2(string commandName, string[] args, ConsoleAppFilter invoker)
138-
{
139-
using var posixSignalHandler = PosixSignalHandler.Register(Timeout);
140-
try
141-
{
142-
143-
144-
await Task.Run(() => invoker.InvokeAsync(new ConsoleAppContext(commandName, args, null), posixSignalHandler.Token)).WaitAsync(posixSignalHandler.TimeoutToken);
145-
146-
147-
await Task.Factory.StartNew(static state => Task.CompletedTask, 1983, default, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default).Unwrap();
148-
149-
150-
151-
}
152-
catch (Exception ex)
153-
{
154-
if (ex is OperationCanceledException)
155-
{
156-
Environment.ExitCode = 130;
157-
return;
158-
}
159-
160-
Environment.ExitCode = 1;
161-
if (ex is ValidationException)
162-
{
163-
LogError(ex.Message);
164-
}
165-
else
166-
{
167-
LogError(ex.ToString());
168-
}
169-
}
170-
}
171-
}
13+
public void Show(string aaa, [Range(0, 1)] double value) => ConsoleApp.Log($"{value}");
17214
}

src/ConsoleAppFramework/Emitter.cs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,14 @@ public void EmitRun(SourceBuilder sb, CommandWithId commandWithId, bool isRunAsy
212212
{
213213
sb.AppendLine();
214214
sb.AppendLine("var validationContext = new System.ComponentModel.DataAnnotations.ValidationContext(\"\", null, null);");
215-
sb.AppendLine("var parameters = command.Method.GetParameters();");
215+
if (command.CommandMethodInfo == null)
216+
{
217+
sb.AppendLine("var parameters = command.Method.GetParameters();");
218+
}
219+
else
220+
{
221+
sb.AppendLine($"var parameters = typeof({command.CommandMethodInfo.TypeFullName}).GetMethod(\"{command.CommandMethodInfo.MethodName}\").GetParameters();");
222+
}
216223
sb.AppendLine("System.Text.StringBuilder? errorMessages = null;");
217224
for (int i = 0; i < command.Parameters.Length; i++)
218225
{

tests/ConsoleAppFramework.GeneratorTests/RunTest.cs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,4 +89,27 @@ public class Obj
8989
}
9090
""", "--foo 10 --bar aiueo --ft Grape --flag --half 1.3 --itt 99 --obj {\"Foo\":1999}", "10aiueoGrapeTrue1.3991999");
9191
}
92+
93+
[Fact]
94+
public void ValidateClass()
95+
{
96+
var expected = """
97+
The field value must be between 0 and 1.
98+
99+
100+
""";
101+
102+
verifier.Execute("""
103+
var app = ConsoleApp.Create();
104+
app.Add<Test>();
105+
app.Run(args);
106+
107+
public class Test
108+
{
109+
public void Show(string aaa, [Range(0, 1)] double value) => ConsoleApp.Log($"{value}");
110+
}
111+
112+
""", "show --aaa foo --value 100", expected);
113+
114+
}
92115
}

0 commit comments

Comments
 (0)