mycroforge/MycroForge.CLI/Commands/MycroForge.Generate.Service.cs
2024-05-04 20:44:48 +02:00

66 lines
2.4 KiB
C#

using System.CommandLine;
using Humanizer;
using MycroForge.CLI.Commands.Interfaces;
namespace MycroForge.CLI.Commands;
public partial class MycroForge
{
public partial class Generate
{
public class Service : Command, ISubCommandOf<Generate>
{
private static readonly Argument<string> NameArgument =
new(name: "name", description: "The name of the service");
private static readonly Option<bool> WithSession =
new(name: "--with-session", description: "Create a service that uses database sessions");
private static readonly string[] DefaultTemplate =
[
"class %class_name%:",
"",
"\tdef do_stuff(self, stuff: str) -> str:",
"\t\treturn f\"Hey, I'm doing stuff!\""
];
private static readonly string[] WithSessionTemplate =
[
"from orm.engine.async_session import async_session",
"# from orm.entities.user import User",
"",
"class %class_name%:",
"",
"\tasync def do_stuff(self, stuff: str) -> str:",
"\t\tasync with async_session() as session():",
"\t\t\t# stmt = select(User).where(User.firstname == \"John\")",
"\t\t\t# results = await session.scalars(stmt).all()",
"\t\t\t# print(len(results))",
"\t\t\tpass",
"\t\treturn f\"Hey, I'm doing stuff!\""
];
private readonly ProjectContext _context;
public Service(ProjectContext context) : base("service", "Generate a service")
{
_context = context;
AddAlias("s");
AddOption(WithSession);
this.SetHandler(ExecuteAsync, NameArgument, WithSession);
}
private async Task ExecuteAsync(string name, bool withSession)
{
_context.AssertDirectoryExists("services");
var className = Path.GetFileName(name).Pascalize();
var code = string.Join('\n', withSession ? WithSessionTemplate : DefaultTemplate)
.Replace("%class_name%", className);
await _context.CreateFile($"services/{name.Underscore().ToLower()}.py", code);
}
}
}
}