aboutsummaryrefslogtreecommitdiff
path: root/src/storage.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/storage.rs')
-rw-r--r--src/storage.rs25
1 files changed, 22 insertions, 3 deletions
diff --git a/src/storage.rs b/src/storage.rs
index 90ff1b4..e069875 100644
--- a/src/storage.rs
+++ b/src/storage.rs
@@ -1,5 +1,6 @@
1use std::{ 1use std::{
2 fs::{create_dir_all, File}, 2 ffi::OsStr,
3 fs::{create_dir_all, File, read_dir},
3 io::{Read, Write}, 4 io::{Read, Write},
4 path::Path, 5 path::Path,
5}; 6};
@@ -26,14 +27,14 @@ impl Device {
26 const STORAGE_PATH: &'static str = "devices"; 27 const STORAGE_PATH: &'static str = "devices";
27 28
28 pub fn setup() -> Result<String, Error> { 29 pub fn setup() -> Result<String, Error> {
29 trace!("check for storage at {}", Self::STORAGE_PATH); 30 trace!("check for storage STORAGE_PATH=\"{}\"", Self::STORAGE_PATH);
30 let sp = Path::new(Self::STORAGE_PATH); 31 let sp = Path::new(Self::STORAGE_PATH);
31 if !sp.exists() { 32 if !sp.exists() {
32 warn!("device storage path doesn't exist, creating it"); 33 warn!("device storage path doesn't exist, creating it");
33 create_dir_all(Self::STORAGE_PATH)?; 34 create_dir_all(Self::STORAGE_PATH)?;
34 }; 35 };
35 36
36 debug!("device storage at '{}'", Self::STORAGE_PATH); 37 debug!("device storage STORAGE_PATH=\"{}\"", Self::STORAGE_PATH);
37 38
38 Ok(Self::STORAGE_PATH.to_string()) 39 Ok(Self::STORAGE_PATH.to_string())
39 } 40 }
@@ -49,6 +50,24 @@ impl Device {
49 Ok(dev) 50 Ok(dev)
50 } 51 }
51 52
53 pub fn read_all() -> Result<Vec<Self>, Error> {
54 trace!("attempt to read all files");
55 let st_path = read_dir(Self::STORAGE_PATH)?;
56
57 let mut devices = vec![];
58 for file_path in st_path {
59 let file_path = file_path?;
60 if file_path.path().extension() != Some(OsStr::new("json")) { continue; };
61 let mut file = File::open(file_path.path())?;
62 let mut buf = String::new();
63 file.read_to_string(&mut buf)?;
64 trace!(?file, ?buf, "read successfully from file");
65 devices.push(serde_json::from_str(&buf)?);
66 }
67
68 Ok(devices)
69 }
70
52 pub fn write(&self) -> Result<(), Error> { 71 pub fn write(&self) -> Result<(), Error> {
53 trace!(?self.id, ?self, "attempt to write to file"); 72 trace!(?self.id, ?self, "attempt to write to file");
54 let mut file = File::create(format!("{}/{}.json", Self::STORAGE_PATH, self.id))?; 73 let mut file = File::create(format!("{}/{}.json", Self::STORAGE_PATH, self.id))?;