1use super::{cache::cache_key, error::*, loader::load_make, model::*, state::*};
60use std::path::{Path, PathBuf};
61use std::process::Command;
62use std::time::Instant;
63
64use std::collections::HashSet;
65use std::sync::{Arc, Mutex};
66
67pub struct Context {
69 pub root: PathBuf,
70 pub make: Arc<Make>,
71 pub state_path: PathBuf,
72 pub env: Vec<(String, String)>,
73 hook_guard: Arc<Mutex<HashSet<String>>>,
75 call_chain: Arc<Mutex<Vec<String>>>,
78}
79
80impl Context {
81 pub fn new(
83 root: PathBuf, make: Arc<Make>, state_path: PathBuf, env: Vec<(String, String)>,
84 ) -> Self {
85 Self {
86 root,
87 make,
88 state_path,
89 env,
90 hook_guard: Arc::new(Mutex::new(HashSet::new())),
91 call_chain: Arc::new(Mutex::new(Vec::new())),
92 }
93 }
94
95 fn enter_phase(&self, phase: &str) -> Result<()> {
99 let mut guard = self
100 .hook_guard
101 .lock()
102 .map_err(|_| LifecycleError::MutexPoisoned {
103 phase: phase.to_string(),
104 })?;
105
106 let mut chain = self
107 .call_chain
108 .lock()
109 .map_err(|_| LifecycleError::MutexPoisoned {
110 phase: phase.to_string(),
111 })?;
112
113 if guard.contains(phase) {
114 let cycle_start = chain.iter().position(|p| p == phase).unwrap_or(0);
116 let mut cycle = chain[cycle_start..].to_vec();
117 cycle.push(phase.to_string());
118
119 return Err(LifecycleError::hook_recursion_with_chain(
120 phase.to_string(),
121 cycle,
122 ));
123 }
124
125 guard.insert(phase.to_string());
126 chain.push(phase.to_string());
127 Ok(())
128 }
129
130 fn exit_phase(&self, phase: &str) {
134 match self.hook_guard.lock() {
135 Ok(mut guard) => {
136 guard.remove(phase);
137 }
138 Err(e) => {
139 tracing::error!(
142 phase = %phase,
143 error = %e,
144 "CRITICAL: Hook guard mutex poisoned - system may be in inconsistent state"
145 );
146 }
147 }
148
149 match self.call_chain.lock() {
151 Ok(mut chain) => {
152 if chain.last().map(|s| s.as_str()) == Some(phase) {
153 chain.pop();
154 }
155 }
156 Err(e) => {
157 tracing::error!(
158 phase = %phase,
159 error = %e,
160 "CRITICAL: Call chain mutex poisoned - system may be in inconsistent state"
161 );
162 }
163 }
164 }
165}
166
167#[tracing::instrument(name = "ggen.lifecycle.phase", skip(ctx), fields(phase = phase_name, duration_ms, status))]
169pub fn run_phase(ctx: &Context, phase_name: &str) -> Result<()> {
170 tracing::info!(phase = phase_name, "lifecycle phase starting");
171
172 ctx.enter_phase(phase_name)?;
174
175 let result = run_phase_internal(ctx, phase_name);
177 ctx.exit_phase(phase_name);
178
179 match &result {
181 Ok(()) => {
182 tracing::Span::current().record("status", "success");
183 tracing::info!(phase = phase_name, "lifecycle phase completed");
184 }
185 Err(e) => {
186 tracing::Span::current().record("status", "error");
187 tracing::error!(phase = phase_name, error = %e, "lifecycle phase failed");
188 }
189 }
190
191 result
192}
193
194fn run_phase_internal(ctx: &Context, phase_name: &str) -> Result<()> {
196 let phase = ctx
197 .make
198 .lifecycle
199 .get(phase_name)
200 .ok_or_else(|| LifecycleError::phase_not_found(phase_name))?;
201
202 run_before_hooks(ctx, phase_name)?;
204
205 crate::alert_info!(&format!("Running phase: {}", phase_name));
207
208 let cmds = phase.commands();
210 if cmds.is_empty() {
211 tracing::warn!(phase = %phase_name, "Phase has no commands");
212 return Ok(());
213 }
214
215 let key = cache_key(phase_name, &cmds, &ctx.env, &[]);
217
218 let started = current_time_ms()?;
220 let timer = Instant::now();
221
222 tracing::info!(phase = %phase_name, "Starting phase execution");
223 for cmd in &cmds {
224 tracing::debug!(phase = %phase_name, command = %cmd, "Executing command");
225 execute_command(cmd, &ctx.root, &ctx.env)?;
226 }
227
228 let duration = timer.elapsed().as_millis();
229
230 tracing::Span::current().record("duration_ms", duration);
232
233 tracing::info!(
234 phase = %phase_name,
235 duration_ms = duration,
236 "Phase completed successfully"
237 );
238
239 let mut state = load_state(&ctx.state_path)?;
241 state.record_run(phase_name.to_string(), started, duration, true);
242 state.add_cache_key(phase_name.to_string(), key);
243
244 use super::state_validation::ValidatedLifecycleState;
246 let validated_state = ValidatedLifecycleState::new(state.clone())
247 .map_err(|e| LifecycleError::Other(format!("State validation failed: {}", e)))?;
248
249 save_state(&ctx.state_path, validated_state.state())?;
250
251 run_after_hooks(ctx, phase_name)?;
253
254 Ok(())
255}
256
257#[tracing::instrument(name = "ggen.lifecycle.pipeline", skip(ctx), fields(phases = ?phases, phase_count = phases.len()))]
259pub fn run_pipeline(ctx: &Context, phases: &[String]) -> Result<()> {
260 tracing::info!(phases = ?phases, "starting lifecycle pipeline");
261 if let Some(workspaces) = &ctx.make.workspace {
262 let parallel = phases
264 .first()
265 .and_then(|p| ctx.make.lifecycle.get(p))
266 .and_then(|ph| ph.parallel)
267 .unwrap_or(false);
268
269 if parallel {
270 use rayon::prelude::*;
272 use rayon::ThreadPoolBuilder;
273
274 let max_threads = 8.min(num_cpus::get());
276 let pool = ThreadPoolBuilder::new()
277 .num_threads(max_threads)
278 .build()
279 .map_err(|e| {
280 LifecycleError::Other(format!("Failed to create thread pool: {}", e))
281 })?;
282
283 let results: Vec<Result<()>> = pool.install(|| {
284 workspaces
285 .par_iter()
286 .map(|(ws_name, workspace)| {
287 tracing::info!(workspace = %ws_name, "Processing workspace");
288 let ws_ctx = create_workspace_context(
289 &ctx.root, ws_name, workspace, &ctx.make, &ctx.env,
290 )?;
291
292 for phase in phases {
293 run_phase(&ws_ctx, phase)?;
294 }
295 Ok(())
296 })
297 .collect()
298 });
299
300 for result in results {
302 result?;
303 }
304 } else {
305 for (ws_name, workspace) in workspaces {
307 tracing::info!(workspace = %ws_name, "Processing workspace");
308 let ws_ctx =
309 create_workspace_context(&ctx.root, ws_name, workspace, &ctx.make, &ctx.env)?;
310
311 for phase in phases {
312 run_phase(&ws_ctx, phase)?;
313 }
314 }
315 }
316 } else {
317 for phase in phases {
319 run_phase(ctx, phase)?;
320 }
321 }
322
323 Ok(())
324}
325
326fn create_workspace_context(
330 root: &Path, ws_name: &str, workspace: &super::model::Workspace, root_make: &Arc<Make>,
331 env: &[(String, String)],
332) -> Result<Context> {
333 let ws_path = root.join(&workspace.path);
334
335 let canonical_root = root
337 .canonicalize()
338 .map_err(|e| LifecycleError::Other(format!("Failed to canonicalize root path: {}", e)))?;
339
340 let canonical_ws = ws_path.canonicalize().map_err(|e| {
341 LifecycleError::Other(format!(
342 "Failed to canonicalize workspace '{}' path: {}",
343 ws_name, e
344 ))
345 })?;
346
347 if !canonical_ws.starts_with(&canonical_root) {
349 return Err(LifecycleError::Other(format!(
350 "Security violation: workspace '{}' path '{}' is outside project root",
351 ws_name, workspace.path
352 )));
353 }
354
355 let ws_make_path = canonical_ws.join("make.toml");
356
357 let ws_make = if ws_make_path.exists() {
359 Arc::new(load_make(&ws_make_path)?)
360 } else {
361 Arc::clone(root_make)
362 };
363
364 let ws_state_path = canonical_ws.join(".ggen/state.json");
365
366 Ok(Context::new(
367 canonical_ws,
368 ws_make,
369 ws_state_path,
370 env.to_vec(),
371 ))
372}
373
374fn run_before_hooks(ctx: &Context, phase_name: &str) -> Result<()> {
379 if let Some(hooks) = &ctx.make.hooks {
380 if let Some(before_all) = &hooks.before_all {
382 for hook_phase in before_all {
383 run_phase(ctx, hook_phase)?;
384 }
385 }
386
387 let before_hooks = match phase_name {
390 "init" => hooks.before_init.as_ref(),
391 "setup" => hooks.before_setup.as_ref(),
392 "build" => hooks.before_build.as_ref(),
393 "test" => hooks.before_test.as_ref(),
394 "deploy" => hooks.before_deploy.as_ref(),
395 _ => None,
396 };
397
398 let hooks_list = before_hooks.or_else(|| {
400 let hook_key = format!("before_{}", phase_name);
401 hooks.phase_hooks.get(&hook_key)
402 });
403
404 if let Some(hooks_list) = hooks_list {
405 for hook_phase in hooks_list {
406 run_phase(ctx, hook_phase)?;
407 }
408 }
409 }
410
411 Ok(())
412}
413
414fn run_after_hooks(ctx: &Context, phase_name: &str) -> Result<()> {
419 if let Some(hooks) = &ctx.make.hooks {
420 let after_hooks = match phase_name {
423 "init" => hooks.after_init.as_ref(),
424 "setup" => hooks.after_setup.as_ref(),
425 "build" => hooks.after_build.as_ref(),
426 "test" => hooks.after_test.as_ref(),
427 "deploy" => hooks.after_deploy.as_ref(),
428 _ => None,
429 };
430
431 let hooks_list = after_hooks.or_else(|| {
433 let hook_key = format!("after_{}", phase_name);
434 hooks.phase_hooks.get(&hook_key)
435 });
436
437 if let Some(hooks_list) = hooks_list {
438 for hook_phase in hooks_list {
439 run_phase(ctx, hook_phase)?;
440 }
441 }
442
443 if let Some(after_all) = &hooks.after_all {
445 for hook_phase in after_all {
446 run_phase(ctx, hook_phase)?;
447 }
448 }
449 }
450
451 Ok(())
452}
453
454fn execute_command(cmd: &str, cwd: &Path, env: &[(String, String)]) -> Result<()> {
458 use std::time::Duration;
459
460 let mut command = if cfg!(target_os = "windows") {
461 let mut c = Command::new("cmd");
462 c.arg("/C");
463 c
464 } else {
465 let mut c = Command::new("sh");
466 c.arg("-c"); c
468 };
469
470 command.current_dir(cwd).arg(cmd);
471
472 for (key, value) in env {
473 command.env(key, value);
474 }
475
476 let mut child = command
478 .stdout(std::process::Stdio::inherit()) .stderr(std::process::Stdio::inherit()) .spawn()
481 .map_err(|e| LifecycleError::command_spawn("unknown", cmd, e))?;
482
483 const DEFAULT_COMMAND_TIMEOUT_SECS: u64 = 300;
486
487 let timeout = Duration::from_secs(DEFAULT_COMMAND_TIMEOUT_SECS);
488 let start = Instant::now();
489
490 loop {
491 match child
492 .try_wait()
493 .map_err(|e| LifecycleError::command_spawn("unknown", cmd, e))?
494 {
495 Some(status) => {
496 if !status.success() {
497 let exit_code = status.code().unwrap_or(-1);
498 return Err(LifecycleError::command_failed(
499 "unknown",
500 cmd,
501 exit_code,
502 "Command output shown above".to_string(),
503 ));
504 }
505 return Ok(());
506 }
507 None if start.elapsed() > timeout => {
508 let _ = child.kill(); return Err(LifecycleError::Other(format!(
511 "Command timeout after {}s: {}",
512 timeout.as_secs(),
513 cmd
514 )));
515 }
516 None => {
517 std::thread::sleep(Duration::from_millis(100));
519 }
520 }
521 }
522}
523
524fn current_time_ms() -> Result<u128> {
526 std::time::SystemTime::now()
527 .duration_since(std::time::UNIX_EPOCH)
528 .map(|d| d.as_millis())
529 .map_err(|_| LifecycleError::Other("System clock error: time is before UNIX epoch".into()))
530}
531
532