use crate::error::TmuxFzfError;
use crate::tmux::{viewer_session_name, TmuxClient};
use crate::tmux_bindings;
pub fn parse_attach_target(arg: &str) -> Result<(String, Option<u32>), TmuxFzfError> {
match arg.split_once(':') {
None => Ok((arg.to_string(), None)),
Some((session, window)) => {
let window = window.parse().map_err(|_| {
TmuxFzfError::InvalidSessionName(format!(
"'{}' is not a window index in '{}'", window, arg
))
})?;
Ok((session.to_string(), Some(window)))
}
}
}
pub fn attach_managed(
client: &mut TmuxClient,
session: &str,
window: Option<u32>,
pane: Option<u32>,
) -> Result<(), TmuxFzfError> {
let viewer = if !client.is_inside_tmux()
&& client.session_attached_count(session).unwrap_or(0) > 0
{
let name = viewer_session_name(session, std::process::id());
let _ = client.kill_session(&name);
client.create_grouped_session(session, &name).ok()
} else {
None
};
let attach_session = viewer.as_deref().unwrap_or(session);
tmux_bindings::install_binding();
tmux_bindings::set_active(attach_session);
let result = match (window, pane) {
(None, _) => client.attach_session(attach_session),
(Some(w), None) => client.attach_window(attach_session, w),
(Some(w), Some(p)) => client.attach_pane(attach_session, w, p),
};
tmux_bindings::clear_active(attach_session);
if let Some(viewer_name) = &viewer {
let _ = client.kill_session(viewer_name);
}
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_attach_target_session_only() {
assert_eq!(parse_attach_target("dev").unwrap(), ("dev".to_string(), None));
}
#[test]
fn parse_attach_target_session_and_window() {
assert_eq!(parse_attach_target("dev:3").unwrap(), ("dev".to_string(), Some(3)));
}
#[test]
fn parse_attach_target_keeps_dashes_in_session_name() {
assert_eq!(
parse_attach_target("my-agent-1:0").unwrap(),
("my-agent-1".to_string(), Some(0))
);
}
#[test]
fn parse_attach_target_rejects_non_numeric_window() {
let err = parse_attach_target("dev:x").unwrap_err();
assert!(
matches!(err, TmuxFzfError::InvalidSessionName(_)),
"expected InvalidSessionName, got {:?}", err
);
}
#[test]
fn parse_attach_target_rejects_empty_window() {
assert!(parse_attach_target("dev:").is_err(), "trailing ':' has no window index");
}
}