<reponame>nanato12/private-line-bot
import os
from ast import (
    Assign,
    ClassDef,
    Constant,
    ImportFrom,
    Load,
    Module,
    Name,
    Store,
    alias,
)
from datetime import datetime

import astor

from core.base.generator import BaseGenerator
from core.utils import convert_camel_case, extract_alphabet

GEN_COMMENT = "# Generated by CommandGenerator on {date}\n\n"


class CommandGenerator(BaseGenerator):
    name: str
    ast_body: list

    def __init__(self, name: str) -> None:
        self.name = name

    def __ast_import_from(self) -> None:
        """append ImportFrom to ast body"""

        self.ast_body.append(
            ImportFrom(
                module="core.base.commnad",
                names=[alias(name="BaseCommand")],
                level=0,
            )
        )

    def __ast_class_def(self) -> None:
        """append ClassDef to ast body"""

        self.ast_body.append(
            ClassDef(
                name=f"{extract_alphabet(convert_camel_case(self.name))}Command",
                bases=[Name(id="BaseCommand", ctx=Load())],
                keywords=[],
                body=[
                    Assign(
                        targets=[Name(id="cmd", ctx=Store())],
                        value=Constant(value=self.name),
                    ),
                    Assign(
                        targets=[Name(id="description", ctx=Store())],
                        value=Constant(value="Please input here command description."),
                    ),
                ],
                decorator_list=[],
            ),
        )

    def __create_ast_module(self) -> Module:
        """create ast module

        Returns:
            Module: ast module
        """

        self.ast_body = []
        self._ast_add_license()
        self.__ast_import_from()
        self.__ast_class_def()
        return Module(body=self.ast_body, type_ignores=[])

    def generate(self) -> None:
        """generate command py file"""

        if (output_dir := os.environ.get("COMMAND_OUTPUT_PATH")) is None:
            raise Exception("COMMAND_OUTPUT_PATH is none.")

        os.makedirs(output_dir, exist_ok=True)

        file_name = f"{output_dir}/{extract_alphabet(self.name)}_command.py"
        if os.path.exists(file_name):
            raise Exception(f"already exists command: {self.name}")

        with open(file_name, "w") as cmd_py_file:
            cmd_py_file.write(
                GEN_COMMENT.format(date=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
                + astor.to_source(self.__create_ast_module())
            )
        print(f"Generate success! {file_name}")

import os
from ast import (
    Assign,
    ClassDef,
    Constant,
    ImportFrom,
    Load,
    Module,
    Name,
    Store,
    alias,
)
from datetime import datetime

import astor

from core.base.generator import BaseGenerator
from core.utils import convert_camel_case, extract_alphabet

GEN_COMMENT = "# Generated by CommandGenerator on {date}\n\n"


class CommandGenerator(BaseGenerator):
    name: str
    ast_body: list

    def __init__(self, name: str) -> None:
        self.name = name

    def __ast_import_from(self) -> None:
        """append ImportFrom to ast body"""

        self.ast_body.append(
            ImportFrom(
                module="core.base.commnad",
                names=[alias(name="BaseCommand")],
                level=0,
            )
        )

    def __ast_class_def(self) -> None:
        """append ClassDef to ast body"""

        self.ast_body.append(
            ClassDef(
                name=f"{extract_alphabet(convert_camel_case(self.name))}Command",
                bases=[Name(id="BaseCommand", ctx=Load())],
                keywords=[],
                body=[
                    Assign(
                        targets=[Name(id="cmd", ctx=Store())],
                        value=Constant(value=self.name),
                    ),
                    Assign(
                        targets=[Name(id="description", ctx=Store())],
                        value=Constant(value="Please input here command description."),
                    ),
                ],
                decorator_list=[],
            ),
        )

    def __create_ast_module(self) -> Module:
        """create ast module

        Returns:
            Module: ast module
        """

        self.ast_body = []
        self._ast_add_license()
        self.__ast_import_from()
        self.__ast_class_def()
        return Module(body=self.ast_body, type_ignores=[])

    def generate(self) -> None:
        """generate command py file"""

        if (output_dir := os.environ.get("COMMAND_OUTPUT_PATH")) is None:
            raise Exception("COMMAND_OUTPUT_PATH is none.")

        os.makedirs(output_dir, exist_ok=True)

        file_name = f"{output_dir}/{extract_alphabet(self.name)}_command.py"
        if os.path.exists(file_name):
            raise Exception(f"already exists command: {self.name}")

        with open(file_name, "w") as cmd_py_file:
            cmd_py_file.write(
                GEN_COMMENT.format(date=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
                + astor.to_source(self.__create_ast_module())
            )
        print(f"Generate success! {file_name}")
append ImportFrom to ast body append ClassDef to ast body create ast module          Returns:             Module: ast module generate command py file