cbor_cli/
files.rs

1use std::path::Path;
2
3/// Get a displayable string of a path.
4pub fn get_path_str(path: &Path) -> &str {
5  path.to_str().unwrap()
6}
7
8/// Get a list of file paths that are not existing files.
9/// Will not check for the existence of directories.
10pub fn get_missing_files(input_paths: &Vec<std::path::PathBuf>) -> Vec<std::path::PathBuf> {
11  let mut missing_files = Vec::new();
12
13  for input_path in input_paths {
14    if !input_path.is_file() {
15      missing_files.push(input_path.clone());
16    }
17  }
18
19  missing_files
20}
21
22pub fn get_format_by_file_extension(input_path: &Path) -> Option<String> {
23  match input_path.extension() {
24    Some(extension) => match extension.to_str() {
25      Some(extension) => match extension {
26        "json" => Some("json".to_string()),
27        "yaml" => Some("yaml".to_string()),
28        "toml" => Some("toml".to_string()),
29        _ => None,
30      },
31      None => None,
32    },
33    None => None,
34  }
35}
36
37#[cfg(test)]
38mod tests {
39  use super::*;
40  use common_testing::assert;
41
42  #[test]
43  fn test_get_path_str() {
44    let path = Path::new("foo");
45    assert::equal(get_path_str(path), "foo");
46  }
47
48  #[test]
49  fn test_get_missing_files() {
50    let input_paths = vec![
51      Path::new("foo").to_path_buf(),
52      Path::new("bar").to_path_buf(),
53      Path::new("baz").to_path_buf(),
54    ];
55    let missing_files = vec![
56      Path::new("foo").to_path_buf(),
57      Path::new("bar").to_path_buf(),
58      Path::new("baz").to_path_buf(),
59    ];
60
61    assert::equal(get_missing_files(&input_paths), missing_files);
62  }
63
64  #[test]
65  fn test_get_format_by_file_extension() {
66    let path = Path::new("foo.json");
67    assert::equal(get_format_by_file_extension(path), Some("json".to_string()));
68
69    let path = Path::new("foo.yaml");
70    assert::equal(get_format_by_file_extension(path), Some("yaml".to_string()));
71
72    let path = Path::new("foo.toml");
73    assert::equal(get_format_by_file_extension(path), Some("toml".to_string()));
74
75    let path = Path::new("foo.bar");
76    assert::equal(get_format_by_file_extension(path), None);
77  }
78}