ggen_core/lifecycle/model.rs
1//! Data model for make.toml lifecycle configuration
2//!
3//! This module defines the data structures used to represent lifecycle configuration
4//! from `make.toml` files. It includes project metadata, phase definitions, workspace
5//! structure, and hook configurations.
6//!
7//! ## Features
8//!
9//! - **Project metadata**: Name, type, version, description
10//! - **Phase definitions**: Commands and configuration for each lifecycle phase
11//! - **Workspace support**: Monorepo workspace structure
12//! - **Hook system**: Before/after hooks for phases
13//! - **Default values**: Sensible defaults for optional fields
14//!
15//! ## Configuration Structure
16//!
17//! ### Project
18//! - `name`: Project name (required)
19//! - `type`: Project type (optional)
20//! - `version`: Project version (optional, defaults to "0.1.0")
21//! - `description`: Project description (optional)
22//!
23//! ### Lifecycle Phases
24//! Each phase defines:
25//! - `commands`: List of commands to execute
26//! - `env`: Environment variables (optional)
27//! - `inputs`: Input files for caching (optional)
28//!
29//! ### Hooks
30//! Hooks define before/after relationships:
31//! - `before_<phase>`: Phases that must run before this phase
32//! - `after_<phase>`: Phases that must run after this phase
33//!
34//! ## Examples
35//!
36//! ### Example make.toml
37//!
38//! ```toml
39//! [project]
40//! name = "my-project"
41//! version = "1.0.0"
42//!
43//! [lifecycle.build]
44//! commands = ["cargo build --release"]
45//!
46//! [lifecycle.test]
47//! commands = ["cargo test"]
48//!
49//! [hooks]
50//! before_build = ["test"]
51//! ```
52
53use serde::{Deserialize, Serialize};
54use std::collections::{BTreeMap, HashMap};
55
56/// Default configuration constants
57///
58/// **Kaizen improvement**: Extracted magic strings to named constants for maintainability.
59pub mod defaults {
60 /// Default project name when not specified
61 pub const DEFAULT_PROJECT_NAME: &str = "unnamed";
62
63 /// Default project version when not specified
64 pub const DEFAULT_PROJECT_VERSION: &str = "0.1.0";
65
66 /// Default project name for readiness reports
67 pub const DEFAULT_READINESS_PROJECT_NAME: &str = "Current Project";
68}
69
70/// Root configuration from make.toml
71#[derive(Debug, Clone, Deserialize, Serialize)]
72pub struct Make {
73 pub project: Project,
74 #[serde(default)]
75 pub workspace: Option<BTreeMap<String, Workspace>>,
76 #[serde(default)]
77 pub lifecycle: BTreeMap<String, Phase>,
78 #[serde(default)]
79 pub hooks: Option<Hooks>,
80}
81
82/// Project metadata
83#[derive(Debug, Clone, Deserialize, Serialize)]
84pub struct Project {
85 pub name: String,
86 #[serde(rename = "type")]
87 pub project_type: Option<String>,
88 #[serde(default)]
89 pub version: Option<String>,
90 #[serde(default)]
91 pub description: Option<String>,
92}
93
94/// Workspace definition for monorepos
95#[derive(Debug, Clone, Deserialize, Serialize)]
96pub struct Workspace {
97 pub path: String,
98 #[serde(default)]
99 pub framework: Option<String>,
100 #[serde(default)]
101 pub runtime: Option<String>,
102 #[serde(default)]
103 pub package_manager: Option<String>,
104}
105
106/// Lifecycle phase definition
107#[derive(Debug, Clone, Deserialize, Serialize)]
108pub struct Phase {
109 #[serde(default)]
110 pub description: Option<String>,
111
112 // Single or multiple commands
113 #[serde(default)]
114 pub command: Option<String>,
115 #[serde(default)]
116 pub commands: Option<Vec<String>>,
117
118 // Execution metadata
119 #[serde(default)]
120 pub watch: Option<bool>,
121 #[serde(default)]
122 pub port: Option<u16>,
123
124 // Output tracking for caching
125 #[serde(default)]
126 pub outputs: Option<Vec<String>>,
127 #[serde(default)]
128 pub cache: Option<bool>,
129
130 // Workspace control
131 #[serde(default)]
132 pub workspaces: Option<Vec<String>>,
133 #[serde(default)]
134 pub parallel: Option<bool>,
135}
136
137/// Hook definitions for lifecycle phases
138///
139/// Supports both predefined phase hooks (for backward compatibility) and
140/// dynamic custom phase hooks via `phase_hooks` HashMap.
141///
142/// **DfLSS Fix**: Added dynamic hook support to prevent hardcoded phase names
143/// and support extensibility for custom phases.
144#[derive(Debug, Clone, Deserialize, Serialize, Default)]
145pub struct Hooks {
146 // Global hooks
147 #[serde(default)]
148 pub before_all: Option<Vec<String>>,
149 #[serde(default)]
150 pub after_all: Option<Vec<String>>,
151
152 // Phase-specific hooks (predefined for backward compatibility)
153 #[serde(default)]
154 pub before_init: Option<Vec<String>>,
155 #[serde(default)]
156 pub after_init: Option<Vec<String>>,
157
158 #[serde(default)]
159 pub before_setup: Option<Vec<String>>,
160 #[serde(default)]
161 pub after_setup: Option<Vec<String>>,
162
163 #[serde(default)]
164 pub before_build: Option<Vec<String>>,
165 #[serde(default)]
166 pub after_build: Option<Vec<String>>,
167
168 #[serde(default)]
169 pub before_test: Option<Vec<String>>,
170 #[serde(default)]
171 pub after_test: Option<Vec<String>>,
172
173 #[serde(default)]
174 pub before_deploy: Option<Vec<String>>,
175 #[serde(default)]
176 pub after_deploy: Option<Vec<String>>,
177
178 // Dynamic hooks for custom phases (and predefined phases via TOML)
179 // Uses #[serde(flatten)] to allow TOML keys like "before_custom" to be deserialized
180 // while maintaining backward compatibility with explicit fields above
181 #[serde(flatten)]
182 pub phase_hooks: HashMap<String, Vec<String>>,
183 // Future: Error handling hooks (80/20 - not implemented yet, fail fast for now)
184 // #[serde(default)]
185 // pub on_error: Option<String>,
186 // #[serde(default)]
187 // pub on_success: Option<String>,
188}
189
190impl Phase {
191 /// Get commands for this phase (eliminates duplication)
192 pub fn commands(&self) -> Vec<String> {
193 if let Some(cmd) = &self.command {
194 vec![cmd.clone()]
195 } else if let Some(cmds) = &self.commands {
196 cmds.clone()
197 } else {
198 vec![]
199 }
200 }
201}
202
203/// Builder for creating validated phases
204///
205/// **Poka-yoke**: Ensures phases always have at least one command before they can be used.
206/// This prevents runtime errors from phases with no commands.
207///
208/// # Example
209///
210/// ```rust
211/// use crate::lifecycle::model::PhaseBuilder;
212///
213/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
214/// let phase = PhaseBuilder::new("build")
215/// .command("cargo build --release")
216/// .build()?;
217/// # Ok(())
218/// # }
219/// ```
220pub struct PhaseBuilder {
221 name: String,
222 description: Option<String>,
223 commands: Vec<String>,
224 watch: Option<bool>,
225 port: Option<u16>,
226 outputs: Option<Vec<String>>,
227 cache: Option<bool>,
228 workspaces: Option<Vec<String>>,
229 parallel: Option<bool>,
230}
231
232impl PhaseBuilder {
233 /// Create a new phase builder with the given name
234 pub fn new(name: impl Into<String>) -> Self {
235 Self {
236 name: name.into(),
237 description: None,
238 commands: Vec::new(),
239 watch: None,
240 port: None,
241 outputs: None,
242 cache: None,
243 workspaces: None,
244 parallel: None,
245 }
246 }
247
248 /// Set the phase description
249 pub fn description(mut self, description: impl Into<String>) -> Self {
250 self.description = Some(description.into());
251 self
252 }
253
254 /// Add a single command (replaces any existing commands)
255 pub fn command(mut self, cmd: impl Into<String>) -> Self {
256 self.commands = vec![cmd.into()];
257 self
258 }
259
260 /// Add multiple commands
261 pub fn commands(mut self, cmds: Vec<String>) -> Self {
262 self.commands = cmds;
263 self
264 }
265
266 /// Add a command to the existing list
267 pub fn add_command(mut self, cmd: impl Into<String>) -> Self {
268 self.commands.push(cmd.into());
269 self
270 }
271
272 /// Set watch mode
273 pub fn watch(mut self, watch: bool) -> Self {
274 self.watch = Some(watch);
275 self
276 }
277
278 /// Set port
279 pub fn port(mut self, port: u16) -> Self {
280 self.port = Some(port);
281 self
282 }
283
284 /// Set outputs
285 pub fn outputs(mut self, outputs: Vec<String>) -> Self {
286 self.outputs = Some(outputs);
287 self
288 }
289
290 /// Set cache flag
291 pub fn cache(mut self, cache: bool) -> Self {
292 self.cache = Some(cache);
293 self
294 }
295
296 /// Set workspaces
297 pub fn workspaces(mut self, workspaces: Vec<String>) -> Self {
298 self.workspaces = Some(workspaces);
299 self
300 }
301
302 /// Set parallel flag
303 pub fn parallel(mut self, parallel: bool) -> Self {
304 self.parallel = Some(parallel);
305 self
306 }
307
308 /// Build a validated phase
309 ///
310 /// **Poka-yoke**: Returns error if no commands are provided.
311 /// This ensures phases always have at least one command.
312 pub fn build(self) -> Result<ValidatedPhase, super::error::LifecycleError> {
313 if self.commands.is_empty() {
314 return Err(super::error::LifecycleError::NoCommands {
315 phase: self.name.clone(),
316 });
317 }
318
319 // Convert commands to Phase format (single command or multiple)
320 let (command, commands) = if self.commands.len() == 1 {
321 (Some(self.commands[0].clone()), None)
322 } else {
323 (None, Some(self.commands))
324 };
325
326 Ok(ValidatedPhase {
327 phase: Phase {
328 description: self.description,
329 command,
330 commands,
331 watch: self.watch,
332 port: self.port,
333 outputs: self.outputs,
334 cache: self.cache,
335 workspaces: self.workspaces,
336 parallel: self.parallel,
337 },
338 })
339 }
340}
341
342/// Validated phase that is guaranteed to have at least one command
343///
344/// **Poka-yoke**: This type can only be created through `PhaseBuilder::build()`,
345/// which ensures at least one command is present. This prevents runtime errors
346/// from phases with no commands.
347#[derive(Debug, Clone)]
348pub struct ValidatedPhase {
349 phase: Phase,
350}
351
352impl ValidatedPhase {
353 /// Get the underlying phase
354 pub fn phase(&self) -> &Phase {
355 &self.phase
356 }
357
358 /// Get commands (guaranteed to be non-empty)
359 pub fn commands(&self) -> Vec<String> {
360 self.phase.commands()
361 }
362
363 /// Get phase name (requires storing it separately or extracting from context)
364 /// For now, this is a limitation - phases don't store their own name
365 pub fn name(&self) -> Option<&str> {
366 None // Phase doesn't store name, it's the key in the map
367 }
368}
369
370impl AsRef<Phase> for ValidatedPhase {
371 fn as_ref(&self) -> &Phase {
372 &self.phase
373 }
374}
375
376impl Make {
377 /// Get list of all defined lifecycle phases
378 pub fn phase_names(&self) -> Vec<String> {
379 self.lifecycle.keys().cloned().collect()
380 }
381
382 /// Get commands for a phase
383 pub fn phase_commands(&self, phase_name: &str) -> Vec<String> {
384 self.lifecycle
385 .get(phase_name)
386 .map_or(vec![], |p| p.commands())
387 }
388}