summaryrefslogtreecommitdiffstats
path: root/src/main.rs
blob: b546377cfb37523c9d5bc0c8617b749fa91475df (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
use std::collections::HashMap;

use clap::Parser;

use sshr::{Commands, Config, History, KnownHosts, Session, SessionSource, Tmux};

fn main() -> anyhow::Result<()> {
    let mut config = Config::parse();

    tracing_subscriber::fmt::fmt()
        .with_max_level(&config.verbosity)
        .without_time()
        .init();

    config.history_file = config.history_file.or_else(History::default_path);

    match config.command.to_owned() {
        Commands::List => list_sessions(config),
        Commands::Switch { name } => switch(config, name),
    }
}

fn list_sessions(config: Config) -> anyhow::Result<()> {
    let mut sessions = HashMap::new();

    sessions = KnownHosts::default().update(sessions)?;
    sessions = Tmux::new(config.socket_name).update(sessions)?;

    if let Some(history) = config.history_file.map(History::new) {
        if history.exists() {
            sessions = history.update(sessions)?;
        }
    }

    let mut sessions: Vec<Session> = sessions.into_values().collect();

    sessions.sort();

    for session in sessions {
        println!("{session}");
    }

    Ok(())
}

fn switch(config: Config, name: String) -> anyhow::Result<()> {
    let tmux = Tmux::new(config.socket_name);

    if let Some(history) = config.history_file.map(History::new) {
        if tmux.switch(&name)?.success() {
            let session = tmux.show(&name)?;
            history.update_session(session)?;
        }
    }

    Ok(())
}