tmux-tango 2.1.0

A CLI tool for managing tmux sessions - dance between your sessions!
Documentation
//! Tmux integration and session management.
//!
//! This module provides types and functionality for interacting with tmux,
//! including session parsing, command execution, and caching for performance.

use std::process::{Command, Stdio};
use std::env;
use std::sync::Arc;
use std::time::{Duration, Instant};
use crate::error::TmuxFzfError;

// Constants
const TMUX_ENV_VAR: &str = "TMUX";
const DEFAULT_WINDOWS: &str = "1";
const UNKNOWN_TIME: &str = "unknown";

/// Represents a tmux session with its metadata.
///
/// This struct uses `Arc<str>` for efficient cloning and sharing of session data.
#[derive(Debug, Clone, PartialEq)]
pub struct TmuxSession {
    /// The session name
    pub name: Arc<str>,
    /// Number of windows in the session
    pub windows: Arc<str>,
    /// Creation timestamp information
    #[allow(dead_code)]
    pub created: Arc<str>,
    /// The original output line from tmux
    #[allow(dead_code)]
    pub raw_line: Arc<str>,
}

impl TmuxSession {
    /// Parse a tmux session from a line of `tmux list-sessions` output.
    ///
    /// Expected format: `session-name: N windows (created timestamp)`
    pub fn from_line(line: &str) -> Self {
        // Split only on the first colon to separate name from info
        let mut parts = line.splitn(2, ':');
        let name: Arc<str> = parts.next().unwrap_or("").into();
        
        let info = parts.next().unwrap_or("");
        
        let windows: Arc<str> = if let Some(windows_start) = info.find(" windows") {
            info[..windows_start].trim().into()
        } else if let Some(window_start) = info.find(" window") {
            info[..window_start].trim().into()
        } else if !info.trim().is_empty() {
            info.trim().into()
        } else {
            DEFAULT_WINDOWS.into()
        };
        
        // Find the created timestamp - it starts after " windows" or " window"
        let created: Arc<str> = if let Some(pos) = info.find(" (created ") {
            info[pos..].into()
        } else {
            UNKNOWN_TIME.into()
        };
        
        Self {
            name,
            windows,
            created,
            raw_line: line.into(),
        }
    }

    /// Check if this session is currently attached.
    ///
    /// This is determined by checking if the raw line contains "(attached)"
    pub fn is_attached(&self) -> bool {
        self.raw_line.contains("(attached)")
    }
}

/// Client for interacting with tmux.
///
/// This client provides methods for listing, creating, attaching to, and managing
/// tmux sessions. It includes a cache for improved performance when listing sessions.
pub struct TmuxClient {
    session_cache: Option<(Vec<TmuxSession>, Instant)>,
}

impl TmuxClient {
    const CACHE_DURATION: Duration = Duration::from_millis(500);
    
    pub fn new() -> Self {
        Self {
            session_cache: None,
        }
    }
    
    pub fn list_sessions(&mut self) -> Result<Vec<TmuxSession>, TmuxFzfError> {
        if let Some((ref cached_sessions, cached_time)) = self.session_cache {
            if cached_time.elapsed() < Self::CACHE_DURATION {
                return Ok(cached_sessions.clone());
            }
        }
        
        let output = Command::new("tmux")
            .arg("list-sessions")
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .output()
            .map_err(|e| TmuxFzfError::TmuxError(format!("Failed to execute tmux command: {}", e)))?;
        
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            if stderr.contains("no sessions") || stderr.contains("no server running") {
                return Err(TmuxFzfError::NoSessions);
            }
            return Err(TmuxFzfError::TmuxError(format!("tmux list-sessions failed: {}", stderr)));
        }
        
        let stdout = String::from_utf8_lossy(&output.stdout);
        let sessions: Vec<TmuxSession> = stdout
            .lines()
            .filter(|line| !line.is_empty())
            .map(TmuxSession::from_line)
            .collect();
        
