use crate::error::SpriteError;
use crate::utils::session_recovery::{
analyze_session_health, cleanup_temp_files, generate_health_report, RecoveryConfig,
};
use crate::utils::tmux;
use anyhow::{Context, Result};
use std::io::{self, Write};
pub fn execute(session_name: Option<String>, force: bool, all: bool) -> Result<()> {
tmux::is_tmux_available()
.context("tmux is not available. Please install tmux to use sprite kill.")?;
if all {
return kill_all_sessions(force);
}
let sessions = match tmux::list_sessions() {
Ok(s) => s,
Err(_) => {
println!("๐ญ No tmux sessions found to kill.");
return Ok(());
}
};
if sessions.is_empty() {
println!("๐ญ No tmux sessions found to kill.");
return Ok(());
}
let target_session = match session_name {
Some(name) => name,
None => {
find_default_session(&sessions)?
}
};
if !sessions.iter().any(|s| s.name == target_session) {
return Err(SpriteError::session(
format!("Session '{}' does not exist. Use 'sprite attach --list' to see available sessions.", target_session),
Some(target_session)
).into());
}
let session_info = sessions.iter().find(|s| s.name == target_session).unwrap();
if !force {
confirm_session_kill(session_info)?;
}
cleanup_session_resources(&target_session)?;
println!("๐ช Killing tmux session: {}", target_session);
tmux::kill_session(&target_session)
.with_context(|| format!("Failed to kill session '{}'", target_session))?;
println!("โ
Session '{}' killed successfully", target_session);
Ok(())
}
fn kill_all_sessions(force: bool) -> Result<()> {
let sessions = tmux::list_sessions().context("Failed to list sessions")?;
if sessions.is_empty() {
println!("๐ญ No tmux sessions found to kill.");
return Ok(());
}
if !force {
confirm_kill_all_sessions(&sessions)?;
}
println!("๐ช Killing {} tmux session(s)...", sessions.len());
let mut killed_count = 0;
let mut failed_sessions = Vec::new();
for session in &sessions {
if let Err(e) = cleanup_session_resources(&session.name) {
eprintln!(
" โ ๏ธ Warning: Failed to cleanup session '{}': {}",
session.name, e
);
}
match tmux::kill_session(&session.name) {
Ok(()) => {
println!(" โ
Killed session: {}", session.name);
killed_count += 1;
}
Err(e) => {
eprintln!(" โ Failed to kill session '{}': {}", session.name, e);
failed_sessions.push(session.name.clone());
}
}
}
if killed_count > 0 {
println!("โ
Successfully killed {} session(s)", killed_count);
}
if !failed_sessions.is_empty() {
println!(
"โ ๏ธ Failed to kill {} session(s): {}",
failed_sessions.len(),
failed_sessions.join(", ")
);
if force && killed_count > 0 {
return Ok(());
}
return Err(SpriteError::tmux(format!(
"Failed to kill some sessions: {}",
failed_sessions.join(", ")
))
.into());
}
Ok(())
}
fn find_default_session(sessions: &[tmux::SessionInfo]) -> Result<String> {
if let Some(session) = sessions.iter().find(|s| s.name.contains("sprite-session")) {
return Ok(session.name.clone());
}
if let Some(session) = sessions.first() {
return Ok(session.name.clone());
}
Err(SpriteError::session(
"No tmux sessions found. Use 'sprite start' to create a new session.",
None::<String>,
)
.into())
}
fn confirm_session_kill(session_info: &tmux::SessionInfo) -> Result<()> {
println!("๐ฏ About to kill session:");
println!(
" Name: {} ({} windows)",
session_info.name, session_info.windows
);
println!(
" Status: {}",
if session_info.attached {
"๐ข Active"
} else {
"โช Detached"
}
);
print!("โ Are you sure you want to kill this session? [y/N] ");
io::stdout().flush().context("Failed to flush stdout")?;
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.context("Failed to read user input")?;
let input = input.trim().to_lowercase();
if input == "y" || input == "yes" {
Ok(())
} else {
println!("โ Session kill cancelled.");
Err(SpriteError::tmux("Session kill cancelled by user".to_string()).into())
}
}
fn confirm_kill_all_sessions(sessions: &[tmux::SessionInfo]) -> Result<()> {
println!("๐ฏ About to kill ALL {} tmux session(s):", sessions.len());
for session in sessions {
let status = if session.attached {
"๐ข Active"
} else {
"โช Detached"
};
println!(
" {} {} ({} windows)",
status, session.name, session.windows
);
}
print!("โ Are you sure you want to kill ALL sessions? This action cannot be undone. [y/N] ");
io::stdout().flush().context("Failed to flush stdout")?;
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.context("Failed to read user input")?;
let input = input.trim().to_lowercase();
if input == "y" || input == "yes" {
Ok(())
} else {
println!("โ Session kill cancelled.");
Err(SpriteError::tmux("Session kill cancelled by user".to_string()).into())
}
}
fn cleanup_session_resources(session_name: &str) -> Result<()> {
println!("๐งน Cleaning up resources for session: {}", session_name);
crate::utils::session_recovery::cleanup_session_resources(session_name)?;
Ok(())
}
#[allow(dead_code)]
pub fn check_session_health() -> Result<()> {
println!("๐ฅ Checking session health...");
let config = RecoveryConfig::default();
let health_reports = analyze_session_health(&config)?;
if health_reports.is_empty() {
println!("๐ญ No tmux sessions found.");
return Ok(());
}
let report = generate_health_report(&health_reports);
println!("{}", report);
let needs_attention = health_reports
.iter()
.any(|h| h.status != crate::utils::session_recovery::SessionStatus::Healthy);
if needs_attention {
println!("\n๐ก Some sessions need attention. Use 'sprite kill --force <session>' to cleanup problematic sessions.");
}
Ok(())
}
#[allow(dead_code)]
pub fn cleanup_old_resources() -> Result<()> {
println!("๐งน Starting cleanup of old resources...");
let config = RecoveryConfig {
auto_cleanup: true,
..Default::default()
};
let cleaned_sessions = crate::utils::session_recovery::cleanup_old_sessions(&config)?;
if !cleaned_sessions.is_empty() {
println!(
"โ
Cleaned up {} old session(s): {}",
cleaned_sessions.len(),
cleaned_sessions.join(", ")
);
} else {
println!("โ
No old sessions needed cleanup.");
}
cleanup_temp_files(&config)?;
println!("โ
Cleaned up temporary files.");
Ok(())
}
#[cfg(test)]
mod tests {
#[test]
fn test_find_default_session_with_sprite_session() {
}
#[test]
fn test_find_default_session_empty_list() {
}
}