1use serde::de::DeserializeOwned;
2use serde::Serialize;
3use serde_json;
4use std::ffi::OsStr;
5use std::fs::{self, File};
6use std::io::Read;
7use std::path::Path;
8use walkdir::{DirEntry, WalkDir};
9
10use error::{Error, Result};
11use report::BenchmarkId;
12
13pub fn load<A, P: ?Sized>(path: &P) -> Result<A>
14where
15 A: DeserializeOwned,
16 P: AsRef<Path>,
17{
18 let path = path.as_ref();
19 let mut f = File::open(path).map_err(|inner| Error::AccessError {
20 inner,
21 path: path.to_owned(),
22 })?;
23 let mut string = String::new();
24 let _ = f.read_to_string(&mut string);
25 let result: A = serde_json::from_str(string.as_str()).map_err(|inner| Error::SerdeError {
26 inner,
27 path: path.to_owned(),
28 })?;
29
30 Ok(result)
31}
32
33pub fn is_dir<P>(path: &P) -> bool
34where
35 P: AsRef<Path>,
36{
37 let path: &Path = path.as_ref();
38 path.is_dir()
39}
40
41pub fn mkdirp<P>(path: &P) -> Result<()>
42where
43 P: AsRef<Path>,
44{
45 fs::create_dir_all(path.as_ref()).map_err(|inner| Error::AccessError {
46 inner,
47 path: path.as_ref().to_owned(),
48 })?;
49 Ok(())
50}
51
52pub fn cp(from: &Path, to: &Path) -> Result<()> {
53 fs::copy(from, to).map_err(|inner| Error::CopyError {
54 inner,
55 from: from.to_owned(),
56 to: to.to_owned(),
57 })?;
58 Ok(())
59}
60
61pub fn save<D, P>(data: &D, path: &P) -> Result<()>
62where
63 D: Serialize,
64 P: AsRef<Path>,
65{
66 let buf = serde_json::to_string(&data).map_err(|inner| Error::SerdeError {
67 path: path.as_ref().to_owned(),
68 inner,
69 })?;
70 save_string(&buf, path)
71}
72
73pub fn save_string<P>(data: &str, path: &P) -> Result<()>
74where
75 P: AsRef<Path>,
76{
77 use std::io::Write;
78
79 File::create(path)
80 .and_then(|mut f| f.write_all(data.as_bytes()))
81 .map_err(|inner| Error::AccessError {
82 inner,
83 path: path.as_ref().to_owned(),
84 })?;
85
86 Ok(())
87}
88
89pub fn list_existing_benchmarks<P>(directory: &P) -> Result<Vec<BenchmarkId>>
90where
91 P: AsRef<Path>,
92{
93 fn is_benchmark(entry: &DirEntry) -> bool {
94 entry.file_name() == OsStr::new("benchmark.json")
97 && entry.path().parent().unwrap().file_name().unwrap() == OsStr::new("new")
98 }
99
100 let mut ids = vec![];
101
102 for entry in WalkDir::new(directory)
103 .into_iter()
104 .filter_map(|e| e.ok())
106 .filter(is_benchmark)
107 {
108 let id: BenchmarkId = load(entry.path())?;
109 ids.push(id);
110 }
111
112 Ok(ids)
113}