remux/src/util.rs

59 lines
1.4 KiB
Rust
Raw Normal View History

use std::{
io::{ stdout, IsTerminal },
path::PathBuf
};
2023-04-06 13:34:32 -04:00
use tmux_interface::{
Session, Tmux,
commands,
variables::session::SessionsCtl
2023-04-06 13:34:32 -04:00
};
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
2023-04-06 13:34:32 -04:00
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; }
2023-04-06 13:34:32 -04:00
}
/// 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 }
}