summaryrefslogtreecommitdiff
path: root/src/util.rs
blob: c641ea6bae5adf8c15302f91fa0da8c083e63fe3 (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
//! Utilities.

use log::debug;
use std::net::TcpStream;
use std::path::{Path, PathBuf};

const SSH_PORT: i32 = 22;

// Wait for a virtual machine to have opened its SSH port.
pub fn wait_for_ssh(name: &str) {
    debug!("waiting for {} to respond to SSH", name);
    let addr = format!("{}:{}", name, SSH_PORT);
    loop {
        if TcpStream::connect(&addr).is_ok() {
            return;
        }
    }
}

/// Expand a ~/ at the beginning of a Path to refer to the home directory.
pub fn expand_tilde(path: &Path) -> PathBuf {
    if path.starts_with("~/") {
        if let Some(home) = std::env::var_os("HOME") {
            let mut expanded = PathBuf::from(home);
            for comp in path.components().skip(1) {
                expanded.push(comp);
            }
            expanded
        } else {
            path.to_path_buf()
        }
    } else {
        path.to_path_buf()
    }
}

pub fn expand_optional_pathbuf(maybe_path: &mut Option<PathBuf>) {
    if let Some(path) = maybe_path {
        *maybe_path = Some(expand_tilde(path));
    }
}

pub fn expand_optional_pathbufs(maybe_paths: &mut Option<Vec<PathBuf>>) {
    if let Some(paths) = maybe_paths {
        let mut expanded = vec![];
        for path in paths {
            expanded.push(expand_tilde(&path));
        }
        *maybe_paths = Some(expanded);
    }
}