Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(attach): Support --index option for attach sub-command to choose the session indexed by provided number in the active sessions ordered creation date #824

Merged
merged 1 commit into from
Nov 5, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/ISSUE_TEMPLATE/bug_report.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ name: "\U0001F41B Bug Report"
about: "If something isn't working as expected."
labels: bug
---
Thank you for taking the time to file this issue! Please follow the instructions and fill the missing parts below the instructions, if it is meaningful. Try to be brief and concise.
Thank you for taking the time to file this issue! Please follow the instructions and fill in the missing parts below the instructions, if it is meaningful. Try to be brief and concise.

**In Case of Graphical or Performance Issues**

Expand All @@ -26,4 +26,4 @@ List of programs you interact with as, `PROGRAM --version`: output cropped meani
`alacritty --version`: alacritty 0.7.2 (5ac8060b)

**Further information**
Reproduction steps, noticable behavior, related issues etc
Reproduction steps, noticeable behavior, related issues, etc
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,16 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
* Fix: pasted text performs much faster and doesn't kill Termion (https://github.com/zellij-org/zellij/pull/810)
* Fix: resizing/scrolling through heavily wrapped panes no longer hangs (https://github.com/zellij-org/zellij/pull/814)
* Terminal compatibility: properly handle HOME/END keys in eg. vim/zsh (https://github.com/zellij-org/zellij/pull/815)
* Fix: Typo (https://github.com/zellij-org/zellij/pull/821)
* Fix: Update `cargo-make` instructions post `v0.35.3` (https://github.com/zellij-org/zellij/pull/819)
* Fix: Unused import for darwin systems (https://github.com/zellij-org/zellij/pull/820)
* Add: `WriteChars` action (https://github.com/zellij-org/zellij/pull/825)
* Fix: typo and grammar (https://github.com/zellij-org/zellij/pull/826)
* Add: `rust-version' - msrv field to `Cargo.toml` (https://github.com/zellij-org/zellij/pull/828)
* Fix: improve memory utilization, reap both sides of pty properly and do not expose open FDs to child processes (https://github.com/zellij-org/zellij/pull/830)
* Fix: move from the deprecated `colors_transform` to `colorsys` (https://github.com/zellij-org/zellij/pull/832)
* Feature: plugins can now detect right mouse clicks (https://github.com/zellij-org/zellij/pull/801)
* Fix: open pane in cwd even when explicitly specifying shell (https://github.com/zellij-org/zellij/pull/834)

## [0.19.0] - 2021-10-20
* Fix: Prevent text overwrite when scrolled up (https://github.com/zellij-org/zellij/pull/655)
Expand Down
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ cargo make build
cargo make test
# Run Zellij (optionally with additional arguments)
cargo make run
cargo make run -- -l strider
cargo make run -l strider
# Run Clippy (potentially with additional options)
cargo make clippy
cargo make clippy -W clippy::pedantic
Expand Down
20 changes: 16 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@ repository = "https://github.com/zellij-org/zellij"
homepage = "https://zellij.dev"
include = ["src/**/*", "assets/plugins/*", "assets/layouts/*", "assets/config/*", "LICENSE.md", "README.md", "!**/*_test.*", "!**/tests/**/*"]
resolver = "2"
rust-version = "1.56"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
anyhow = "1.0"
names = "0.11.0"
zellij-client = { path = "zellij-client/", version = "0.20.0" }
zellij-server = { path = "zellij-server/", version = "0.20.0" }
Expand Down
119 changes: 84 additions & 35 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ mod tests;

use crate::install::populate_data_dir;
use sessions::{
assert_session, assert_session_ne, get_active_session, get_sessions, kill_session,
list_sessions, print_sessions, session_exists, ActiveSession,
assert_session, assert_session_ne, get_active_session, get_sessions,
get_sessions_sorted_by_creation_date, kill_session, list_sessions, print_sessions,
print_sessions_with_index, session_exists, ActiveSession,
};
use std::process;
use zellij_client::{os_input_output::get_client_os_input, start_client, ClientInfo};
Expand Down Expand Up @@ -62,7 +63,7 @@ pub fn main() {
}
}
Err(e) => {
eprintln!("Error occured: {:?}", e);
eprintln!("Error occurred: {:?}", e);
process::exit(1);
}
}
Expand Down Expand Up @@ -111,6 +112,7 @@ pub fn main() {
if let Some(Command::Sessions(Sessions::Attach {
session_name,
create,
index,
options,
})) = opts.command.clone()
{
Expand All @@ -119,47 +121,94 @@ pub fn main() {
None => config_options,
};

let (client, attach_layout) = match session_name.as_ref() {
Some(session) => {
if create {
if !session_exists(session).unwrap() {
(ClientInfo::New(session_name.unwrap()), layout)
let (client, attach_layout) = if let Some(idx) = index {
// Ignore session_name when `--index` is provided
match get_sessions_sorted_by_creation_date() {
Ok(sessions) => {
if sessions.is_empty() {
if create {
(
ClientInfo::New(names::Generator::default().next().unwrap()),
layout,
)
} else {
println!("No active zellij sessions found.");
process::exit(1);
}
} else {
(
ClientInfo::Attach(session_name.unwrap(), config_options.clone()),
None,
)
match sessions.get(idx) {
Some(session) => (
ClientInfo::Attach(session.clone(), config_options.clone()),
None,
),
None => {
if create {
(
ClientInfo::New(
names::Generator::default().next().unwrap(),
),
layout,
)
} else {
println!("No session indexed by {} found. The following sessions are active:", idx);
print_sessions_with_index(sessions);
process::exit(1);
}
}
}
}
} else {
assert_session(session);
(
ClientInfo::Attach(session_name.unwrap(), config_options.clone()),
None,
)
}
Err(e) => {
eprintln!("Error occurred: {:?}", e);
process::exit(1);
}
}
None => match get_active_session() {
ActiveSession::None => {
} else {
match session_name.as_ref() {
Some(session) => {
if create {
if !session_exists(session).unwrap() {
(ClientInfo::New(session_name.unwrap()), layout)
} else {
(
ClientInfo::Attach(
session_name.unwrap(),
config_options.clone(),
),
None,
)
}
} else {
assert_session(session);
(
ClientInfo::New(names::Generator::default().next().unwrap()),
layout,
ClientInfo::Attach(session_name.unwrap(), config_options.clone()),
None,
)
} else {
println!("No active zellij sessions found.");
process::exit(1);
}
}
ActiveSession::One(session_name) => (
ClientInfo::Attach(session_name, config_options.clone()),
None,
),
ActiveSession::Many => {
println!("Please specify the session name to attach to. The following sessions are active:");
print_sessions(get_sessions().unwrap());
process::exit(1);
}
},
None => match get_active_session() {
ActiveSession::None => {
if create {
(
ClientInfo::New(names::Generator::default().next().unwrap()),
layout,
)
} else {
println!("No active zellij sessions found.");
process::exit(1);
}
}
ActiveSession::One(session_name) => (
ClientInfo::Attach(session_name, config_options.clone()),
None,
),
ActiveSession::Many => {
println!("Please specify the session name to attach to. The following sessions are active:");
print_sessions(get_sessions().unwrap());
process::exit(1);
}
},
}
};

start_client(
Expand Down
53 changes: 48 additions & 5 deletions src/sessions.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::os::unix::fs::FileTypeExt;
use std::time::SystemTime;
use std::{fs, io, process};
use zellij_utils::{
consts::ZELLIJ_SOCK_DIR,
Expand Down Expand Up @@ -29,6 +30,36 @@ pub(crate) fn get_sessions() -> Result<Vec<String>, io::ErrorKind> {
}
}

pub(crate) fn get_sessions_sorted_by_creation_date() -> anyhow::Result<Vec<String>> {
match fs::read_dir(&*ZELLIJ_SOCK_DIR) {
Ok(files) => {
let mut sessions_with_creation_date: Vec<(String, SystemTime)> = Vec::new();
for file in files {
let file = file?;
let file_name = file.file_name().into_string().unwrap();
let file_created_at = file.metadata()?.created()?;
if file.file_type()?.is_socket() && assert_socket(&file_name) {
sessions_with_creation_date.push((file_name, file_created_at));
}
}
sessions_with_creation_date.sort_by_key(|x| x.1); // the oldest one will be the first

let sessions = sessions_with_creation_date
.iter()
.map(|x| x.0.clone())
.collect();
Ok(sessions)
}
Err(err) => {
if let io::ErrorKind::NotFound = err.kind() {
Ok(Vec::with_capacity(0))
} else {
Err(err.into())
}
}
}
}

fn assert_socket(name: &str) -> bool {
let path = &*ZELLIJ_SOCK_DIR.join(name);
match LocalSocketStream::connect(path) {
Expand Down Expand Up @@ -59,6 +90,18 @@ pub(crate) fn print_sessions(sessions: Vec<String>) {
})
}

pub(crate) fn print_sessions_with_index(sessions: Vec<String>) {
let curr_session = std::env::var("ZELLIJ_SESSION_NAME").unwrap_or_else(|_| "".into());
for (i, session) in sessions.iter().enumerate() {
let suffix = if curr_session == *session {
" (current)"
} else {
""
};
println!("{}: {}{}", i, session, suffix);
}
}

pub(crate) enum ActiveSession {
None,
One(String),
Expand All @@ -78,7 +121,7 @@ pub(crate) fn get_active_session() -> ActiveSession {
}
}
Err(e) => {
eprintln!("Error occured: {:?}", e);
eprintln!("Error occurred: {:?}", e);
process::exit(1);
}
}
Expand All @@ -91,7 +134,7 @@ pub(crate) fn kill_session(name: &str) {
IpcSenderWithContext::new(stream).send(ClientToServerMsg::KillSession);
}
Err(e) => {
eprintln!("Error occured: {:?}", e);
eprintln!("Error occurred: {:?}", e);
process::exit(1);
}
};
Expand All @@ -108,7 +151,7 @@ pub(crate) fn list_sessions() {
0
}
Err(e) => {
eprintln!("Error occured: {:?}", e);
eprintln!("Error occurred: {:?}", e);
1
}
};
Expand Down Expand Up @@ -137,7 +180,7 @@ pub(crate) fn assert_session(name: &str) {
}
}
Err(e) => {
eprintln!("Error occured: {:?}", e);
eprintln!("Error occurred: {:?}", e);
}
};
process::exit(1);
Expand All @@ -151,7 +194,7 @@ pub(crate) fn assert_session_ne(name: &str) {
}
println!("Session with name {:?} aleady exists. Use attach command to connect to it or specify a different name.", name);
}
Err(e) => eprintln!("Error occured: {:?}", e),
Err(e) => eprintln!("Error occurred: {:?}", e),
};
process::exit(1);
}
3 changes: 3 additions & 0 deletions zellij-client/src/input_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,9 @@ impl InputHandler {
MouseButton::Left => {
self.dispatch_action(Action::LeftClick(point));
}
MouseButton::Right => {
self.dispatch_action(Action::RightClick(point));
}
_ => {}
},
MouseEvent::Release(point) => {
Expand Down
1 change: 1 addition & 0 deletions zellij-server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ zellij-utils = { path = "../zellij-utils/", version = "0.20.0" }
log = "0.4.14"
typetag = "0.1.7"
chrono = "0.4.19"
close_fds = "0.3.2"

[target.'cfg(target_os = "macos")'.dependencies]
darwin-libproc = "0.2.0"
Expand Down
Loading