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 { private static readonly Argument NameArgument = new(name: "name", description: "The name of the service"); private static readonly Option 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); } } } }