korasi_cli/
util.rs

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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
//! IO Utilities wrapper to allow automock for requests and user input prompts.

use std::{
    fmt::{self, Display},
    io::Write,
    iter::Map,
    path::{Path, PathBuf},
};

use aws_sdk_ec2::types::{Image, Instance, InstanceStateName};
use ignore::Walk;
use inquire::{InquireError, MultiSelect, Select};

use crate::ec2::{EC2Error, EC2Impl as EC2};

#[derive(Default)]
pub struct UtilImpl;

impl UtilImpl {
    /// Utility to perform a GET request and return the body as UTF-8, or an appropriate EC2Error.
    pub async fn do_get(url: &str) -> Result<String, EC2Error> {
        reqwest::get(url)
            .await
            .map_err(|e| EC2Error::new(format!("Could not request ip from {url}: {e:?}")))?
            .error_for_status()
            .map_err(|e| EC2Error::new(format!("Failure status from {url}: {e:?}")))?
            .text_with_charset("utf-8")
            .await
            .map_err(|e| EC2Error::new(format!("Failed to read response from {url}: {e:?}")))
    }

    pub fn write_secure(path: &PathBuf, material: String, mode: u32) -> Result<(), EC2Error> {
        let mut file = open_file_with_perm(path, mode)?;
        file.write(material.as_bytes())
            .map_err(|e| EC2Error::new(format!("Failed to write to {path:?} ({e:?})")))?;
        Ok(())
    }
}

#[cfg(unix)]
fn open_file_with_perm(path: &PathBuf, mode: u32) -> Result<std::fs::File, EC2Error> {
    use std::os::unix::fs::OpenOptionsExt;
    std::fs::OpenOptions::new()
        .mode(mode)
        .write(true)
        .create(true)
        .open(path)
        .map_err(|e| EC2Error::new(format!("Failed to create {path:?} ({e:?})")))
}

#[cfg(not(unix))]
fn open_file(path: &PathBuf) -> Result<File, EC2Error> {
    fs::File::create(path.clone())
        .map_err(|e| EC2Error::new(format!("Failed to create {path:?} ({e:?})")))?
}

/// Image doesn't impl Display, which is necessary for inquire to use it in a Select.
/// This wraps Image and provides a Display impl.
#[derive(PartialEq, Debug)]
pub struct ScenarioImage(pub Image);
impl From<Image> for ScenarioImage {
    fn from(value: Image) -> Self {
        ScenarioImage(value)
    }
}

impl Display for ScenarioImage {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}: {}",
            self.0.name().unwrap_or("(unknown)"),
            self.0.description().unwrap_or("unknown")
        )
    }
}

#[derive(Debug, Default, Clone)]
pub struct SelectOption {
    pub name: String,
    pub instance_id: String,
    pub public_dns_name: Option<String>,
    state: Option<InstanceStateName>,
}

impl fmt::Display for SelectOption {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let status = self.state.as_ref().unwrap().clone();
        write!(
            f,
            "name = {}, instance_id = {}, status = {}",
            self.name, self.instance_id, status
        )
    }
}

impl From<Instance> for SelectOption {
    fn from(value: Instance) -> Self {
        let mut opt = SelectOption {
            state: value.state().unwrap().name().cloned(),
            instance_id: value.instance_id().unwrap().to_string(),
            public_dns_name: value.public_dns_name().map(str::to_string),
            ..SelectOption::default()
        };

        for t in value.tags() {
            if t.key() == Some("Name") {
                opt.name = t.value().unwrap().to_owned();
            }
        }

        opt
    }
}

/// Express list of instance ids as a comma separated string.
pub fn ids_to_str(ids: Vec<SelectOption>) -> String {
    ids.iter()
        .map(|i| i.instance_id.to_owned())
        .collect::<Vec<_>>()
        .join(",")
}

pub async fn multi_select_instances(
    ec2: &EC2,
    prompt: &str,
    statuses: Vec<InstanceStateName>,
) -> Result<Vec<SelectOption>, InquireError> {
    // Get all instances tagged by this tool.
    let instances = ec2.describe_instance(statuses).await.unwrap();
    let options: Vec<SelectOption> = instances.into_iter().map(|i| i.into()).collect();

    if options.len() == 1 {
        return Ok(vec![options[0].to_owned()]);
    }
    MultiSelect::new(prompt, options)
        .with_vim_mode(true)
        .prompt()
}

