Compare commits

..

2 commits

Author SHA1 Message Date
390950a7e6 updated README 2024-03-08 10:19:23 -05:00
7ef44e9931 updated README 2024-03-08 10:18:14 -05:00
16 changed files with 213 additions and 1045 deletions

View file

@ -1,20 +1,12 @@
[package]
name = "remux"
version = "0.3.6"
version = "0.3.0"
edition = "2021"
authors = [ "Valerie Wolfe <sleeplessval@gmail.com>" ]
description = "A friendly command shortener for tmux"
homepage = "https://git.vwolfe.io/valerie/remux"
repository = "https://git.vwolfe.io/valerie/remux"
license = "MIT"
categories = [ "command-line-utilities" ]
keywords = [ "tmux", "remux" ]
[package.metadata.aur]
name = "remux"
type = "source"
archive = "archive/v$pkgver.tar.gz"
depends = [ "tmux>=3.0" ]
[[bin]]
name = "remux"

View file

@ -7,33 +7,40 @@ A tmux wrapper and command shortener written in Rust. ReMux's
goal is to wrap tmux commands to be both shorter, and oriented
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.
To further simplify developer workflows, the `attach`, `detach`, `has`, and
`new` commands will default to the name of the root directory if used inside
a Git repository.
In their shortest forms, *every* ReMux command is as short or
shorter than its equivalent tmux command:
## Goals
- Accelerating: Makes simple tmux workflows faster.
- Friendly: Easy to start using.
- Short: Every ReMux command is as short or shorter than its raw tmux equivalent.
<details>
<summary><h2>Examples</h2></summary>
```sh
# new session
tmux new-s -t foo
tmux new-session -t foo
remux n foo
# list sessions
# lists
tmux ls
remux l
remux
# attach
tmux a -t foo
remux a foo
# has
tmux h -t foo
remux h foo
tmux has -t foo
remux has foo
# detach
tmux det -t foo
tmux detach-client -t foo
remux d foo
# nesting sessions with '-n' flag
@ -42,16 +49,14 @@ remux a -n foo
TMUX='' tmux new-session -t foo
remux n -n foo
# switch to another session
tmux swi -t foo
rmux s foo
# cd to session path
cd `tmux display-mes -p "#{session_path}"`
cd `rmux p`
# switch
tmux switch-client -t foo
remux s foo
```
</details>
## Dependencies
ReMux depends on [tmux](https://github.com/tmux/tmux).
@ -62,47 +67,43 @@ ReMux depends on [tmux](https://github.com/tmux/tmux).
<details>
<summary>Release Binary</summary>
Copy the compiled binary from the <a href="https://git.vwolfe.io/valerie/remux/releases">releases page</a>
to a directory in <code>$PATH</code>, such as <code>/usr/bin/</code>.
Copy the compiled binary from the [releases page](https://git.vwolfe.io/valerie/remux/releases)
to a directory in `$PATH`, such as `/usr/bin/`.
</details>
<details>
<summary>Compile from Source</summary>
Compile using cargo with the command <code>cargo build --release</code> and copy
the file from <code>target/release/</code> to a directory in <code>$PATH</code>,
such as <code>/usr/bin/</code>.
Compile using cargo with the command `cargo build --release` and copy the file
from `target/release/` to a directory in `$PATH`, such as `/usr/bin/`.
</details>
<details>
<summary>makepkg (AUR)</summary>
Clone the <a href="https://aur.archlinux.org/remux.git">AUR Repository</a> and
run the command <code>makepkg --install</code>.
Clone the [AUR Repository](https://aur.archlinux.org/remux.git) and run the
command `makepkg --install`.
</details>
### Package Managers
<details>
<summary>Arch Linux (AUR): <code>remux</code></summary>
Install the package from the <a href="https://aur.archlinux.org/packages/remux"><code>remux</code> AUR Package</a>
using an AUR package manager such as <a href="https://github.com/Morganamilo/paru"><code>paru</code></a>.
Install the package from the [`remux` AUR Package](https://aur.archlinux.org/packages/remux)
using an AUR package manager such as [`paru`](https://github.com/Morganamilo/paru").
</details>
<details>
<summary>Cargo: <code>tmux-remux</code></summary>
Install the package using Cargo with the command <code>cargo install tmux-remux</code>.
</details>
### Supplemental
Install the package using Cargo with the command `cargo install tmux-remux`.
<details>
<summary>Bash Completions</summary>
Copy <code>bash-completion/remux</code> to the appropriate directory, typically
<code>/usr/share/bash-completion</code>.
</details>
<details>
<summary>Man Page: Section 1</summary>
Copy <code>man/remux.1</code> into <code>/usr/share/man/man1/</code>.
</details>
## Configuration

View file

@ -1,19 +0,0 @@
_remux() {
local word
COMPREPLY=()
word="${COMP_WORDS[COMP_CWORD]}"
case $COMP_CWORD in
1)
COMPREPLY=( `compgen -W 'attach detach has help list new path switch title' -- "$word"` )
;;
2)
COMPREPLY=( `compgen -W "$(remux l -q $word)"` )
;;
esac
return 0
}
complete -F _remux remux

View file

@ -1,4 +0,0 @@
[licenses]
allow = [ "MIT" ]

View file

@ -1,177 +0,0 @@
.Dd $Mdocdate$
.Dt REMUX 1
.Os
.Sh NAME
.Nm remux
.Nd a command shortener for
.Xr tmux 1
.Sh SYNOPSIS
.Nm remux
.Op Fl dhnqrtv
.Op Ar command
.Op args...
.Sh DESCRIPTION
.Nm
is a wrapper and command shortener for
.Xr tmux 1 ,
primarily focused on improving the ergonomics of using named sessions.
.Pp
If no command is provided, remux will use the context action. Inside a repository, remux will attach or create. If in a session or outside a repository, remux will list sessions.
.Sh COMMANDS
.Nm remux
commands are split into two categories: global commands, which can be used anywhere, and session commands, which can only be used from inside a session.
.Ss GLOBAL COMMANDS
.Bl -tag -width Ds
.It Xo Ic attach
.Op Fl dnr
.Op Ar title
.Op Ar window
.Xc
.Bd -literal -compact
aliases: a
Attaches to an existing session.
.Ed
.Pp
.Bl -tag -width Ds -compact
.It Fl d , Fl -detach
Detach all other connections to the session.
.It Fl n , Fl -nest
Allow nesting (attaching a session from inside another session).
.It Fl r , Fl -read-only
Attach the session in read-only mode.
.It Ar title
The title of the target session. If not given, remux will try to use the name of the repository containing the current directory.
.It Ar window
The name of the window to attach to.
.El
.It Xo Ic detach
.Op Ar title
.Xc
.Bd -literal -compact
aliases: d
Detaches all clients from the target session.
.Ed
.It Xo Ic has
.Op Fl q
.Op Ar title
.Xc
.Bd -literal -compact
aliases: h
Checks whether or not a session exists.
.Ed
.Pp
.Bl -tag -width Ds -compact
.It Fl q , Fl -quiet
Run silently without printing to standard output.
.It Ar title
The title of the target session. If not given, remux will attempt to use the name of the repository containing the current directory.
.El
.It Ic list
.Bd -literal -compact
aliases: l, ls
Pretty-prints a list of tmux sessions.
.Ed
.It Xo Ic new
.Op Fl dn
.Op Fl t\ |\ --target Ar path
.Op Ar title
.Op Ar command
.Xc
.Bd -literal -compact
aliases: n
Creates a new session.
.Ed
.Pp
.Bl -tag -width Ds -compact
.It Fl d , Fl -detach
Creates the session without attaching.
.It Fl n , Fl -nest
Allow nesting (attaching a session from inside another session).
.It Fl t , Fl -target Ar path
Sets the session path to the provided directory.
.It Ar title
Create the session with the given title. If not given, remux will attempt to use the name of the repository containing the current directory.
.El
.El
.Ss SESSION COMMANDS
.Bl -tag -width Ds
.It Ic path
.Bd -literal -compact
aliases: p
Prints the session path.
.Ed
.It Xo Ic switch
.Op Fl rd
.Op Ar title
.Xc
.Bd -literal -compact
aliases: s
Switches from the current session to the target.
.Ed
.Pp
.Bl -tag -width Ds -compact
.It Fl d , Fl -detach
Detaches other clients from the target session.
.It Fl r , Fl -read-only
Switch to the target session in read-only mode.
.It Ar title
The title of the session to switch to. If blank, the previous session will be used.
.El
.It Ic title
.Bd -literal -compact
aliases: t, which
Prints the session title.
.El
.Sh ENVIRONMENT
.Bl -tag -width Ds
.It Ev REMUX_ATTACH_SYMBOL
Changes the symbol displayed for attached sessions in the
.Ic list
command.
Default: '*'
.It Ev REMUX_CURRENT_SYMBOL
Changes the symbol displayed for the current session in the
.Ic list
command.
Default: '>'
.It Ev REMUX_NEW_WINDOW
Provides a default windows name when creating a new session. Unused if empty.
Default: (unset)
.It Ev REMUX_PREVIOUS_SYMBOL
Changes the symbol displayed for the previous session in the
.Ic list
command.
Default: '-'
.It Ev REMUX_REPO_FILE
The filename to match on when trying to find the root of a repository.
Default: '.git'
.El
.Sh EXIT STATUS
.Bl -tag -Width Ds
.It 1
Unmatched command name.
.It 2
Unmatched target session.
.It 3
Unmatched help topic.
.It 4
Missing or invalid target; target was not given or is the same as the current session.
.It 5
.Nm remux
is not running from within a terminal.
.It 6
Nesting error; nest flag is missing or inappropriate.
.It 7
A session command was attempted outside a session.
.Sh EXAMPLES
Use
.Ic path
to navigate to the session path:
.Pp
.Dl $ cd `remux p`
.Pp
.Sh SEE ALSO
.Xr tmux 1
.Sh AUTHORS
.An -nosplit
.An Valerie Wolfe Aq Mt sleeplessval@gmail.com

260
sbom.xml
View file

@ -1,260 +0,0 @@
{
"SPDXID": "SPDXRef-DOCUMENT",
"creationInfo": {
"created": "2024-03-14T20:41:35.559Z",
"creators": [
"Tool: cargo-sbom-v0.8.4"
]
},
"dataLicense": "CC0-1.0",
"documentNamespace": "https://spdx.org/spdxdocs/remux-eb288ebb-1cdd-412b-87c2-b15fc96cd8bd",
"files": [
{
"SPDXID": "SPDXRef-File-remux",
"checksums": [],
"fileName": "remux",
"fileTypes": [
"BINARY"
]
}
],
"name": "remux",
"packages": [
{
"SPDXID": "SPDXRef-Package-libredox-0.0.2",
"description": "Redox stable ABI",
"downloadLocation": "registry+https://github.com/rust-lang/crates.io-index",
"externalRefs": [
{
"referenceCategory": "PACKAGE-MANAGER",
"referenceLocator": "pkg:cargo/libredox@0.0.2",
"referenceType": "purl"
}
],
"licenseConcluded": "MIT",
"licenseDeclared": "MIT",
"name": "libredox",
"versionInfo": "0.0.2"
},
{
"SPDXID": "SPDXRef-Package-libc-0.2.153",
"description": "Raw FFI bindings to platform libraries like libc.\n",
"downloadLocation": "registry+https://github.com/rust-lang/crates.io-index",
"externalRefs": [
{
"referenceCategory": "PACKAGE-MANAGER",
"referenceLocator": "pkg:cargo/libc@0.2.153",
"referenceType": "purl"
}
],
"homepage": "https://github.com/rust-lang/libc",
"licenseConcluded": "MIT OR Apache-2.0",
"licenseDeclared": "MIT OR Apache-2.0",
"name": "libc",
"versionInfo": "0.2.153"
},
{
"SPDXID": "SPDXRef-Package-numtoa-0.1.0",
"description": "Convert numbers into stack-allocated byte arrays",
"downloadLocation": "registry+https://github.com/rust-lang/crates.io-index",
"externalRefs": [
{
"referenceCategory": "PACKAGE-MANAGER",
"referenceLocator": "pkg:cargo/numtoa@0.1.0",
"referenceType": "purl"
}
],
"licenseConcluded": "MIT OR Apache-2.0",
"licenseDeclared": "MIT OR Apache-2.0",
"name": "numtoa",
"versionInfo": "0.1.0"
},
{
"SPDXID": "SPDXRef-Package-termion-2.0.3",
"description": "A bindless library for manipulating terminals.",
"downloadLocation": "registry+https://github.com/rust-lang/crates.io-index",
"externalRefs": [
{
"referenceCategory": "PACKAGE-MANAGER",
"referenceLocator": "pkg:cargo/termion@2.0.3",
"referenceType": "purl"
}
],
"licenseConcluded": "MIT",
"licenseDeclared": "MIT",
"name": "termion",
"versionInfo": "2.0.3"
},
{
"SPDXID": "SPDXRef-Package-pico-args-0.5.0",
"description": "An ultra simple CLI arguments parser.",
"downloadLocation": "registry+https://github.com/rust-lang/crates.io-index",
"externalRefs": [
{
"referenceCategory": "PACKAGE-MANAGER",
"referenceLocator": "pkg:cargo/pico-args@0.5.0",
"referenceType": "purl"
}
],
"licenseConcluded": "MIT",
"licenseDeclared": "MIT",
"name": "pico-args",
"versionInfo": "0.5.0"
},
{
"SPDXID": "SPDXRef-Package-redox_termios-0.1.3",
"description": "A Rust library to access Redox termios functions",
"downloadLocation": "registry+https://github.com/rust-lang/crates.io-index",
"externalRefs": [
{
"referenceCategory": "PACKAGE-MANAGER",
"referenceLocator": "pkg:cargo/redox_termios@0.1.3",
"referenceType": "purl"
}
],
"licenseConcluded": "MIT",
"licenseDeclared": "MIT",
"name": "redox_termios",
"versionInfo": "0.1.3"
},
{
"SPDXID": "SPDXRef-Package-remux-0.2.1",
"description": "A friendly command shortener for tmux",
"downloadLocation": "NONE",
"homepage": "https://git.vwolfe.io/valerie/remux",
"licenseConcluded": "MIT",
"licenseDeclared": "MIT",
"name": "remux",
"versionInfo": "0.2.1"
},
{
"SPDXID": "SPDXRef-Package-bitflags-2.4.2",
"description": "A macro to generate structures which behave like bitflags.\n",
"downloadLocation": "registry+https://github.com/rust-lang/crates.io-index",
"externalRefs": [
{
"referenceCategory": "PACKAGE-MANAGER",
"referenceLocator": "pkg:cargo/bitflags@2.4.2",
"referenceType": "purl"
}
],
"homepage": "https://github.com/bitflags/bitflags",
"licenseConcluded": "MIT OR Apache-2.0",
"licenseDeclared": "MIT OR Apache-2.0",
"name": "bitflags",
"versionInfo": "2.4.2"
},
{
"SPDXID": "SPDXRef-Package-bitflags-1.3.2",
"description": "A macro to generate structures which behave like bitflags.\n",
"downloadLocation": "registry+https://github.com/rust-lang/crates.io-index",
"externalRefs": [
{
"referenceCategory": "PACKAGE-MANAGER",
"referenceLocator": "pkg:cargo/bitflags@1.3.2",
"referenceType": "purl"
}
],
"homepage": "https://github.com/bitflags/bitflags",
"licenseConcluded": "MIT OR Apache-2.0",
"licenseDeclared": "MIT/Apache-2.0",
"name": "bitflags",
"versionInfo": "1.3.2"
},
{
"SPDXID": "SPDXRef-Package-redox_syscall-0.4.1",
"description": "A Rust library to access raw Redox system calls",
"downloadLocation": "registry+https://github.com/rust-lang/crates.io-index",
"externalRefs": [
{
"referenceCategory": "PACKAGE-MANAGER",
"referenceLocator": "pkg:cargo/redox_syscall@0.4.1",
"referenceType": "purl"
}
],
"licenseConcluded": "MIT",
"licenseDeclared": "MIT",
"name": "redox_syscall",
"versionInfo": "0.4.1"
},
{
"SPDXID": "SPDXRef-Package-tmux_interface-0.2.1",
"description": "Rust language library for communication with TMUX via CLI",
"downloadLocation": "registry+https://github.com/rust-lang/crates.io-index",
"externalRefs": [
{
"referenceCategory": "PACKAGE-MANAGER",
"referenceLocator": "pkg:cargo/tmux_interface@0.2.1",
"referenceType": "purl"
}
],
"licenseConcluded": "MIT",
"licenseDeclared": "MIT",
"name": "tmux_interface",
"versionInfo": "0.2.1"
}
],
"relationships": [
{
"relatedSpdxElement": "SPDXRef-Package-libc-0.2.153",
"relationshipType": "DEPENDS_ON",
"spdxElementId": "SPDXRef-Package-termion-2.0.3"
},
{
"relatedSpdxElement": "SPDXRef-Package-termion-2.0.3",
"relationshipType": "DEPENDS_ON",
"spdxElementId": "SPDXRef-Package-remux-0.2.1"
},
{
"relatedSpdxElement": "SPDXRef-Package-redox_syscall-0.4.1",
"relationshipType": "DEPENDS_ON",
"spdxElementId": "SPDXRef-Package-libredox-0.0.2"
},
{
"relatedSpdxElement": "SPDXRef-Package-numtoa-0.1.0",
"relationshipType": "DEPENDS_ON",
"spdxElementId": "SPDXRef-Package-termion-2.0.3"
},
{
"relatedSpdxElement": "SPDXRef-Package-tmux_interface-0.2.1",
"relationshipType": "DEPENDS_ON",
"spdxElementId": "SPDXRef-Package-remux-0.2.1"
},
{
"relatedSpdxElement": "SPDXRef-Package-pico-args-0.5.0",
"relationshipType": "DEPENDS_ON",
"spdxElementId": "SPDXRef-Package-remux-0.2.1"
},
{
"relatedSpdxElement": "SPDXRef-Package-redox_termios-0.1.3",
"relationshipType": "DEPENDS_ON",
"spdxElementId": "SPDXRef-Package-termion-2.0.3"
},
{
"relatedSpdxElement": "SPDXRef-Package-libc-0.2.153",
"relationshipType": "DEPENDS_ON",
"spdxElementId": "SPDXRef-Package-libredox-0.0.2"
},
{
"relatedSpdxElement": "SPDXRef-Package-bitflags-1.3.2",
"relationshipType": "DEPENDS_ON",
"spdxElementId": "SPDXRef-Package-redox_syscall-0.4.1"
},
{
"relatedSpdxElement": "SPDXRef-Package-remux-0.2.1",
"relationshipType": "GENERATED_FROM",
"spdxElementId": "SPDXRef-File-remux"
},
{
"relatedSpdxElement": "SPDXRef-Package-bitflags-2.4.2",
"relationshipType": "DEPENDS_ON",
"spdxElementId": "SPDXRef-Package-libredox-0.0.2"
},
{
"relatedSpdxElement": "SPDXRef-Package-libredox-0.0.2",
"relationshipType": "DEPENDS_ON",
"spdxElementId": "SPDXRef-Package-termion-2.0.3"
}
],
"spdxVersion": "SPDX-2.3"
}

View file

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

View file

@ -1,67 +0,0 @@
//! commands accessible from within a session
use tmux_interface::{
Tmux,
commands
};
use crate::{
error,
state::State,
util::{
self,
message,
MSG_PREVIOUS, MSG_SESSION_PATH, NULL
}
};
pub fn path(state: &mut State) {
state.session_enforce("path");
if let Some(message) = message(MSG_SESSION_PATH) {
println!("{message}");
}
}
pub fn switch(state: &mut State) {
util::terminal_enforce();
// refuse to run outside a session
state.session_enforce("switch");
// consume optional flags
let read_only = state.flags.read_only;
let detach_other = state.flags.detached;
let args = state.args.clone().finish();
let target: String = match if let Some(inner) = args.get(0) { inner.to_str() } else { None } {
None |
Some("-") => if let Some(prev) = message(MSG_PREVIOUS) { prev }
else { error::missing_target() },
Some(inner) => inner.to_owned()
};
let exists = util::session_exists(target.clone());
if !exists { error::no_target(target.clone()); }
let mut tmux = Tmux::new();
if detach_other {
let detach = commands::DetachClient::new()
.target_session(&target);
tmux = tmux.add_command(detach);
}
let mut switch = commands::SwitchClient::new();
switch = switch.target_session(&target);
if read_only { switch.read_only = true; }
tmux.add_command(switch)
.stderr(NULL).output().ok();
}
pub fn title(state: State) {
state.session_enforce("title");
if let Some(title) = state.title { println!("{title}"); }
}

View file

@ -1,5 +1,9 @@
//! globally available tmux commands.
use std::process::exit;
use std::{
env::var,
ffi::OsString,
process::exit
};
use pico_args::{ Arguments, Error };
use termion::{ color, style };
@ -8,36 +12,28 @@ use tmux_interface::{
commands
};
use crate::{
env::{
self,
env_var,
SYMBOL_ATTACH, SYMBOL_CURRENT, SYMBOL_PREV
},
error,
flag,
state::State,
util::{
self,
message,
MSG_PREVIOUS, NULL
}
};
use crate::{ error, flag, util };
pub fn attach(state: &mut State) {
util::terminal_enforce();
state.nest_init();
pub fn attach(pargs: &mut Arguments) {
// don't allow unflagged nests
util::prevent_nest();
// consume optional flags
let read_only = state.flags.read_only;
let detach_other = state.flags.detached;
let read_only = pargs.contains(flag::READ_ONLY);
let detach_other = pargs.contains(flag::DETACHED);
// consume arguments
let target = state.target_title().unwrap();
let window = state.target();
// do not allow attaching to the same session
if state.session && target == state.title.clone().unwrap() { error::same_session(); }
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());
@ -52,41 +48,25 @@ pub fn attach(state: &mut State) {
let select_window: Option<commands::SelectWindow>;
if let Some(window) = window {
let mut command = commands::SelectWindow::new();
command.target_window = Some(window.into());
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.stderr(NULL).output().ok();
state.nest_deinit();
tmux.output().ok();
}
pub fn context_action(state: &mut State) {
if !state.session {
if let Some(repository) = &state.repository {
let target = repository.name.clone();
let mut args = Arguments::from_vec( vec![(&target).into()] );
let mut substate = State::new(&mut args);
substate.flags = state.flags.clone();
if util::session_exists(&target) {
attach(&mut substate);
pub fn detach(pargs: &mut Arguments) {
// get target or fallback
let args = pargs.clone().finish();
let target: String;
if args.len() < 1 {
target = util::repo_fallback();
} else {
new(&mut substate);
target = args.get(0).unwrap().to_string_lossy().to_string();
}
return;
}
}
// fallback behavior is list
list(state);
}
pub fn detach(state: &mut State) {
util::terminal_enforce();
let target = state.target_title().unwrap();
// make sure the session exists
let exists = util::session_exists(target.clone());
@ -97,15 +77,21 @@ pub fn detach(state: &mut State) {
.target_session(target);
Tmux::new()
.add_command(detach)
.disable_echo().output().ok();
.output().ok();
}
pub fn has(state: &mut State) {
pub fn has(pargs: &mut Arguments) {
// consume optional flags
let quiet = state.flags.quiet;
let quiet = pargs.contains(flag::QUIET);
// get target
let target = state.target_title().unwrap();
// 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());
@ -122,13 +108,10 @@ pub fn has(state: &mut State) {
exit( if success { 0 } else { 1 });
}
pub fn list(state: &mut State) {
pub fn list() {
// get session list
let sessions = util::get_sessions().unwrap_or(Vec::new());
let search = state.target();
let previous = message(MSG_PREVIOUS);
// handle empty case
if sessions.len() == 0 {
println!("no sessions");
@ -136,81 +119,56 @@ pub fn list(state: &mut State) {
}
// get attached session symbol
let attach_symbol = env_var(SYMBOL_ATTACH);
let current_symbol = env_var(SYMBOL_CURRENT);
let prev_symbol = env_var(SYMBOL_PREV);
let attach_symbol = var("REMUX_ATTACH_SYMBOL").unwrap_or("*".to_string());
// pretty print session list
if !state.flags.quiet { println!("sessions:"); }
for session in sessions {
let name = session.name.unwrap_or("[untitled]".to_string());
if search.is_some() && !name.starts_with(search.as_ref().unwrap()) { continue; }
if !state.flags.quiet {
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;
let compare = Some(name.clone());
let marker =
if compare == state.title { current_symbol.clone() }
else if state.session && compare == previous { prev_symbol.clone() }
else { " ".to_string() };
println!(
" {marker} {name}{reset} ({bold}{blue}{id}{reset}) {bold}{green}{attach}{reset}",
" {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,
reset = style::Reset
);
} else {
print!("{name} ");
}
}
}
pub fn new(state: &mut State) {
util::terminal_enforce();
pub fn new(pargs: &mut Arguments) {
// don't allow unflagged nesting
util::prevent_nest();
// get optional flags
let detached = state.flags.detached;
let target_dir: Result<String, Error> = state.args.value_from_str(flag::TARGET);
// get optional flag
let target_dir: Result<String, Error> = pargs.value_from_str(flag::TARGET);
// delayed nest_init; detached behavior conflicts with nest
if !detached { state.nest_init(); }
else if state.flags.nested { error::conflict_nest(Some("detached session is not nesting")); }
// get environment variables
let window_name = env_var(env::NEW_WINDOW_NAME);
// consume arguments
let title = state.target_title().unwrap();
let command = state.target();
// don't allow duplicate names
let exists = util::session_exists(title.clone());
if exists { error::target_exists(title.clone()); }
// 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.session_name(title);
if let Some(command) = command { new.shell_command = Some(command.into()); }
if detached { new.detached = true; }
new = new.group_name(title);
if let Some(command) = command { new.shell_command = Some(command.to_string_lossy()); }
if let Ok(target_dir) = target_dir { new = new.start_directory(target_dir); }
let mut tmux = Tmux::new().add_command(new);
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.stderr(NULL).output().ok();
.output().ok();
}

View file

@ -1,17 +0,0 @@
use std::env::var;
pub type EnvVar = (&'static str, &'static str);
pub const NEW_WINDOW_NAME: EnvVar = ("REMUX_NEW_WINDOW", "");
pub const REPO_FILE: EnvVar = ("REMUX_REPO_FILE", ".git");
pub const SYMBOL_ATTACH: EnvVar = ("REMUX_ATTACH_SYMBOL", "*");
pub const SYMBOL_CURRENT: EnvVar = ("REMUX_CURRENT_SYMBOL", ">");
pub const SYMBOL_PREV: EnvVar = ("REMUX_PREVIOUS_SYMBOL", "-");
pub const TMUX: &str = "TMUX";
/// get or default an environment variable
pub fn env_var(envvar: EnvVar) -> String {
var(envvar.0).unwrap_or(envvar.1.to_string())
}

View file

@ -1,77 +1,39 @@
use std::process::exit;
/// no subcommand that matches user input; code 1
pub fn no_subcommand(subcommand: String) -> ! {
eprintln!("remux: no command match for \"{subcommand}\"");
pub fn no_subcommand(subcommand: String) {
println!("remux: no command match for \"{subcommand}\"");
exit(1);
}
/// target session not found; code 2
pub fn no_target<S: Into<String>>(target: S) -> ! {
pub fn no_target<S: Into<String>>(target: S) {
let target = target.into();
eprintln!("remux: no session \"{target}\" exists");
println!("remux: no session \"{target}\" exists");
exit(2);
}
/// help topic doesn't exist; code 3
pub fn no_help(topic: String) -> ! {
eprintln!("remux: no help for \"{topic}\"");
pub fn no_help(topic: String) {
println!("remux: no help for \"{topic}\"");
exit(3);
}
/// user provided no target; code 4
pub fn missing_target() -> ! {
eprintln!("remux: no target provided");
pub fn missing_target() {
println!("remux: no target provided");
exit(4);
}
/// refuse to attach to current session; code 4
pub fn same_session() -> ! {
eprintln!("remux: cannot attach to same session");
exit(4);
}
/// a session with the target name already exists; code 4
pub fn target_exists<S: Into<String>>(target: S) -> ! {
let target = target.into();
eprintln!("remux: session \"{target}\" already exists");
exit(4);
}
/// non-terminal environment prevention; code 5
pub fn not_terminal() -> ! {
eprintln!("remux: not running from a terminal");
pub fn not_terminal() {
println!("remux: not running from a terminal");
exit(5);
}
/// tried to nest while not in a session; code 6
pub fn not_nesting() -> ! {
eprintln!("remux: inappropriate nesting flag (-n); not in a session");
pub fn not_nesting() {
println!("remux: cannot use nesting flag outside a TMUX session");
exit(6);
}
/// operation requires nesting flag; code 6
pub fn prevent_nest() -> ! {
eprintln!("remux: the nesting flag (-n) is required for nesting operation");
exit(6);
}
/// operation conflicts with nesting flag; code 6
pub fn conflict_nest(reason: Option<&'static str>) -> ! {
if let Some(reason) = reason { eprintln!("remux: inappropriate nesting flag (-n): {reason}"); }
else { eprintln!("remux: nesting flag (-n) is inappropriate for this operation."); }
exit(6);
}
/// tried to run a session command outside a session; code 7
pub fn not_in_session(cmd: &'static str) -> ! {
eprintln!("remux: '{cmd}' must be run from within a session");
exit(7);
}

View file

@ -1,9 +1,7 @@
use pico_args::Arguments;
type Flag = [&'static str;2];
pub static DETACH: Flag = ["-d", "--detach"];
pub static DETACHED: Flag = ["-d", "--detached"];
pub static HELP: Flag = ["-h", "--help"];
pub static NEST: Flag = ["-n", "--nest"];
pub static QUIET: Flag = ["-q", "--quiet"];
@ -11,41 +9,3 @@ pub static READ_ONLY: Flag = ["-r", "--read-only"];
pub static TARGET: Flag = ["-t", "--target"];
pub static VERSION: Flag = ["-v", "--version"];
pub struct Flags {
pub detached: bool,
pub nested: bool,
pub quiet: bool,
pub read_only: bool,
pub target: Option<String>,
}
impl Flags {
pub fn from(args: &mut Arguments) -> Flags {
let detached = args.contains(DETACH);
let nested = args.contains(NEST);
let quiet = args.contains(QUIET);
let read_only = args.contains(READ_ONLY);
let target = args.value_from_str(TARGET).ok();
Flags {
detached,
nested,
quiet,
read_only,
target
}
}
pub fn clone(&self) -> Flags {
Flags {
detached: self.detached,
nested: self.nested,
quiet: self.quiet,
read_only: self.read_only,
target: None
}
}
}

View file

@ -13,27 +13,17 @@ println!("remux v{VERSION}
Valerie Wolfe <sleeplessval@gmail.com>
A command wrapper for tmux written in Rust.
usage: remux [command] [<args>]
usage: remux <command> [<args>]
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
detach Detach clients from a tmux session
has Check if a tmux session exists
list Pretty-print all tmux sessions
new Create a new tmux session
path print session path (session)
switch switch to another session (session)
title print session title (session)
Use 'remux help <command>' to see detailed help text for each command.
help topics:
env Environment variables"),
// COMMAND HELP
Use 'remux help <command>' to see detailed help text for each command."),
Some("a" | "attach")
=>
@ -63,13 +53,12 @@ usage: remux detach <session>
args:
<session> The session name to detach clients from"),
Some("h" | "has")
Some("has")
=>
println!("remux has
Check if the target session exists.
usage: remux has [flags] <session>
rmux h [flags] session
args:
<session> The session to check for
@ -102,62 +91,6 @@ flags:
-n, --nest Create the session inside another session.
-t, --target <dir> Sets the target directory for the new session."),
Some("p" | "path")
=>
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."),
Some("w" | "which" | "title")
=>
println!("remux which
Print the title of the current session.
usage: remux which
remux w
remux title"),
// 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_CURRENT_SYMBOL
Changes the symbol displayed to denote the current session
in the 'list' command.
Default: '>'
REMUX_NEW_WINDOW
Provides a default window name when creating a session with
the 'new' command, if not empty.
Default: (unset)"),
// not found
_ => error::no_help(topic.unwrap())
}

View file

@ -1,16 +1,17 @@
use std::{
env::{ set_var, var },
io::{ stdout, IsTerminal }
};
use pico_args::Arguments;
mod command;
mod env;
mod error;
mod flag;
mod help;
mod state;
mod util;
use help::{ help, version };
use state::State;
static VERSION: &str = env!("CARGO_PKG_VERSION");
@ -29,44 +30,47 @@ fn main() {
return;
}
let mut state = State::new(&mut args);
let target = state.target();
// invoke subcommand function
match target.as_deref() {
Some("help")
=> help(&mut args),
None
=> command::share::context_action(&mut state),
Some("a" | "attach")
=> command::share::attach(&mut state),
Some("d" | "detach")
=> command::share::detach(&mut state),
Some("h" | "has")
=> command::share::has(&mut state),
Some("l" | "ls" | "list")
=> command::share::list(&mut state),
Some("n" | "new")
=> command::share::new(&mut state),
Some("p" | "path")
=> command::session::path(&mut state),
Some("s" | "switch")
=> command::session::switch(&mut state),
Some("t" | "title" | "which")
=> command::session::title(state),
_
=> error::no_subcommand(target.unwrap())
let nesting = args.contains(flag::NEST);
let tmux_var = var("TMUX").ok();
if nesting {
if tmux_var.is_none() {
error::not_nesting();
}
set_var("TMUX", "");
}
if !stdout().is_terminal() { error::not_terminal(); }
let subcommand = args.subcommand().unwrap();
// invoke subcommand function
match subcommand.as_deref() {
Some("h" | "help")
=> help(&mut args),
Some("a" | "attach")
=> command::share::attach(&mut args),
Some("d" | "detach")
=> command::share::detach(&mut args),
Some("has")
=> command::share::has(&mut args),
None |
Some("l" | "ls" | "list")
=> command::share::list(),
Some("n" | "new")
=> command::share::new(&mut args),
_
=> error::no_subcommand(subcommand.unwrap())
}
// re-set TMUX var if we unset it for nest mode
if nesting {
set_var("TMUX", tmux_var.unwrap());
}
}

View file

@ -1,93 +0,0 @@
use std::{
env,
path::PathBuf
};
use pico_args::Arguments;
use crate::{
env::{ env_var, REPO_FILE, TMUX },
error,
flag::Flags,
util::{ find, message, MSG_SESSION_NAME }
};
pub struct State<'a> {
pub args: &'a mut Arguments,
pub flags: Flags,
pub session: bool,
tmux_var: Option<String>,
pub title: Option<String>,
pub repository: Option<Repository>
}
impl State<'_> {
pub fn new(args: &mut Arguments) -> State {
let flags = Flags::from(args);
let tmux_var = env::var(TMUX).ok();
let session = tmux_var.is_some();
let title = if session { message(MSG_SESSION_NAME) } else { None };
let repository = Repository::find();
State {
args,
flags,
session,
tmux_var,
title,
repository
}
}
pub fn nest_init(&self) {
if self.flags.nested {
if self.session { env::set_var(TMUX, ""); } // nesting & session => ok
else { error::not_nesting(); } // nesting & !session => error
} else if self.session { error::prevent_nest(); } // !nesting & session => error
// !nesting & !session => ok
}
pub fn nest_deinit(&self) {
if self.flags.nested && self.session {
env::set_var(TMUX, self.tmux_var.as_ref().unwrap());
}
}
pub fn session_enforce(&self, cmd: &'static str) {
if !self.session { error::not_in_session(cmd); }
}
pub fn target(&mut self) -> Option<String> { self.args.subcommand().unwrap_or(None) }
pub fn target_title(&mut self) -> Option<String> {
let from_args = self.target();
if from_args.is_some() { return from_args; }
else if let Some(repository) = &self.repository { Some(repository.name.clone()) }
else { error::missing_target() }
}
}
pub struct Repository {
pub path: PathBuf,
pub name: String
}
impl Repository {
pub fn find() -> Option<Repository> {
let path = find(&env_var(REPO_FILE), env::current_dir().unwrap());
if let Some(path) = path {
let name = path.file_name().unwrap().to_string_lossy().to_string();
let inner = Repository {
path,
name
};
Some(inner)
} else { None }
}
}

View file

@ -1,10 +1,11 @@
use std::{
io::{ stdout, IsTerminal },
path::PathBuf
env::{ current_dir, var },
path::PathBuf,
process::exit
};
use tmux_interface::{
Session, StdIO, Tmux,
Session, Tmux,
commands,
variables::session::SessionsCtl
@ -12,26 +13,6 @@ use tmux_interface::{
use crate::error;
pub const NULL: Option<StdIO> = Some(StdIO::Null);
pub const MSG_PREVIOUS: &str = "#{client_last_session}";
pub const MSG_SESSION_NAME: &str = "#S";
pub const MSG_SESSION_PATH: &str = "#{session_path}";
pub const MSG_WINDOW_NAME: &str = "#{window_name}";
pub fn message(fstr: &str) -> Option<String> {
let message = commands::DisplayMessage::new().print().message(fstr);
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 {
if title.len() > 0 { Some(title[0..title.len() - 1].to_owned()) }
else { None }
} 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();
@ -40,28 +21,42 @@ pub fn get_sessions() -> Option<Vec<Session>> {
} else { return None; }
}
/// show the tmux nest text if env var is not unset
pub fn prevent_nest() {
let tmux = var("TMUX").ok();
if tmux.is_some() && tmux.unwrap() != "" {
println!("Sessions should be nested with care; unset TMUX or use the '-n' flag to allow.");
exit(1);
}
}
/// 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)
.stderr(NULL)
.status()
.unwrap()
.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
pub fn repo_fallback() -> String {
let repo = repo_root(current_dir().unwrap());
if repo.is_none() { error::missing_target(); }
let target = repo.unwrap().file_name().unwrap().to_string_lossy().to_string();
target
}
/// recursively propagate up directories to find a child
pub fn find(target: &str, path: PathBuf) -> Option<PathBuf> {
if path.join(target).exists() { return Some(path); }
/// recursively attempt to find a git root directory
pub fn repo_root(path: PathBuf) -> Option<PathBuf> {
// if .git dir is found, return
if path.join(".git").exists() { return Some(path); }
// otherwise, attempt to traverse
let parent = path.parent();
if let Some(parent) = parent { return find(target, parent.to_path_buf()) }
if let Some(parent) = parent { repo_root(parent.to_path_buf()) }
else { None }
}