nethsm_cli/
passphrase_file.rs1use std::{
2 fs::read_to_string,
3 path::{Path, PathBuf},
4 str::FromStr,
5};
6
7use nethsm::Passphrase;
8
9#[derive(Debug, thiserror::Error)]
11pub enum Error {
12 #[error("I/O error: {0}")]
14 Io(#[from] std::io::Error),
15 #[error("Path error: {0}")]
17 Path(#[from] core::convert::Infallible),
18}
19
20#[derive(Clone, Debug)]
22pub struct PassphraseFile {
23 pub passphrase: Passphrase,
24}
25
26impl PassphraseFile {
27 pub fn new(path: &Path) -> Result<Self, Error> {
28 Ok(Self {
29 passphrase: Passphrase::new(read_to_string(path)?),
30 })
31 }
32}
33
34impl FromStr for PassphraseFile {
35 type Err = Error;
36
37 fn from_str(s: &str) -> Result<Self, Self::Err> {
38 PassphraseFile::new(&PathBuf::from_str(s)?)
39 }
40}
41
42#[cfg(test)]
43mod tests {
44 use std::fs::File;
45 use std::io::Write;
46
47 use rand::{Rng, thread_rng};
48 use rstest::rstest;
49 use testdir::testdir;
50 use testresult::TestResult;
51
52 use super::*;
53
54 #[rstest]
55 fn passphrase_file() -> TestResult {
56 let mut i = 0;
57 while i < 20 {
58 let mut rng = thread_rng();
59 let lines = rng.gen_range(0..20);
60 let lines_vec = (0..lines)
61 .map(|_x| "this is a passphrase".to_string())
62 .collect::<Vec<String>>();
63 let path = testdir!().join(format!("passphrase_file_lines_{}.txt", lines));
64 let mut file = File::create(&path)?;
65 file.write_all(lines_vec.join("\n").as_bytes())?;
66
67 let passphrase_file = PassphraseFile::new(&path);
68 assert!(passphrase_file.is_ok());
69 i += 1;
70 }
71
72 Ok(())
73 }
74}