        self.session_cache = Some((sessions.clone(), Instant::now()));
        Ok(sessions)
    }
    
    pub fn attach_session(&self, session_name: &str) -> Result<(), TmuxFzfError> {
        let (command, action) = if self.is_inside_tmux() {
            ("switch-client", "switch to")
        } else {
            ("attach-session", "attach to")
        };

        let status = Command::new("tmux")
            .arg(command)
            .arg("-t")
            .arg(session_name)
            .stdin(Stdio::inherit())
            .stdout(Stdio::inherit())
            .stderr(Stdio::inherit())
            .status()
            .map_err(|e| TmuxFzfError::TmuxError(format!("Failed to execute tmux {}: {}", command, e)))?;

        if status.success() {
            Ok(())
        } else {
            let error_msg = match status.code() {
                Some(code) => {
                    format!("Failed to {} session '{}' (exit code: {})", action, session_name, code)
                },
                None => {
                    format!("tmux process was terminated while trying to {} session '{}'", action, session_name)
                }
            };

            Err(TmuxFzfError::TmuxError(error_msg))
        }
    }
    
    pub fn kill_session(&mut self, session_name: &str) -> Result<(), TmuxFzfError> {
        let status = Command::new("tmux")
            .arg("kill-session")
            .arg("-t")
            .arg(session_name)
            .status()
            .map_err(|e| TmuxFzfError::TmuxError(format!("Failed to execute tmux kill-session: {}", e)))?;
        
        if status.success() {
            self.session_cache = None; // Invalidate cache after successful kill
            Ok(())
        } else {
            Err(TmuxFzfError::TmuxError(format!(
                "Failed to kill session '{}' (exit code: {})", 
                session_name, status.code().unwrap_or(-1)
            )))
        }
    }
    
    pub fn rename_session(&mut self, old_name: &str, new_name: &str) -> Result<(), TmuxFzfError> {
        if new_name.is_empty() {
            return Err(TmuxFzfError::InvalidSessionName("Session name cannot be empty".to_string()));
        }
        
        if new_name.contains(':') {
            return Err(TmuxFzfError::InvalidSessionName("Session name cannot contain ':'".to_string()));
        }
        
        let status = Command::new("tmux")
            .arg("rename-session")
            .arg("-t")
            .arg(old_name)
            .arg(new_name)
            .status()
            .map_err(|e| TmuxFzfError::TmuxError(format!("Failed to execute tmux rename-session: {}", e)))?;
        
        if status.success() {
            self.session_cache = None; // Invalidate cache after successful rename
            Ok(())
        } else {
            Err(TmuxFzfError::TmuxError(format!(
                "Failed to rename session '{}' to '{}' (exit code: {})", 
                old_name, new_name, status.code().unwrap_or(-1)
            )))
        }
    }
    
    pub fn new_session(&mut self, session_name: Option<&str>) -> Result<String, TmuxFzfError> {
        self.new_session_with_attach(session_name, true)
    }
    
    fn new_session_with_attach(&mut self, session_name: Option<&str>, should_attach: bool) -> Result<String, TmuxFzfError> {
        if let Some(name) = session_name {
            if name.is_empty() {
                return Err(TmuxFzfError::InvalidSessionName("Session name cannot be empty".to_string()));
            }
            if name.contains(':') {
                return Err(TmuxFzfError::InvalidSessionName("Session name cannot contain ':'".to_string()));
            }
        }
        
        let mut cmd = Command::new("tmux");
        cmd.arg("new-session").arg("-d");
        
        if let Some(name) = session_name {
            cmd.arg("-s").arg(name);
        }
        
        // Set the working directory to current directory to ensure session starts in a good state
        if let Ok(current_dir) = std::env::current_dir() {
            cmd.arg("-c").arg(current_dir);
        }
        
        let output = cmd
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .output()
            .map_err(|e| TmuxFzfError::TmuxError(format!("Failed to execute tmux new-session: {}", e)))?;
        
        if output.status.success() {
            let created_name = if let Some(name) = session_name {
                name.to_string()
            } else {
                self.get_latest_session_name()?
            };
            
            
            if should_attach && !self.is_inside_tmux() {
                self.attach_session(&created_name)?;
            }
            
            self.session_cache = None; // Invalidate cache after successful creation
            Ok(created_name)
        } else {
            let stderr = String::from_utf8_lossy(&output.stderr);
            Err(TmuxFzfError::TmuxError(format!(
                "Failed to create session: {}", stderr
            )))
        }
    }
    
    pub fn is_inside_tmux(&self) -> bool {
        env::var(TMUX_ENV_VAR).is_ok()
    }
    
    fn get_latest_session_name(&mut self) -> Result<String, TmuxFzfError> {
        let sessions = self.list_sessions()?;
        sessions
            .last()
            .map(|s| s.name.as_ref().to_string())
            .ok_or(TmuxFzfError::NoSessions)
    }
    
    #[allow(dead_code)]
    pub fn has_sessions(&mut self) -> bool {
        self.list_sessions().is_ok()
    }
    
    pub fn clear_cache(&mut self) {
        self.session_cache = None;
    }
}