agent-ssh 0.3.0

Arrange agent terminal layouts and reconnect through provider attachment plans
Documentation
use crate::config::Host;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Direction {
    Vertical,
    Horizontal,
}

impl Direction {
    pub fn wt_flag(self) -> &'static str {
        match self {
            Self::Vertical => "-V",
            Self::Horizontal => "-H",
        }
    }
    pub fn json_name(self) -> &'static str {
        match self {
            Self::Vertical => "vertical",
            Self::Horizontal => "horizontal",
        }
    }
}

#[derive(Clone, Debug)]
pub enum Step<'a, T = Host> {
    New(&'a T),
    Split {
        direction: Direction,
        size: f64,
        target: &'a T,
    },
    FocusLeft,
}

pub fn grid_steps<T>(targets: &[T]) -> Vec<Step<'_, T>> {
    if targets.is_empty() {
        return Vec::new();
    }
    let columns_count = (targets.len() as f64).sqrt().ceil() as usize;
    let base = targets.len() / columns_count;
    let extra = targets.len() % columns_count;
    let mut columns = Vec::new();
    let mut start = 0;
    for column in 0..columns_count {
        let count = base + usize::from(column < extra);
        columns.push(&targets[start..start + count]);
        start += count;
    }

    let mut steps = vec![Step::New(&columns[0][0])];
    for (column, members) in columns.iter().enumerate().skip(1) {
        steps.push(Step::Split {
            direction: Direction::Vertical,
            size: (columns_count - column) as f64 / (columns_count - column + 1) as f64,
            target: &members[0],
        });
    }
    for column in (0..columns_count).rev() {
        for row in 1..columns[column].len() {
            steps.push(Step::Split {
                direction: Direction::Horizontal,
                size: (columns[column].len() - row) as f64
                    / (columns[column].len() - row + 1) as f64,
                target: &columns[column][row],
            });
        }
        if column > 0 {
            steps.push(Step::FocusLeft);
        }
    }
    steps
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn seven_hosts_form_three_columns() {
        let hosts: Vec<_> = (1..=7)
            .map(|n| Host {
                name: n.to_string(),
                group: "g".into(),
                color: None,
            })
            .collect();
        let steps = grid_steps(&hosts);
        assert_eq!(steps.len(), 9);
        assert!(matches!(steps[0], Step::New(_)));
        assert!(matches!(
            steps[1],
            Step::Split {
                direction: Direction::Vertical,
                ..
            }
        ));
    }
}