Skip to main content

ferrum_cli/commands/
stop.rs

1//! Stop command - Stop the running server
2
3use clap::Args;
4use colored::*;
5use ferrum_types::Result;
6
7#[derive(Args)]
8pub struct StopCommand {}
9
10pub async fn execute(_cmd: StopCommand) -> Result<()> {
11    let pid_file = std::env::temp_dir().join("ferrum.pid");
12
13    if !pid_file.exists() {
14        println!("{}", "No running server found.".yellow());
15        return Ok(());
16    }
17
18    // Read PID
19    let pid_str = std::fs::read_to_string(&pid_file).map_err(|e| {
20        ferrum_types::FerrumError::io_str(format!("Failed to read PID file: {}", e))
21    })?;
22
23    let pid: i32 = pid_str
24        .trim()
25        .parse()
26        .map_err(|e| ferrum_types::FerrumError::io_str(format!("Invalid PID: {}", e)))?;
27
28    // Send SIGTERM
29    #[cfg(unix)]
30    {
31        use std::process::Command;
32        let status = Command::new("kill")
33            .args(["-TERM", &pid.to_string()])
34            .status();
35
36        match status {
37            Ok(s) if s.success() => {
38                println!("{} Server stopped (PID: {})", "✓".green().bold(), pid);
39                std::fs::remove_file(&pid_file).ok();
40            }
41            Ok(_) => {
42                println!(
43                    "{} Process {} not found (may have already stopped)",
44                    "⚠".yellow(),
45                    pid
46                );
47                std::fs::remove_file(&pid_file).ok();
48            }
49            Err(e) => {
50                eprintln!("{} Failed to stop server: {}", "✗".red().bold(), e);
51            }
52        }
53    }
54
55    #[cfg(windows)]
56    {
57        use std::process::Command;
58        let status = Command::new("taskkill")
59            .args(["/PID", &pid.to_string(), "/F"])
60            .status();
61
62        match status {
63            Ok(s) if s.success() => {
64                println!("{} Server stopped (PID: {})", "✓".green().bold(), pid);
65                std::fs::remove_file(&pid_file).ok();
66            }
67            _ => {
68                println!("{} Process {} not found", "⚠".yellow(), pid);
69                std::fs::remove_file(&pid_file).ok();
70            }
71        }
72    }
73
74    Ok(())
75}