Compare commits

..

No commits in common. "222f929fd4b76e8a5150c3f7b7f5f77165f2df3b" and "307ff23049a65d39bc827b4e59708c4ae7b2d081" have entirely different histories.

12 changed files with 221 additions and 412 deletions

View file

@ -1,6 +1,6 @@
[package] [package]
name = "remux" name = "remux"
version = "0.3.1" version = "0.2.1"
edition = "2021" edition = "2021"
authors = [ "Valerie Wolfe <sleeplessval@gmail.com>" ] authors = [ "Valerie Wolfe <sleeplessval@gmail.com>" ]
description = "A friendly command shortener for tmux" description = "A friendly command shortener for tmux"
@ -23,7 +23,7 @@ path = "src/main.rs"
[dependencies] [dependencies]
pico-args = { version = "0.5.0", features = [ "combined-flags", "eq-separator" ] } pico-args = { version = "0.5.0", features = [ "combined-flags", "eq-separator" ] }
termion = "2.0.1" termion = "2.0.1"
tmux_interface = "0.3.2" tmux_interface = "0.2.1"
[profile.release] [profile.release]
opt-level = 's' opt-level = 's'

View file

@ -7,20 +7,16 @@ A tmux wrapper and command shortener written in Rust. ReMux's
goal is to wrap tmux commands to be both shorter, and oriented goal is to wrap tmux commands to be both shorter, and oriented
around session names instead of session IDs. around session names instead of session IDs.
To further simplify developer usage, the `attach`, `detach`, `has`, and `new`
commands can be used without a target field, and will default to the name of
the Git repository root directory, if one is found.
In their shortest forms, *every* ReMux command is as short or In their shortest forms, *every* ReMux command is as short or
shorter than its equivalent tmux command: shorter than its equivalent tmux command:
```sh ```sh
# new session # new session
tmux new-s -t foo tmux new-session -t foo
remux n foo remux n foo
# list sessions # lists
tmux ls tmux ls
remux l remux l
remux remux
@ -30,11 +26,11 @@ tmux a -t foo
remux a foo remux a foo
# has # has
tmux h -t foo tmux has -t foo
remux h foo remux has foo
# detach # detach
tmux det -t foo tmux detach-client -t foo
remux d foo remux d foo
# nesting sessions with '-n' flag # nesting sessions with '-n' flag
@ -43,17 +39,12 @@ remux a -n foo
TMUX='' tmux new-session -t foo TMUX='' tmux new-session -t foo
remux n -n foo remux n -n foo
# switch to another session
tmux swi -t foo
rmux s foo
# cd to session path
tmux run 'printf "#{session_path}" > /tmp/tmux_path'
cd `cat /tmp/tmux_path`
cd `rmux p`
``` ```
If you're working in a git repository, the `attach`, `has`, and `new` commands
can be used without a session title, and the repository directory name will be
used instead.
## Dependencies ## Dependencies
ReMux depends on [tmux](https://github.com/tmux/tmux). ReMux depends on [tmux](https://github.com/tmux/tmux).
@ -94,10 +85,6 @@ using an AUR package manager such as <a href="https://github.com/Morganamilo/par
Install the package using Cargo with the command <code>cargo install tmux-remux</code>. Install the package using Cargo with the command <code>cargo install tmux-remux</code>.
</details> </details>
## Configuration
The pretty-print attached symbol (default: `*`) can be set manually by setting `REMUX_ATTACH_SYMBOL`.
## Libraries ## Libraries
- [pico-args](https://crates.io/crates/pico_args) — argument parsing - [pico-args](https://crates.io/crates/pico_args) — argument parsing

170
src/command.rs Normal file
View file

@ -0,0 +1,170 @@
use std::{
env::current_dir,
ffi::OsString,
process::exit
};
use pico_args::Arguments;
use termion::{ color, style };
use tmux_interface::TmuxCommand;
use crate::error;
use crate::util;
pub fn attach(pargs: &mut Arguments) {
util::prevent_nest();
// get optional flags
let read_only = pargs.contains(["-r", "--readonly"]);
let detach_other = pargs.contains(["-d", "--detach"]);
// collect target and window arguments
let args = pargs.clone().finish();
let target: String;
let window: Option<&OsString>;
if args.len() < 1 {
// missing name will attempt to fall back to repository
target = util::repo_fallback();
if !util::session_exists(target.clone()) { error::missing_target(); }
window = None;
} else {
target = args.get(0).unwrap().to_string_lossy().to_string();
window = args.get(1);
}
// focus window if provided
if window.is_some() {
let target = window.unwrap().to_string_lossy();
TmuxCommand::new()
.select_window()
.target_window(target)
.output().ok();
}
// make sure the target session exists
let exists = util::session_exists(target.clone());
if !exists { error::no_target(target.clone()); }
// build command
let mut attach = TmuxCommand::new().attach_session();
// handle optional flags
if read_only { attach.read_only(); }
if detach_other { attach.detach_other(); }
// run command
attach
.target_session(target)
.output().ok();
}
pub fn detach(pargs: &mut Arguments) {
// get target and error out if not provided
let args = pargs.clone().finish();
if args.len() < 1 { error::missing_target(); }
let target = args.get(0).unwrap().to_string_lossy();
// make sure the target session exists
let exists = util::session_exists(target.clone());
if !exists { error::no_target(target.clone()); }
// build command and run
TmuxCommand::new()
.detach_client()
.target_session(target)
.output().ok();
}
pub fn has(pargs: &mut Arguments) {
// get optional flag
let quiet = pargs.contains(["-q", "--quiet"]);
// collect target argument
let args = pargs.clone().finish();
let target: String;
if args.len() < 1 {
// missing name will attempt to fall back to repository
target = util::repo_fallback();
} else {
target = args.get(0).unwrap().to_string_lossy().to_string();
}
// run command
let success = util::session_exists(target.clone());
// handle optional flag
// inverted; print text if NOT quiet
if !quiet { println!("session \"{target}\" {}.", if success { "exists" } else { "does not exist" }); }
// exit codes for scripts to use
exit( if success { 0 } else { 1 });
}
pub fn list() {
// get session list
let sessions = util::get_sessions().unwrap_or(Vec::new());
// handle empty case
if sessions.len() == 0 {
println!("no sessions");
return;
}
// iterate over pretty print
println!("sessions:");
for session in sessions.into_iter() {
let group = session.group.unwrap_or("[untitled]".to_string());
let id = session.id.unwrap();
let attached = session.attached.unwrap_or(0) > 0;
println!(
" {group} ({bold}{blue}{id}{reset}) {bold}{green}{attach_sym}{reset}",
// values
attach_sym = if attached { "󰌹" } else {""},
// formatting
bold = style::Bold,
blue = color::Fg(color::Blue),
green = color::Fg(color::LightGreen),
reset = style::Reset
);
}
}
pub fn new(pargs: &mut Arguments) {
use pico_args::Error;
// show nest message
util::prevent_nest();
// get optional flag
let target_dir: Result<String, Error> = pargs.value_from_str(["-t", "--target"]);
// get target and error out if not provided
let args = pargs.clone().finish();
// collect name and command arguments
let title: String;
let command: Option<&OsString>;
if args.len() < 1 {
// missing name will attempt to fall back to repository
title = util::repo_fallback();
command = None;
} else {
title = args.get(0).unwrap().to_string_lossy().to_string();
command = args.get(1);
}
// build command
let mut new = TmuxCommand::new().new_session();
// handle shell command argument
if command.is_some() { new.shell_command(command.unwrap().to_string_lossy()); }
// run command
new
.session_name(title)
.attach()
.start_directory(target_dir.unwrap_or(current_dir().unwrap().to_string_lossy().to_string()))
.output().ok();
}

View file

@ -1,4 +0,0 @@
pub mod share;
pub mod session;

View file

@ -1,52 +0,0 @@
//! commands accessible from within a session
use std::fs::read_to_string;
use pico_args::Arguments;
use tmux_interface::{
Tmux,
commands
};
use crate::{ error, flag, util };
const TMP_ROOT: &str = "/tmp/remux_path";
pub fn switch(pargs: &mut Arguments) {
util::terminal_enforce();
// refuse to run outside a session
util::session_enforce("switch");
// consume optional flags
let read_only = pargs.contains(flag::READ_ONLY);
//TODO: -d flag handling needs to be done manually
let args = pargs.clone().finish();
if args.len() < 1 { error::missing_target(); }
let target = args.get(0).unwrap().to_string_lossy().to_string();
let exists = util::session_exists(target.clone());
if !exists { error::no_target(target.clone()); }
let mut switch = commands::SwitchClient::new();
switch = switch.target_session(target);
if read_only { switch.read_only = true; }
Tmux::new()
.add_command(switch)
.output().ok();
}
pub fn path() {
util::session_enforce("path");
let exec = commands::Run::new().shell_command("printf '#{session_path}' > ".to_string() + TMP_ROOT);
Tmux::new()
.add_command(exec)
.output().ok();
if let Ok(text) = read_to_string(TMP_ROOT) {
println!("{text}");
std::fs::remove_file(TMP_ROOT).ok();
}
}

View file

@ -1,193 +0,0 @@
//! globally available tmux commands.
use std::{
ffi::OsString,
process::exit
};
use pico_args::{ Arguments, Error };
use termion::{ color, style };
use tmux_interface::{
Tmux,
commands
};
use crate::{
env::{ self, env_var },
error,
flag,
util
};
pub fn attach(pargs: &mut Arguments) {
// must be run from terminal
util::terminal_enforce();
// don't allow unflagged nests
util::prevent_nest();
// consume optional flags
let read_only = pargs.contains(flag::READ_ONLY);
let detach_other = pargs.contains(flag::DETACH);
let args = pargs.clone().finish();
let target: String;
let window: Option<&OsString>;
if args.len() < 1 {
// missing name will attempt to fall back to repository
target = util::repo_fallback();
if !util::session_exists(target.clone()) { error::missing_target(); }
window = None;
} else {
target = args.get(0).unwrap().to_string_lossy().to_string();
window = args.get(1);
}
// make sure the session exists
let exists = util::session_exists(target.clone());
if !exists { error::no_target(target.clone()); }
// build attach command
let mut attach = commands::AttachSession::new();
attach = attach.target_session(target);
if read_only { attach.read_only = true; }
if detach_other { attach.detach_other = true; }
let select_window: Option<commands::SelectWindow>;
if let Some(window) = window {
let mut command = commands::SelectWindow::new();
command.target_window = Some(window.to_string_lossy());
select_window = Some(command);
} else { select_window = None; }
// build dispatch
let mut tmux = Tmux::new().add_command(attach);
if let Some(select_window) = select_window { tmux = tmux.add_command(select_window); }
tmux.output().ok();
}
pub fn detach(pargs: &mut Arguments) {
util::terminal_enforce();
// get target or fallback
let args = pargs.clone().finish();
let target: String;
if args.len() < 1 {
target = util::repo_fallback();
} else {
target = args.get(0).unwrap().to_string_lossy().to_string();
}
// make sure the session exists
let exists = util::session_exists(target.clone());
if !exists { error::no_target(target.clone()); }
// build and dispatch
let detach = commands::DetachClient::new()
.target_session(target);
Tmux::new()
.add_command(detach)
.disable_echo().output().ok();
}
pub fn has(pargs: &mut Arguments) {
// consume optional flags
let quiet = pargs.contains(flag::QUIET);
// get target or fallback
let args = pargs.clone().finish();
let target: String;
if args.len() < 1 {
target = util::repo_fallback();
} else {
target = args.get(0).unwrap().to_string_lossy().to_string();
}
// run command
let success = util::session_exists(target.clone());
// print if not quiet
if !quiet {
println!("session \"{target}\" {}.",
if success { "exists" }
else { "does not exist" }
);
}
// emit exit code
exit( if success { 0 } else { 1 });
}
pub fn list() {
// get session list
let sessions = util::get_sessions().unwrap_or(Vec::new());
// handle empty case
if sessions.len() == 0 {
println!("no sessions");
return;
}
// get attached session symbol
let attach_symbol = env_var(env::ATTACH_SYMBOL);
// pretty print session list
println!("sessions:");
for session in sessions.into_iter() {
let group = session.group.unwrap_or("[untitled]".to_string());
let id = session.id.unwrap();
let attached = session.attached.unwrap_or(0) > 0;
println!(
" {group} ({bold}{blue}{id}{reset}) {bold}{green}{attach}{reset}",
// values
attach = if attached { attach_symbol.clone() } else { "".to_string() },
// formatting
bold = style::Bold,
blue = color::Fg(color::Blue),
green = color::Fg(color::LightGreen),
reset = style::Reset
);
}
}
pub fn new(pargs: &mut Arguments) {
util::terminal_enforce();
// don't allow unflagged nesting
util::prevent_nest();
// get optional flags
let detached = pargs.contains(flag::DETACH);
let target_dir: Result<String, Error> = pargs.value_from_str(flag::TARGET);
// get environment variables
let window_name = env_var(env::NEW_WINDOW_NAME);
// get target or fallback
let args = pargs.clone().finish();
let title: String;
let command: Option<&OsString>;
if args.len() < 1 {
// attempt repo fallback
title = util::repo_fallback();
command = None;
} else {
title = args.get(0).unwrap().to_string_lossy().to_string();
command = args.get(1);
}
let mut new = commands::NewSession::new();
new = new.group_name(title);
if let Some(command) = command { new.shell_command = Some(command.to_string_lossy()); }
if detached { new.detached = true; }
if let Ok(target_dir) = target_dir { new = new.start_directory(target_dir); }
let mut tmux = Tmux::new().add_command(new);
// rename window if var not empty
if !window_name.is_empty() {
let auto_name = commands::RenameWindow::new()
.new_name(window_name);
tmux = tmux.add_command(auto_name);
}
tmux.output().ok();
}

View file

@ -1,13 +0,0 @@
use std::env::var;
pub type EnvVar = (&'static str, &'static str);
pub static ATTACH_SYMBOL: EnvVar = ("REMUX_ATTACH_SYMBOL", "*");
pub static NEW_WINDOW_NAME: EnvVar = ("REMUX_NEW_WINDOW", "");
pub fn env_var(envvar: EnvVar) -> String {
var(envvar.0).unwrap_or(envvar.1.to_string())
}
pub fn tmux() -> bool { !var("TMUX").unwrap_or("".to_string()).is_empty() }

View file

@ -37,9 +37,3 @@ pub fn not_nesting() {
exit(6); exit(6);
} }
/// tried to run a session command outside a session; code 7
pub fn not_in_session(cmd: &'static str) {
println!("remux: '{cmd}' must be run from within a session");
exit(7);
}

View file

@ -1,11 +0,0 @@
type Flag = [&'static str;2];
pub static DETACH: Flag = ["-d", "--detach"];
pub static HELP: Flag = ["-h", "--help"];
pub static NEST: Flag = ["-n", "--nest"];
pub static QUIET: Flag = ["-q", "--quiet"];
pub static READ_ONLY: Flag = ["-r", "--read-only"];
pub static TARGET: Flag = ["-t", "--target"];
pub static VERSION: Flag = ["-v", "--version"];

View file

@ -16,23 +16,14 @@ A command wrapper for tmux written in Rust.
usage: remux <command> [<args>] usage: remux <command> [<args>]
commands: commands:
help Show help text for remux, a command, or a help topic. help Show help text for remux or a specific command
attach Attach to an existing tmux session attach Attach to an existing tmux session
detach Detach clients from a tmux session detach Detach clients from a tmux session
has Check if a tmux session exists has Check if a tmux session exists
list Pretty-print all tmux sessions list Pretty-print all tmux sessions
new Create a new tmux session new Create a new tmux session
path print session path (session) Use 'remux help <command>' to see detailed help text for each command."),
switch switch to another session (session)
Use 'remux help <command>' to see detailed help text for each command.
help topics:
env Environment variables"),
// COMMAND HELP
Some("a" | "attach") Some("a" | "attach")
=> =>
@ -49,7 +40,7 @@ args:
flags: flags:
-d, --detach Detach other attached clients from the session -d, --detach Detach other attached clients from the session
-n, --nest Attach the session inside another session. -n, --nest Attach the session inside another session.
-r, --read-only Attach the session as read-only"), -r, --readonly Attach the session as read-only"),
Some("d" | "detach") Some("d" | "detach")
=> =>
@ -62,13 +53,12 @@ usage: remux detach <session>
args: args:
<session> The session name to detach clients from"), <session> The session name to detach clients from"),
Some("h" | "has") Some("has")
=> =>
println!("remux has println!("remux has
Check if the target session exists. Check if the target session exists.
usage: remux has [flags] <session> usage: remux has [flags] <session>
rmux h [flags] session
args: args:
<session> The session to check for <session> The session to check for
@ -91,7 +81,6 @@ println!("remux new
Create a new tmux session. Create a new tmux session.
usage: remux new [flags] <title> [command] usage: remux new [flags] <title> [command]
remux n [flags] <title> [command]
args: args:
<title> The title of the new session <title> The title of the new session
@ -101,47 +90,6 @@ flags:
-n, --nest Create the session inside another session. -n, --nest Create the session inside another session.
-t, --target <dir> Sets the target directory for the new session."), -t, --target <dir> Sets the target directory for the new session."),
Some("root")
=>
println!("remux path
Print the session path (#{{session_path}}) to standard output.
Must be run from inside a session.
usage: remux path
remux p"),
Some("s" | "switch")
=>
println!("remux switch
Switch to a different tmux session.
Must be run from inside a session.
usage: remux switch [flags] <title>
remux s [flags] <title>
args:
<title> The title of the session to switch to.
flags:
-r, --read-only Attach the target session as read-only."),
// TOPIC HELP
Some("env" | "vars")
=>
println!("remux environment variables
REMUX_ATTACH_SYMBOL
Changes the symbol displayed for attached sessions displayed
by the 'list' command.
Default: '*'
REMUX_NEW_WINDOW
Provides a default window name when creating a session with
the 'new' command, if not empty.
Default: ''"),
// not found // not found
_ => error::no_help(topic.unwrap()) _ => error::no_help(topic.unwrap())
} }

View file

@ -1,11 +1,12 @@
use std::env::{ set_var, var }; use std::{
env::{ set_var, var },
io::{ stdout, IsTerminal }
};
use pico_args::Arguments; use pico_args::Arguments;
mod command; mod command;
mod env;
mod error; mod error;
mod flag;
mod help; mod help;
mod util; mod util;
@ -18,17 +19,17 @@ fn main() {
let mut args = Arguments::from_env(); let mut args = Arguments::from_env();
// consume flags // consume flags
if args.contains(flag::HELP) { if args.contains(["-h", "--help"]) {
help(&mut args); help(&mut args);
return; return;
} }
if args.contains(flag::VERSION) { if args.contains(["-v", "--version"]) {
version(); version();
return; return;
} }
let nesting = args.contains(flag::NEST); let nesting = args.contains(["-n", "--nest"]);
let tmux_var = var("TMUX").ok(); let tmux_var = var("TMUX").ok();
if nesting { if nesting {
if tmux_var.is_none() { if tmux_var.is_none() {
@ -37,34 +38,30 @@ fn main() {
set_var("TMUX", ""); set_var("TMUX", "");
} }
if !stdout().is_terminal() { error::not_terminal(); }
let subcommand = args.subcommand().unwrap(); let subcommand = args.subcommand().unwrap();
// invoke subcommand function // invoke subcommand function
match subcommand.as_deref() { match subcommand.as_deref() {
Some("help") Some("h" | "help")
=> help(&mut args), => help(&mut args),
Some("a" | "attach") Some("a" | "attach")
=> command::share::attach(&mut args), => command::attach(&mut args),
Some("d" | "detach") Some("d" | "detach")
=> command::share::detach(&mut args), => command::detach(&mut args),
Some("h" | "has") Some("has")
=> command::share::has(&mut args), => command::has(&mut args),
None | None |
Some("l" | "ls" | "list") Some("l" | "ls" | "list")
=> command::share::list(), => command::list(),
Some("n" | "new") Some("n" | "new")
=> command::share::new(&mut args), => command::new(&mut args),
Some("p" | "path")
=> command::session::path(),
Some("s" | "switch")
=> command::session::switch(&mut args),
_ _
=> error::no_subcommand(subcommand.unwrap()) => error::no_subcommand(subcommand.unwrap())

View file

@ -1,58 +1,44 @@
use std::{ use std::{
env::current_dir, env::{ current_dir, var },
io::{ stdout, IsTerminal },
path::PathBuf, path::PathBuf,
process::exit process::exit
}; };
use tmux_interface::{ use tmux_interface::{
Session, Tmux, Session, Sessions, TmuxCommand,
variables::session::session::SESSION_ALL
commands,
variables::session::SessionsCtl
}; };
use crate::{ use crate::error;
env,
error
};
/// return a Vec of all sessions or None /// return a Vec of all sessions or None
pub fn get_sessions() -> Option<Vec<Session>> { pub fn get_sessions() -> Option<Vec<Session>> {
let sessions = SessionsCtl::new().get_all(); let i_sessions = Sessions::get(SESSION_ALL);
if let Ok(sessions) = sessions { if i_sessions.is_err() { return None; }
return Some(sessions.0); let sessions = i_sessions.ok();
} else { return None; } if sessions.is_none() { return None; }
Some(sessions.unwrap().0)
} }
/// show the tmux nest text if env var is not unset /// show the tmux nest text if env var is not unset
pub fn prevent_nest() { pub fn prevent_nest() {
if env::tmux() { let tmux = var("TMUX").ok();
println!("To nest sessions, use the -n flag."); if tmux.is_some() && tmux.unwrap() != "" {
exit(6); println!("Sessions should be nested with care; unset TMUX or use the '-n' flag to allow.");
exit(1);
} }
} }
/// enforce a command is being used in-session
pub fn session_enforce(cmd: &'static str) {
if !env::tmux() { error::not_in_session(cmd); }
}
/// check whether a target session exists /// check whether a target session exists
pub fn session_exists<S: Into<String>>(target: S) -> bool { pub fn session_exists<S: Into<String>>(target: S) -> bool {
let has_session = commands::HasSession::new() TmuxCommand::new()
.target_session(target.into()); .has_session()
Tmux::new().add_command(has_session) .target_session(target.into())
.status() .output().unwrap()
.unwrap()
.success() .success()
} }
/// enforce a command is being run in a terminal
pub fn terminal_enforce() {
if !stdout().is_terminal() { error::not_terminal(); }
}
/// attempt to return the repo name or exit /// attempt to return the repo name or exit
pub fn repo_fallback() -> String { pub fn repo_fallback() -> String {
let repo = repo_root(current_dir().unwrap()); let repo = repo_root(current_dir().unwrap());