Skip to main content

mecha10_templates/services/
init_service.rs

1//! Init service for project initialization
2//!
3//! Handles business logic for creating new Mecha10 projects.
4
5use crate::paths;
6use anyhow::Result;
7use std::path::Path;
8
9pub struct InitService;
10
11impl InitService {
12    /// Create a new InitService
13    pub fn new() -> Self {
14        Self
15    }
16
17    /// Create all the necessary directories for a new Mecha10 project.
18    pub async fn create_project_directories(&self, path: &Path) -> Result<()> {
19        let dirs = vec![
20            paths::project::NODES_DIR,
21            paths::project::DRIVERS_DIR,
22            paths::project::TYPES_DIR,
23            paths::project::BEHAVIORS_DIR,
24            paths::project::LOGS_DIR,
25            paths::project::MODELS_DIR,
26            paths::project::MODELS_CATALOG_DIR,
27            paths::project::SIMULATION_DIR,
28            paths::project::SIMULATION_MODELS_DIR,
29            paths::project::SIMULATION_ENVIRONMENTS_DIR,
30            paths::project::SIMULATION_IMAGES_DIR,
31            paths::project::RL_TASKS_DIR,
32            paths::config::NODES_DIR,
33        ];
34
35        for dir in dirs {
36            let dir_path = path.join(dir);
37            tokio::fs::create_dir_all(&dir_path).await?;
38        }
39
40        Ok(())
41    }
42
43    /// Add an example node from the catalog to the project, updating Cargo.toml and
44    /// mecha10.json as needed.
45    pub async fn add_example_node(&self, project_root: &Path, component_name: &str) -> Result<()> {
46        use crate::component_catalog::ComponentCatalog;
47
48        let catalog = ComponentCatalog::new();
49        let components = catalog.search(component_name);
50
51        if components.is_empty() {
52            return Err(anyhow::anyhow!("Component '{}' not found in catalog", component_name));
53        }
54
55        let component = &components[0];
56
57        for file_template in &component.files {
58            let file_path = project_root.join(&file_template.path);
59
60            if let Some(parent) = file_path.parent() {
61                tokio::fs::create_dir_all(parent).await?;
62            }
63
64            tokio::fs::write(&file_path, &file_template.content).await?;
65        }
66
67        if !component.files.is_empty() {
68            self.add_workspace_member(project_root, component_name).await?;
69        }
70
71        let is_monorepo_node = component.files.is_empty();
72        if is_monorepo_node {
73            self.add_dependency(project_root, component).await?;
74        }
75
76        self.add_node_to_config(project_root, component_name, is_monorepo_node)
77            .await?;
78
79        Ok(())
80    }
81
82    /// Add a workspace member to Cargo.toml
83    async fn add_workspace_member(&self, project_root: &Path, component_name: &str) -> Result<()> {
84        let cargo_toml_path = project_root.join(paths::rust::CARGO_TOML);
85        let content = tokio::fs::read_to_string(&cargo_toml_path).await?;
86
87        let new_member = format!("nodes/{}", component_name);
88        let updated_content = if content.contains("members = []") {
89            content.replace("members = []", &format!("members = [\n    \"{}\",\n]", new_member))
90        } else if let Some(start) = content.find("members = [") {
91            if let Some(end) = content[start..].find(']') {
92                let insert_pos = start + end;
93                let members_section = &content[start..insert_pos];
94                if members_section.contains('\"') {
95                    format!(
96                        "{}\n    \"{}\",{}",
97                        &content[..insert_pos],
98                        new_member,
99                        &content[insert_pos..]
100                    )
101                } else {
102                    format!(
103                        "{}\n    \"{}\",\n{}",
104                        &content[..insert_pos],
105                        new_member,
106                        &content[insert_pos..]
107                    )
108                }
109            } else {
110                content
111            }
112        } else {
113            content
114        };
115
116        tokio::fs::write(&cargo_toml_path, updated_content).await?;
117        Ok(())
118    }
119
120    /// Add a dependency to Cargo.toml
121    async fn add_dependency(&self, project_root: &Path, component: &crate::component_catalog::Component) -> Result<()> {
122        let cargo_toml_path = project_root.join(paths::rust::CARGO_TOML);
123        let content = tokio::fs::read_to_string(&cargo_toml_path).await?;
124
125        let package_name = if let Some(dep) = component.cargo_dependencies.first() {
126            dep.name.clone()
127        } else {
128            format!("mecha10-nodes-{}", component.id)
129        };
130
131        if !content.contains(&package_name) {
132            let updated_content = if let Some(pos) = content.find("mecha10-core = \"0.1\"") {
133                if let Some(newline_pos) = content[pos..].find('\n') {
134                    let insert_pos = pos + newline_pos + 1;
135                    format!(
136                        "{}{} = \"0.1\"\n{}",
137                        &content[..insert_pos],
138                        package_name,
139                        &content[insert_pos..]
140                    )
141                } else {
142                    content
143                }
144            } else {
145                content
146            };
147
148            tokio::fs::write(&cargo_toml_path, updated_content).await?;
149        }
150
151        Ok(())
152    }
153
154    /// Add node entry to mecha10.json. Only mints the `nodes` map entry; `targets` placement
155    /// is handled separately by `handlers/init.rs`.
156    async fn add_node_to_config(
157        &self,
158        project_root: &Path,
159        component_name: &str,
160        is_monorepo_node: bool,
161    ) -> Result<()> {
162        use crate::services::ConfigService;
163
164        let config_path = project_root.join(paths::PROJECT_CONFIG);
165        let mut config = ConfigService::load_from(&config_path).await?;
166
167        let (node_identifier, version) = if is_monorepo_node {
168            (
169                format!("@mecha10/{}", component_name),
170                env!("CARGO_PKG_VERSION").to_string(),
171            )
172        } else {
173            (component_name.to_string(), "0.1.0".to_string())
174        };
175
176        config.nodes.add_node(&node_identifier, &version);
177
178        let config_json = serde_json::to_string_pretty(&config)?;
179        tokio::fs::write(&config_path, config_json).await?;
180
181        Ok(())
182    }
183}
184
185impl Default for InitService {
186    fn default() -> Self {
187        Self::new()
188    }
189}
190
191#[cfg(test)]
192mod add_node_to_config_tests {
193    use super::*;
194    use mecha10_cli_core::services::ConfigService;
195
196    /// Minimal valid mecha10.json content for a freshly-initialized project.
197    fn minimal_project_config_json() -> &'static str {
198        r#"{
199            "name": "test-project",
200            "version": "0.1.0",
201            "robot_id": "test-robot"
202        }"#
203    }
204
205    #[tokio::test]
206    async fn mints_project_nodes_with_plain_identifier() {
207        let temp_dir = tempfile::tempdir().expect("create temp dir");
208        let project_root = temp_dir.path();
209        tokio::fs::write(project_root.join(paths::PROJECT_CONFIG), minimal_project_config_json())
210            .await
211            .expect("write mecha10.json");
212
213        let service = InitService::new();
214
215        service
216            .add_node_to_config(project_root, "my-custom", false)
217            .await
218            .expect("add_node_to_config should succeed");
219
220        let config = ConfigService::load_from(&project_root.join(paths::PROJECT_CONFIG))
221            .await
222            .expect("reload config");
223
224        assert!(
225            config.nodes.identifiers().contains(&"my-custom"),
226            "expected plain identifier 'my-custom' in nodes, got: {:?}",
227            config.nodes.identifiers()
228        );
229        assert!(
230            !config.nodes.identifiers().contains(&"@local/my-custom"),
231            "new project nodes must not be minted with the legacy @local/ prefix, got: {:?}",
232            config.nodes.identifiers()
233        );
234    }
235
236    /// `add_node_to_config` must preserve `template_version` across its save, since it runs for
237    /// every default/selected node on every `mecha10 init`.
238    #[tokio::test]
239    async fn preserves_template_version_written_by_mecha10_init() {
240        let temp_dir = tempfile::tempdir().expect("create temp dir");
241        let project_root = temp_dir.path();
242        tokio::fs::write(
243            project_root.join(paths::PROJECT_CONFIG),
244            r#"{
245                "name": "test-project",
246                "version": "0.6.5",
247                "template_version": "0.6.5",
248                "robot_id": "test-robot"
249            }"#,
250        )
251        .await
252        .expect("write mecha10.json");
253
254        let service = InitService::new();
255
256        service
257            .add_node_to_config(project_root, "speaker", true)
258            .await
259            .expect("add_node_to_config should succeed");
260
261        let config = ConfigService::load_from(&project_root.join(paths::PROJECT_CONFIG))
262            .await
263            .expect("reload config");
264
265        assert_eq!(
266            config.template_version,
267            Some("0.6.5".to_string()),
268            "template_version written at `mecha10 init` time must survive add_node_to_config's save"
269        );
270    }
271
272    #[tokio::test]
273    async fn mints_framework_nodes_with_mecha10_scope() {
274        let temp_dir = tempfile::tempdir().expect("create temp dir");
275        let project_root = temp_dir.path();
276        tokio::fs::write(project_root.join(paths::PROJECT_CONFIG), minimal_project_config_json())
277            .await
278            .expect("write mecha10.json");
279
280        let service = InitService::new();
281
282        service
283            .add_node_to_config(project_root, "speaker", true)
284            .await
285            .expect("add_node_to_config should succeed");
286
287        let config = ConfigService::load_from(&project_root.join(paths::PROJECT_CONFIG))
288            .await
289            .expect("reload config");
290
291        assert!(
292            config.nodes.identifiers().contains(&"@mecha10/speaker"),
293            "expected framework identifier '@mecha10/speaker' in nodes, got: {:?}",
294            config.nodes.identifiers()
295        );
296    }
297
298    /// `add_node_to_config` must not touch `targets` at all - that placement is already
299    /// written by `handlers/init.rs`'s `build_node_placement` before this ever runs.
300    #[tokio::test]
301    async fn does_not_touch_targets_at_all() {
302        let temp_dir = tempfile::tempdir().expect("create temp dir");
303        let project_root = temp_dir.path();
304        let config_with_targets = r#"{
305            "name": "test-project",
306            "version": "0.1.0",
307            "robot_id": "test-robot",
308            "targets": {
309                "robot": { "nodes": ["@mecha10/camera"] }
310            }
311        }"#;
312        tokio::fs::write(project_root.join(paths::PROJECT_CONFIG), config_with_targets)
313            .await
314            .expect("write mecha10.json");
315
316        let service = InitService::new();
317
318        service
319            .add_node_to_config(project_root, "image-classifier", true)
320            .await
321            .expect("add_node_to_config should succeed");
322
323        let config = ConfigService::load_from(&project_root.join(paths::PROJECT_CONFIG))
324            .await
325            .expect("reload config");
326
327        assert!(
328            config.targets.simulation.is_none(),
329            "add_node_to_config must not synthesize any targets.* entry anymore"
330        );
331        let robot = config
332            .targets
333            .robot
334            .expect("pre-existing targets.robot must be preserved");
335        assert_eq!(
336            robot.nodes.iter().map(|n| n.name().to_string()).collect::<Vec<_>>(),
337            vec!["@mecha10/camera".to_string()],
338            "add_node_to_config must leave pre-existing targets.robot.nodes untouched, got {:?}",
339            robot.nodes
340        );
341    }
342}