pub async fn select_instance(
    ec2: &EC2,
    prompt: &str,
    statuses: Vec<InstanceStateName>,
) -> Result<SelectOption, InquireError> {
    let instances = ec2.describe_instance(statuses).await.unwrap();
    let options: Vec<SelectOption> = instances.into_iter().map(|i| i.into()).collect();

    if options.len() == 1 {
        return Ok(options[0].to_owned());
    }
    Select::new(prompt, options).with_vim_mode(true).prompt()
}

pub fn calc_prefix(pth: PathBuf) -> std::io::Result<PathBuf> {
    Ok(pth.parent().unwrap_or(Path::new("")).to_path_buf())
}

pub fn biject_paths<'a>(
    src_path: &str,
    prefix: &'a str,
    dst_folder: &'a str,
) -> Map<
    Walk,
    impl FnMut(
            Result<ignore::DirEntry, ignore::Error>,
        ) -> Result<(PathBuf, PathBuf, bool), ignore::Error>
        + 'a,
> {
    Walk::new(src_path).map(move |result| match result {
        Ok(entry) => {
            let is_dir = match entry.metadata() {
                Ok(ent) => ent.is_dir(),
                _ => false,
            };
            let local_pth = entry.path().to_path_buf();
            let mut rel_pth = entry
                .path()
                .to_str()
                .unwrap()
                .strip_prefix(prefix)
                .unwrap()
                .chars();
            rel_pth.next();
            let transformed = PathBuf::from(dst_folder).join(rel_pth.as_str());

            tracing::info!("uploaded path = {:?}", transformed);

            Ok((local_pth, transformed, is_dir))
        }
        Err(err) => Err(err),
    })
}

#[cfg(test)]
mod tests {
    use std::{
        fs::remove_file,
        path::{Path, PathBuf},
    };

    use crate::util::biject_paths;

    use super::{calc_prefix, open_file_with_perm};

    #[test]
    fn open_readonly_file() {
        let pk_file = "pk.pem";

        assert!(
            !Path::new(pk_file).exists(),
            "Test pk file should not exist before test."
        );
        let _ = open_file_with_perm(&pk_file.into(), 0o400);
        let meta = std::fs::metadata(pk_file).unwrap();
        assert!(
            meta.permissions().readonly(),
            "ssh PK file should be readonly."
        );
        let _ = remove_file(pk_file);
    }

    #[test]
    fn calc_src_prefix() {
        let _ = std::fs::remove_dir("../outside-cwd");

        let cwd = std::env::current_dir().unwrap();
        std::fs::create_dir("../outside-cwd").unwrap();

        let cases = [
            ("/", PathBuf::from("")),
            ("README.md", cwd.clone()),
            ("src/main.rs", cwd.join("src")),
            ("../outside-cwd", cwd.parent().unwrap().to_path_buf()),
        ];

        for (input, expected) in cases {
            println!("input = {input}");
            let canon_pth = std::fs::canonicalize(input).unwrap();
            let got = calc_prefix(canon_pth);
            assert!(
                got.is_ok(),
                "Failed to canonicalize path = {}, Err = {}",
                input,
                got.unwrap_err()
            );
            pretty_assertions::assert_eq!(got.unwrap(), expected);
        }

        std::fs::remove_dir("../outside-cwd").unwrap();
    }

    #[test]
    fn calc_remote_paths() {
        let cwd = std::env::current_dir().unwrap();

        let cases = [
            (
                // Paths are unchanged
                cwd.as_path().to_str().unwrap(),
                "",
                "/home/foobar",
            ),
            (
                // Paths prefixes are replaced
                cwd.as_path().to_str().unwrap(),
                cwd.parent().unwrap().to_str().unwrap(),
                "/home/foobar",
            ),
        ];

        for (x, y, z) in cases {
            for result in biject_paths(x, y, z) {
                match result {
                    Ok(entry) => {
                        println!("entry = {:?}", entry);
                    }
                    Err(err) => {
                        println!("err = {}", err);
                    }
                }
            }
            println!();
        }
    }
}