mecha10_cli/services/
project_template_service.rs

1//! Project template service for generating project files
2//!
3//! This service coordinates template generation across specialized modules:
4//! - Rust templates (Cargo.toml, main.rs, build.rs)
5//! - Infrastructure templates (docker-compose.yml, .env)
6//! - Meta templates (README.md, .gitignore, package.json)
7//!
8//! # Architecture
9//!
10//! Templates are organized into focused modules under `crate::templates`:
11//! - **RustTemplates**: Rust-specific files
12//! - **InfraTemplates**: Infrastructure files
13//! - **MetaTemplates**: Project metadata files
14//!
15//! Template content is stored in external files at `packages/cli/templates/`
16//! and embedded at compile time using `include_str!()`.
17
18use crate::templates::{InfraTemplates, MetaTemplates, RustTemplates};
19use anyhow::{Context, Result};
20use std::path::Path;
21
22// Embedded configuration templates
23#[allow(dead_code)]
24const MECHA10_JSON_TEMPLATE: &str = include_str!("../../templates/config/mecha10.json.template");
25const MODEL_JSON_TEMPLATE: &str = include_str!("../../templates/config/model.json.template");
26const ENVIRONMENT_JSON_TEMPLATE: &str = include_str!("../../templates/config/environment.json.template");
27
28// Embedded node configs (copied from packages/nodes/*/configs/ - keep in sync)
29const BEHAVIOR_EXECUTOR_CONFIG_DEV: &str = include_str!("../../templates/config/nodes/behavior-executor/config.json");
30const IMAGE_CLASSIFIER_CONFIG_DEV: &str = include_str!("../../templates/config/nodes/image-classifier/config.json");
31const LLM_COMMAND_CONFIG_DEV: &str = include_str!("../../templates/config/nodes/llm-command/config.json");
32const OBJECT_DETECTOR_CONFIG_DEV: &str = include_str!("../../templates/config/nodes/object-detector/config.json");
33const SIMULATION_BRIDGE_CONFIG_DEV: &str = include_str!("../../templates/config/nodes/simulation-bridge/config.json");
34const WEBSOCKET_BRIDGE_CONFIG_DEV: &str = include_str!("../../templates/config/nodes/websocket-bridge/config.json");
35
36// Embedded simulation config (simulation is dev-only, no production config needed)
37const SIMULATION_CONFIG: &str = include_str!("../../templates/config/simulation/config.json");
38
39// Embedded simulation image assets (for standalone mode)
40const AIKO_IMAGE: &[u8] = include_bytes!("../../templates/assets/images/aiko.jpg");
41const PHOEBE_IMAGE: &[u8] = include_bytes!("../../templates/assets/images/phoebe.jpg");
42
43// Embedded behavior tree templates (for standalone mode)
44const BEHAVIOR_BASIC_NAVIGATION: &str = include_str!("../../templates/behaviors/basic_navigation.json");
45const BEHAVIOR_IDLE_WANDER: &str = include_str!("../../templates/behaviors/idle_wander.json");
46const BEHAVIOR_OBSTACLE_AVOIDANCE: &str = include_str!("../../templates/behaviors/obstacle_avoidance.json");
47const BEHAVIOR_PATROL_SIMPLE: &str = include_str!("../../templates/behaviors/patrol_simple.json");
48
49/// Service for generating project template files
50///
51/// # Examples
52///
53/// ```rust,ignore
54/// use mecha10_cli::services::ProjectTemplateService;
55///
56/// let service = ProjectTemplateService::new();
57///
58/// // Generate all project files
59/// service.create_readme(&project_path, "my-robot").await?;
60/// service.create_cargo_toml(&project_path, "my-robot", false).await?;
61/// ```
62pub struct ProjectTemplateService {
63    rust: RustTemplates,
64    infra: InfraTemplates,
65    meta: MetaTemplates,
66}
67
68impl ProjectTemplateService {
69    /// Create a new ProjectTemplateService
70    pub fn new() -> Self {
71        Self {
72            rust: RustTemplates::new(),
73            infra: InfraTemplates::new(),
74            meta: MetaTemplates::new(),
75        }
76    }
77
78    /// Create README.md for the project
79    pub async fn create_readme(&self, path: &Path, project_name: &str) -> Result<()> {
80        self.meta.create_readme(path, project_name).await
81    }
82
83    /// Create .gitignore for the project
84    pub async fn create_gitignore(&self, path: &Path) -> Result<()> {
85        self.meta.create_gitignore(path).await
86    }
87
88    /// Create .cargo/config.toml for framework development
89    ///
90    /// This patches all mecha10-* dependencies to use local paths instead of crates.io.
91    /// Requires a framework_path pointing to the mecha10-monorepo root.
92    pub async fn create_cargo_config(&self, path: &Path, framework_path: &str) -> Result<()> {
93        self.rust.create_cargo_config(path, framework_path).await
94    }
95
96    /// Create Cargo.toml for the project
97    ///
98    /// # Arguments
99    ///
100    /// * `path` - Project root path
101    /// * `project_name` - Name of the project
102    /// * `dev` - Whether this is for framework development (affects dependency resolution)
103    pub async fn create_cargo_toml(&self, path: &Path, project_name: &str, dev: bool) -> Result<()> {
104        self.rust.create_cargo_toml(path, project_name, dev).await
105    }
106
107    /// Create src/main.rs for the project
108    pub async fn create_main_rs(&self, path: &Path, project_name: &str) -> Result<()> {
109        self.rust.create_main_rs(path, project_name).await
110    }
111
112    /// Create build.rs for the project
113    ///
114    /// This build script generates:
115    /// 1. node_registry.rs - Node dispatcher based on mecha10.json
116    pub async fn create_build_rs(&self, path: &Path) -> Result<()> {
117        self.rust.create_build_rs(path).await
118    }
119
120    /// Create .env.example for the project
121    ///
122    /// # Arguments
123    ///
124    /// * `path` - Project root path
125    /// * `project_name` - Name of the project
126    /// * `framework_path` - Optional framework path for development mode
127    pub async fn create_env_example(
128        &self,
129        path: &Path,
130        project_name: &str,
131        framework_path: Option<String>,
132    ) -> Result<()> {
133        self.infra.create_env_example(path, project_name, framework_path).await
134    }
135
136    /// Create rustfmt.toml for the project
137    pub async fn create_rustfmt_toml(&self, path: &Path) -> Result<()> {
138        self.rust.create_rustfmt_toml(path).await
139    }
140
141    /// Create docker-compose.yml for the project
142    ///
143    /// Generates a Docker Compose file with Redis and optional PostgreSQL services
144    /// for local development and deployment.
145    ///
146    /// # Arguments
147    ///
148    /// * `path` - Project root path
149    /// * `project_name` - Name of the project (used for container naming)
150    pub async fn create_docker_compose(&self, path: &Path, project_name: &str) -> Result<()> {
151        self.infra.create_docker_compose(path, project_name).await
152    }
153
154    /// Create package.json for npm dependencies
155    ///
156    /// Includes @mecha10/simulation-models and @mecha10/simulation-environments dependencies.
157    /// Resolution happens at runtime via MECHA10_FRAMEWORK_PATH env var:
158    /// - If set: Uses local monorepo packages
159    /// - If not set: Uses node_modules/@mecha10/* (requires npm install)
160    ///
161    /// # Arguments
162    ///
163    /// * `path` - Project root path
164    /// * `project_name` - Name of the project
165    pub async fn create_package_json(&self, path: &Path, project_name: &str) -> Result<()> {
166        self.meta.create_package_json(path, project_name).await
167    }
168
169    /// Create requirements.txt for Python dependencies
170    ///
171    /// Includes Python packages needed for AI nodes (onnx, onnxruntime).
172    /// Install with: `mecha10 setup` or `pip install -r requirements.txt`
173    ///
174    /// # Arguments
175    ///
176    /// * `path` - Project root path
177    pub async fn create_requirements_txt(&self, path: &Path) -> Result<()> {
178        self.meta.create_requirements_txt(path).await
179    }
180
181    /// Create mecha10.json configuration file
182    ///
183    /// Generates the main project configuration file with robot identity,
184    /// simulation settings, nodes, services, and Docker configuration.
185    ///
186    /// # Arguments
187    ///
188    /// * `path` - Project root directory
189    /// * `project_name` - Name of the project
190    /// * `template` - Robot template (rover, humanoid, etc.)
191    #[allow(dead_code)]
192    pub async fn create_mecha10_json(&self, path: &Path, project_name: &str, template: &Option<String>) -> Result<()> {
193        let platform = template.as_deref().unwrap_or("basic");
194        let project_id = project_name.replace('-', "_");
195
196        // Render template with handlebars
197        let config_content = MECHA10_JSON_TEMPLATE
198            .replace("{{project_name}}", project_name)
199            .replace("{{project_id}}", &project_id)
200            .replace("{{platform}}", platform);
201
202        tokio::fs::write(path.join("mecha10.json"), config_content).await?;
203        Ok(())
204    }
205
206    /// Create simulation/models/model.json
207    ///
208    /// Generates the rover robot physical model configuration for Godot simulation
209    /// from embedded template.
210    ///
211    /// # Arguments
212    ///
213    /// * `path` - Project root directory
214    pub async fn create_simulation_model_json(&self, path: &Path) -> Result<()> {
215        let model_dest = path.join("simulation/models/rover/model.json");
216
217        // Ensure destination directory exists
218        if let Some(parent) = model_dest.parent() {
219            tokio::fs::create_dir_all(parent).await?;
220        }
221
222        // Write embedded model.json template
223        tokio::fs::write(&model_dest, MODEL_JSON_TEMPLATE)
224            .await
225            .context("Failed to write model.json")?;
226
227        Ok(())
228    }
229
230    /// Create simulation/environments/basic_arena/environment.json
231    ///
232    /// Generates the basic arena environment configuration for Godot simulation
233    /// from embedded template.
234    ///
235    /// # Arguments
236    ///
237    /// * `path` - Project root directory
238    pub async fn create_simulation_environment_json(&self, path: &Path) -> Result<()> {
239        let env_dest = path.join("simulation/environments/basic_arena/environment.json");
240
241        // Ensure destination directory exists
242        if let Some(parent) = env_dest.parent() {
243            tokio::fs::create_dir_all(parent).await?;
244        }
245
246        // Write embedded environment.json template
247        tokio::fs::write(&env_dest, ENVIRONMENT_JSON_TEMPLATE)
248            .await
249            .context("Failed to write environment.json")?;
250
251        Ok(())
252    }
253
254    /// Create node configuration files from embedded configs
255    ///
256    /// Writes node configs to configs/nodes/@mecha10/{node}/config.json
257    /// Configs are embedded from packages/nodes/*/configs/ at build time (single source of truth).
258    ///
259    /// # Arguments
260    ///
261    /// * `path` - Project root directory
262    pub async fn create_node_configs(&self, path: &Path) -> Result<()> {
263        let node_configs: &[(&str, &str)] = &[
264            ("behavior-executor", BEHAVIOR_EXECUTOR_CONFIG_DEV),
265            ("image-classifier", IMAGE_CLASSIFIER_CONFIG_DEV),
266            ("llm-command", LLM_COMMAND_CONFIG_DEV),
267            ("object-detector", OBJECT_DETECTOR_CONFIG_DEV),
268            ("simulation-bridge", SIMULATION_BRIDGE_CONFIG_DEV),
269            ("websocket-bridge", WEBSOCKET_BRIDGE_CONFIG_DEV),
270        ];
271
272        for (node_name, config_content) in node_configs {
273            // Config path: configs/nodes/@mecha10/{node}/config.json
274            let dest = path.join("configs/nodes/@mecha10").join(node_name).join("config.json");
275
276            if let Some(parent) = dest.parent() {
277                tokio::fs::create_dir_all(parent).await?;
278            }
279
280            tokio::fs::write(&dest, *config_content)
281                .await
282                .with_context(|| format!("Failed to write @mecha10/{}/config.json", node_name))?;
283        }
284
285        Ok(())
286    }
287
288    /// Create simulation config from embedded config
289    ///
290    /// Writes simulation config to configs/simulation/config.json.
291    ///
292    /// # Arguments
293    ///
294    /// * `path` - Project root directory
295    pub async fn create_simulation_configs(&self, path: &Path) -> Result<()> {
296        let dest = path.join("configs/simulation/config.json");
297        if let Some(parent) = dest.parent() {
298            tokio::fs::create_dir_all(parent).await?;
299        }
300        tokio::fs::write(&dest, SIMULATION_CONFIG)
301            .await
302            .context("Failed to write configs/simulation/config.json")?;
303
304        Ok(())
305    }
306
307    /// Create simulation image assets from embedded templates
308    ///
309    /// Writes image assets to assets/images/ directory.
310    /// This is used in standalone mode when framework path is not available.
311    /// In framework dev mode, these are copied from the simulation package instead.
312    ///
313    /// # Arguments
314    ///
315    /// * `path` - Project root directory
316    pub async fn create_simulation_assets(&self, path: &Path) -> Result<()> {
317        // Create assets/images directory
318        let images_dest = path.join("assets/images");
319        tokio::fs::create_dir_all(&images_dest).await?;
320
321        // Write image files
322        let image_assets: &[(&str, &[u8])] = &[("aiko.jpg", AIKO_IMAGE), ("phoebe.jpg", PHOEBE_IMAGE)];
323
324        for (filename, content) in image_assets {
325            let dest_file = images_dest.join(filename);
326            tokio::fs::write(&dest_file, content)
327                .await
328                .with_context(|| format!("Failed to write assets/images/{}", filename))?;
329        }
330
331        Ok(())
332    }
333
334    /// Create behavior tree templates from embedded files
335    ///
336    /// Writes behavior tree JSON files to behaviors/ directory.
337    /// This is used in standalone mode when framework path is not available.
338    /// In framework dev mode, these are copied from behavior-runtime/seeds/ instead.
339    ///
340    /// # Arguments
341    ///
342    /// * `path` - Project root directory
343    pub async fn create_behavior_templates(&self, path: &Path) -> Result<()> {
344        let behaviors_dest = path.join("behaviors");
345        tokio::fs::create_dir_all(&behaviors_dest).await?;
346
347        let behavior_templates: &[(&str, &str)] = &[
348            ("basic_navigation.json", BEHAVIOR_BASIC_NAVIGATION),
349            ("idle_wander.json", BEHAVIOR_IDLE_WANDER),
350            ("obstacle_avoidance.json", BEHAVIOR_OBSTACLE_AVOIDANCE),
351            ("patrol_simple.json", BEHAVIOR_PATROL_SIMPLE),
352        ];
353
354        for (filename, content) in behavior_templates {
355            let dest_file = behaviors_dest.join(filename);
356            tokio::fs::write(&dest_file, *content)
357                .await
358                .with_context(|| format!("Failed to write behaviors/{}", filename))?;
359        }
360
361        Ok(())
362    }
363}
364
365impl Default for ProjectTemplateService {
366    fn default() -> Self {
367        Self::new()
368    }
369}