1use std::fs::{self, File};
2use std::io::{BufReader, BufWriter, Read, Write};
3use std::path::Path;
4
5use anyhow::Result;
6use std::io;
7
8#[allow(dead_code)]
9pub fn mk_dir(path: impl AsRef<Path>) -> Result<()> {
10 fs::create_dir_all(path)?;
11 Ok(())
12}
13
14#[allow(dead_code)]
15pub fn read_file(path: impl AsRef<Path>) -> Result<Vec<u8>> {
16 let file = File::open(&path)?;
17 let mut reader = BufReader::new(file);
18 let mut buf = Vec::new();
19 reader.read_to_end(&mut buf)?;
20 Ok(buf)
21}
22
23#[allow(dead_code)]
24pub fn write_file(path: impl AsRef<Path>, contents: &[u8]) -> Result<()> {
25 let file = File::create(path)?;
26 let mut buf = BufWriter::new(file);
27 buf.write_all(contents)?;
28 Ok(())
29}
30
31pub fn read_from_stdin() -> Result<String> {
32 let mut buf = String::new();
33 let stdin = io::stdin();
34 let mut handle = stdin.lock();
35 handle.read_to_string(&mut buf)?;
36 Ok(buf)
37}
38
39#[cfg(test)]
40mod tests {
41
42 use crate::fs::*;
43 use std::str;
44 use tempfile::tempdir;
45
46 #[test]
47 fn mk_dir_one_layer_ok() -> Result<()> {
48 let tmp_dir = tempdir()?;
49 let path = tmp_dir.path().join("test");
50 let actual = mk_dir(&path);
51 assert!(actual.is_ok());
52 assert!(path.exists());
53 Ok(())
54 }
55
56 #[test]
57 fn mk_dir_deep_layer_ok() -> Result<()> {
58 let tmp_dir = tempdir()?;
59 let path = tmp_dir.path().join("test/test/test/test");
60 let actual = mk_dir(&path);
61 assert!(actual.is_ok());
62 assert!(path.exists());
63 Ok(())
64 }
65
66 #[test]
67 fn read_file_temp_ok() -> Result<()> {
68 let expect = "hello";
69 let file = "read_test.txt";
70
71 let tmp_dir = tempdir()?;
72 let tmp_file = tmp_dir.path().join(file);
73 write_file(&tmp_file, expect.as_bytes()).unwrap();
74
75 let actual = read_file(&tmp_file);
76 assert!(actual.is_ok());
77 assert_eq!(expect, str::from_utf8(&actual.unwrap()).unwrap());
78 Ok(())
79 }
80
81 #[test]
82 fn read_file_not_file_ng() -> Result<()> {
83 let file = "not_found.txt";
84 let tmp_dir = tempdir()?;
85 let tmp_file = tmp_dir.path().join(file);
86 let actual = read_file(&tmp_file);
87 assert!(actual.is_err());
88 Ok(())
89 }
90
91 #[test]
92 fn write_file_ok() -> Result<()> {
93 let file = "write_test.txt";
94 let tmp_dir = tempdir()?;
95 let tmp_file = tmp_dir.path().join(file);
96 let actual = write_file(&tmp_file, b"write");
97 assert!(actual.is_ok());
98 Ok(())
99 }
100}