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 PathOption = new(name: "--path", description: "The folder path of the service") { IsRequired = true }; private static readonly Option WithSessionOption = 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 sqlalchemy import select", "# from orm.entities.some_entity import SomeEntity", "", "class %class_name%Service:", "", "\tasync def do_stuff(self, stuff: str) -> str:", "\t\tasync with async_session() as session:", "\t\t\t# stmt = select(User).where(SomeEntity.value == \"some_value\")", "\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"); AddArgument(NameArgument); AddOption(PathOption); AddOption(WithSessionOption); this.SetHandler(ExecuteAsync, NameArgument, PathOption, WithSessionOption); } private async Task ExecuteAsync(string name, string? path, bool withSession) { var folderPath = "services"; if (!string.IsNullOrEmpty(path) && !path.Equals(".")) { folderPath = Path.Join(_context.RootDirectory, path); Directory.CreateDirectory(folderPath); } var className = Path.GetFileName(name).Pascalize(); var code = string.Join('\n', withSession ? WithSessionTemplate : DefaultTemplate) .Replace("%class_name%", className); var filePath = Path.Join(folderPath, $"{name.Underscore().ToLower()}_service.py"); await _context.CreateFile(filePath, code); } } } }