60 lines
1.3 KiB
Rust
60 lines
1.3 KiB
Rust
use crate::errors::{Error, ErrorStatus};
|
|
use serde::{Deserialize, Serialize};
|
|
use std::path::Path;
|
|
|
|
#[derive(Serialize, Deserialize, Debug, Clone)]
|
|
pub struct Site {
|
|
pub url: String,
|
|
pub name: Option<String>,
|
|
}
|
|
|
|
pub fn load_names(names: String) -> Result<Vec<Site>, Error> {
|
|
match serde_json::from_str::<Vec<Site>>(&names) {
|
|
Ok(content) => {
|
|
log::debug!("successfully parsed names.json.");
|
|
Ok(content)
|
|
}
|
|
Err(err) => Err(Error {
|
|
status: ErrorStatus::ParsingError,
|
|
data: err.to_string(),
|
|
}),
|
|
}
|
|
}
|
|
|
|
pub fn read_names_file(path: &Path) -> Result<String, Error> {
|
|
if !path.exists() {
|
|
log::debug!(
|
|
"the names.json file does not exist at {}. creating names.json",
|
|
path.display()
|
|
);
|
|
create_names_file(path)?
|
|
}
|
|
|
|
match std::fs::read_to_string(path) {
|
|
Ok(data) => {
|
|
log::debug!(
|
|
"successfully read the names.json file at {}",
|
|
path.display()
|
|
);
|
|
Ok(data)
|
|
}
|
|
Err(err) => Err(Error {
|
|
status: ErrorStatus::IOError,
|
|
data: err.to_string(),
|
|
}),
|
|
}
|
|
}
|
|
|
|
fn create_names_file(path: &Path) -> Result<(), Error> {
|
|
match std::fs::write(path, "[]") {
|
|
Ok(_) => {
|
|
log::debug!("created a names.json file at {}", path.display());
|
|
Ok(())
|
|
}
|
|
Err(err) => Err(Error {
|
|
status: ErrorStatus::IOError,
|
|
data: err.to_string(),
|
|
}),
|
|
}
|
|
}
|