better errors + generate default config

This commit is contained in:
Alex Janka 2023-12-26 08:58:14 +11:00
parent ed2fee6571
commit b4a03f5e54
3 changed files with 69 additions and 26 deletions

View file

@ -1,7 +1,16 @@
use std::time::Duration;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone, Debug)] #[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Config {} pub struct Config {
watch_interval: Duration,
}
#[derive(Serialize, Deserialize, Clone, Debug)] impl Default for Config {
pub struct Auth {} fn default() -> Self {
Self {
watch_interval: Duration::from_secs(60),
}
}
}

38
src/errors.rs Normal file
View file

@ -0,0 +1,38 @@
use thiserror::Error;
#[derive(Error, Debug)]
pub enum AuthLoadError {
#[error("stdio error")]
StdIo(#[from] std::io::Error),
#[error("ron - spanned error")]
RonSpanned(#[from] ron::error::SpannedError),
}
impl AuthLoadError {
pub fn error_string(&self) -> String {
match self {
AuthLoadError::StdIo(e) => format!("Error reading access token from disk: {e:?}"),
AuthLoadError::RonSpanned(e) => format!("Error deserialising access token: {e:?}"),
}
}
}
#[derive(Error, Debug)]
pub enum LoginError {
#[error("teslatte error")]
Teslatte(#[from] teslatte::error::TeslatteError),
#[error("ron error")]
Ron(#[from] ron::Error),
#[error("stdio error")]
StdIo(#[from] std::io::Error),
}
impl LoginError {
pub fn error_string(&self) -> String {
match self {
LoginError::Teslatte(e) => format!("Authentication flow error: {e:?}"),
LoginError::Ron(e) => format!("Error serialising access token: {e:?}"),
LoginError::StdIo(e) => format!("Error saving access token to disk: {e:?}"),
}
}
}

View file

@ -1,10 +1,11 @@
use std::{io::BufRead, path::PathBuf};
use clap::{Parser, Subcommand}; use clap::{Parser, Subcommand};
use std::{io::BufRead, path::PathBuf};
use teslatte::{auth::AccessToken, OwnerApi}; use teslatte::{auth::AccessToken, OwnerApi};
use thiserror::Error;
use crate::{config::Config, errors::*};
mod config; mod config;
mod errors;
#[derive(Parser, Debug, Clone)] #[derive(Parser, Debug, Clone)]
#[clap(author, version, about, long_about = None)] #[clap(author, version, about, long_about = None)]
@ -20,7 +21,9 @@ enum Commands {
/// Run charge controller server /// Run charge controller server
Watch, Watch,
/// Authenticate with Tesla login /// Authenticate with Tesla login
Auth {}, Auth,
/// Print the default config file
GenerateConfig,
} }
fn press_y_to_continue() -> bool { fn press_y_to_continue() -> bool {
@ -41,8 +44,15 @@ async fn main() {
let args = Args::parse(); let args = Args::parse();
let auth_path = args.config_dir.join("auth"); let auth_path = args.config_dir.join("auth");
let config_path = args.config_dir.join("config"); let config_path = args.config_dir.join("config");
match args.command { match args.command {
Commands::Auth {} => { Commands::GenerateConfig => {
println!(
"{}",
ron::ser::to_string_pretty(&Config::default(), Default::default()).unwrap()
);
}
Commands::Auth => {
if auth_path.exists() { if auth_path.exists() {
println!("Auth file already exists"); println!("Auth file already exists");
if !press_y_to_continue() { if !press_y_to_continue() {
@ -50,38 +60,24 @@ async fn main() {
} }
} }
if let Err(e) = log_in(auth_path).await { if let Err(e) = log_in(auth_path).await {
println!("Error: {e:#?}") println!("{}", e.error_string());
} }
} }
Commands::Watch => match get_auth(auth_path) { Commands::Watch => match get_auth(auth_path) {
Ok(api) => { Ok(api) => {
println!("got products: {:#?}", api.products().await) println!("got products: {:#?}", api.products().await)
} }
Err(e) => println!("error getting auth: {e:#?}"), Err(e) => println!("{}", e.error_string()),
}, },
} }
} }
#[derive(Error, Debug)] fn get_auth(auth_path: PathBuf) -> Result<OwnerApi, AuthLoadError> {
pub enum TeslaError {
#[error("teslatte error")]
Teslatte(#[from] teslatte::error::TeslatteError),
#[error("ron error")]
Ron(#[from] ron::Error),
#[error("stdio error")]
StdIo(#[from] std::io::Error),
#[error("ron - spanned error")]
RonSpanned(#[from] ron::error::SpannedError),
#[error("unknown error")]
Unknown,
}
fn get_auth(auth_path: PathBuf) -> Result<OwnerApi, TeslaError> {
let key: AccessToken = ron::from_str(&std::fs::read_to_string(auth_path)?)?; let key: AccessToken = ron::from_str(&std::fs::read_to_string(auth_path)?)?;
Ok(OwnerApi::new(key, None)) Ok(OwnerApi::new(key, None))
} }
async fn log_in(auth_path: PathBuf) -> Result<(), TeslaError> { async fn log_in(auth_path: PathBuf) -> Result<(), LoginError> {
let v = OwnerApi::from_interactive_url().await?; let v = OwnerApi::from_interactive_url().await?;
std::fs::write(auth_path, ron::ser::to_string(&v.access_token)?)?; std::fs::write(auth_path, ron::ser::to_string(&v.access_token)?)?;