remux/src/util.rs

58 lines
1.4 KiB
Rust

use std::{
io::{ stdout, IsTerminal },
path::PathBuf
};
use tmux_interface::{
Session, Tmux,
commands,
variables::session::SessionsCtl
};
use crate::error;
pub fn session_name() -> Option<String> {
let message = commands::DisplayMessage::new().print().message("#{session_name}");
let result = Tmux::new().add_command(message).output();
if let Ok(output) = result {
let text = String::from_utf8(output.0.stdout);
if let Ok(title) = text {
Some(title[0..title.len() - 1].to_owned())
} else { None }
} else { None }
}
/// return a Vec of all sessions or None
pub fn get_sessions() -> Option<Vec<Session>> {
let sessions = SessionsCtl::new().get_all();
if let Ok(sessions) = sessions {
return Some(sessions.0);
} else { return None; }
}
/// check whether a target session exists
pub fn session_exists<S: Into<String>>(target: S) -> bool {
let has_session = commands::HasSession::new()
.target_session(target.into());
Tmux::new().add_command(has_session)
.status()
.unwrap()
.success()
}
/// enforce a command is being run in a terminal
pub fn terminal_enforce() {
if !stdout().is_terminal() { error::not_terminal(); }
}
/// recursively propagate up directories to find a child
pub fn find(target: &'static str, path: PathBuf) -> Option<PathBuf> {
if path.join(target).exists() { return Some(path); }
let parent = path.parent();
if let Some(parent) = parent { return find(target, parent.to_path_buf()) }
else { None }
}