File size: 6,411 Bytes
2df0cf9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
"""
Docker file generation service.
"""

from typing import Union
from pathlib import Path

from fastapi import HTTPException, status
from jinja2 import Environment, Template

from app.core.config import Settings
from app.models.schemas import DockerfileConfig, DockerComposeConfig


class DockerGenerator:
    """Service for generating Docker files and configurations."""

    def __init__(self, template_env: Environment, settings: Settings, logger):
        self.template_env = template_env
        self.settings = settings
        self.logger = logger

    def generate_dockerfile(self, config: DockerfileConfig, file_id: str) -> str:
        """
        Generate a Dockerfile based on stack type and configuration.
        """
        stack = config.stackType.lower()
        
        # Map stack to template
        template_map = {
            "nodejs": "docker/dockerfile_nodejs.j2",
            "python": "docker/dockerfile_python.j2",
            "php": "docker/dockerfile_php.j2",
            "go": "docker/dockerfile_go.j2",
            "java": "docker/dockerfile_java.j2",
            "dotnet": "docker/dockerfile_dotnet.j2",
            "ruby": "docker/dockerfile_ruby.j2",
        }

        template_name = template_map.get(stack)
        if not template_name:
            raise ValueError(f"Unsupported stack type: {stack}")

        try:
            # Read template from disk
            template_path = self.settings.templates_dir / template_name
            with open(template_path, 'r', encoding='utf-8') as f:
                template_content = f.read()

            # Render using Jinja2
            template = Template(
                template_content,
                trim_blocks=True,
                lstrip_blocks=True
            )
            
            dockerfile_content = template.render(config=config, file_id=file_id)
            return dockerfile_content

        except Exception as e:
            self.logger.error(f"Failed to generate Dockerfile: {str(e)}")
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=f"Failed to generate Dockerfile: {str(e)}"
            )

    def generate_docker_compose(self, config: DockerComposeConfig, file_id: str) -> str:
        """
        Generate a docker-compose.yml based on configuration.
        """
        template_name = "docker/docker-compose.yml.j2"

        try:
            # Read template from disk
            template_path = self.settings.templates_dir / template_name
            with open(template_path, 'r', encoding='utf-8') as f:
                template_content = f.read()

            # Render using Jinja2
            template = Template(
                template_content,
                trim_blocks=True,
                lstrip_blocks=True
            )
            
            compose_content = template.render(config=config, file_id=file_id)
            return compose_content

        except Exception as e:
            self.logger.error(f"Failed to generate docker-compose: {str(e)}")
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=f"Failed to generate docker-compose: {str(e)}"
            )

    def generate_dockerignore(self, config: Union[DockerfileConfig, DockerComposeConfig], file_id: str) -> str:
        """
        Generate a .dockerignore file.
        """
        template_name = "docker/dockerignore.j2"

        try:
            # Read template from disk
            template_path = self.settings.templates_dir / template_name
            with open(template_path, 'r', encoding='utf-8') as f:
                template_content = f.read()

            # Render using Jinja2
            template = Template(
                template_content,
                trim_blocks=True,
                lstrip_blocks=True
            )
            
            dockerignore_content = template.render(config=config, file_id=file_id)
            return dockerignore_content

        except Exception as e:
            self.logger.error(f"Failed to generate .dockerignore: {str(e)}")
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=f"Failed to generate .dockerignore: {str(e)}"
            )

    def generate_env_example(self, config: DockerComposeConfig, file_id: str) -> str:
        """
        Generate a .env.example file for docker-compose.
        """
        template_name = "docker/env.example.j2"

        try:
            # Read template from disk
            template_path = self.settings.templates_dir / template_name
            with open(template_path, 'r', encoding='utf-8') as f:
                template_content = f.read()

            # Render using Jinja2
            template = Template(
                template_content,
                trim_blocks=True,
                lstrip_blocks=True
            )
            
            env_content = template.render(config=config, file_id=file_id)
            return env_content

        except Exception as e:
            self.logger.error(f"Failed to generate .env.example: {str(e)}")
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=f"Failed to generate .env.example: {str(e)}"
            )

    def generate_build_script(self, config: DockerComposeConfig, file_id: str) -> str:
        """
        Generate a docker-build.sh helper script.
        """
        template_name = "docker/docker-build.sh.j2"

        try:
            # Read template from disk
            template_path = self.settings.templates_dir / template_name
            with open(template_path, 'r', encoding='utf-8') as f:
                template_content = f.read()

            # Render using Jinja2
            template = Template(
                template_content,
                trim_blocks=True,
                lstrip_blocks=True
            )
            
            script_content = template.render(config=config, file_id=file_id)
            return script_content

        except Exception as e:
            self.logger.error(f"Failed to generate build script: {str(e)}")
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=f"Failed to generate build script: {str(e)}"
            )