index : license-api-rs.git

ascending towards madness

author holly sparkles <sparkles@holly.sh> 2024-02-06 11:19:30.0 +00:00:00
committer holly sparkles <sparkles@holly.sh> 2024-02-06 11:19:30.0 +00:00:00
commit
0dc16a9da14eb4397dad7aad009c4447e3ab4e75 [patch]
tree
76213f9a3d4d9f347927685231d207cdac127df8
parent
4cdfc8bb80de6b09aadc80324c095949fcc5c7e8
download
0dc16a9da14eb4397dad7aad009c4447e3ab4e75.tar.gz

refactor: replace `as_str()` on message enums with `impl Display`

- automatic formatting of printed errors
- its better to not reinvent the wheel
- comes with `to_string()`

Diff

 src/data.rs   |  8 ++++----
 src/errors.rs | 23 ++++++++++++++---------
 src/main.rs   | 10 +++++-----
 3 files changed, 23 insertions(+), 18 deletions(-)

diff --git a/src/data.rs b/src/data.rs
index e6ad7b0..82b673b 100644
--- a/src/data.rs
+++ b/src/data.rs
@@ -36,7 +36,7 @@ impl Queryable for LicenseDatabase {
            .join("\n");

        if result.is_empty() {
            log::warn!("{}", ErrorMsg::NoLicensesAvailable.as_str());
            log::warn!("{}", ErrorMsg::NoLicensesAvailable);
            None
        } else {
            Some(result)
@@ -61,7 +61,7 @@ impl Queryable for LicenseDatabase {
            .join("\n");

        if result.is_empty() {
            log::warn!("{}", ErrorMsg::NoLicensesAvailable.as_str());
            log::warn!("{}", ErrorMsg::NoLicensesAvailable);
            None
        } else {
            Some(result)
@@ -87,11 +87,11 @@ impl LicenseDatabase {
        match std::fs::read_to_string(db_path.as_path()) {
            Ok(contents) => {
                let database: LicenseDatabase = serde_yaml::from_str(&contents).unwrap();
                log::info!("{}", SuccessMsg::DatabaseLoaded.as_str());
                log::info!("{}", SuccessMsg::DatabaseLoaded);
                Some(database)
            }
            Err(_) => {
                log::error!("{}", ErrorMsg::DatabaseError.as_str());
                log::error!("{}", ErrorMsg::DatabaseError);
                None
            }
        }
diff --git a/src/errors.rs b/src/errors.rs
index 0ed1956..93184e7 100644
--- a/src/errors.rs
+++ b/src/errors.rs
@@ -1,3 +1,5 @@
use std::fmt::Display;

#[derive(Debug)]
pub enum ErrorMsg {
    DatabaseError,
@@ -7,17 +9,19 @@ pub enum ErrorMsg {
    LicenseReadError,
}

impl ErrorMsg {
    pub fn as_str(&self) -> &str {
        match *self {
impl Display for ErrorMsg {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let message = match self {
            ErrorMsg::LicenseReadError => "Unable to read license file:",
            ErrorMsg::DatabaseError => "Unable to load or parse license database.",
            ErrorMsg::NoLicensesAvailable => "No licenses found.",
            ErrorMsg::InvalidLicenseRequest => { //TODO: make this not hardcoded
            ErrorMsg::InvalidLicenseRequest => {
                //TODO: make this not hardcoded
                "Invalid license. use the 'list' or 'list/all' endpoints to see defined licenses."
            }
            ErrorMsg::InvalidLicense => "Invalid license requested:",
        }
        };
        write!(f, "{}", message)
    }
}

@@ -26,10 +30,11 @@ pub enum SuccessMsg {
    DatabaseLoaded,
}

impl SuccessMsg {
    pub fn as_str(&self) -> &str {
        match *self {
impl Display for SuccessMsg {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let message = match self {
            SuccessMsg::DatabaseLoaded => "Database loaded successfully!",
        }
        };
        write!(f, "{}", message)
    }
}
diff --git a/src/main.rs b/src/main.rs
index a22da75..f3df657 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -116,7 +116,7 @@ async fn get_license_list(req: tide::Request<RunningConfig>) -> tide::Result<Res
        Some(licenses) => Ok(build_response(StatusCode::Ok, format!("{}", licenses))),
        None => Ok(build_response(
            StatusCode::NotFound,
            String::from(ErrorMsg::NoLicensesAvailable.as_str()),
            ErrorMsg::NoLicensesAvailable.to_string(),
        )),
    }
}
@@ -126,7 +126,7 @@ async fn get_detailed_license_list(req: tide::Request<RunningConfig>) -> tide::R
        Some(licenses) => Ok(build_response(StatusCode::Ok, format!("{}", licenses))),
        None => Ok(build_response(
            StatusCode::NotFound,
            String::from(ErrorMsg::NoLicensesAvailable.as_str()),
            ErrorMsg::NoLicensesAvailable.to_string(),
        )),
    }
}
@@ -153,7 +153,7 @@ async fn get_requested_license(req: tide::Request<RunningConfig>) -> tide::Resul
                Err(_) => {
                    log::error!(
                        "{} '{}'.",
                        ErrorMsg::LicenseReadError.as_str(),
                        ErrorMsg::LicenseReadError,
                        license_file_path.to_string_lossy().to_string()
                    );

@@ -162,7 +162,7 @@ async fn get_requested_license(req: tide::Request<RunningConfig>) -> tide::Resul
            }
        }
        None => {
            log::error!("{} '{}'", ErrorMsg::InvalidLicense.as_str(), request);
            log::error!("{} '{}'", ErrorMsg::InvalidLicense, request);
            error_response(request)
        }
    };
@@ -173,6 +173,6 @@ async fn get_requested_license(req: tide::Request<RunningConfig>) -> tide::Resul
fn error_response(_req: &str) -> Response {
    build_response(
        StatusCode::NotFound,
        format!("{}", ErrorMsg::InvalidLicenseRequest.as_str()).to_string(),
        format!("{}", ErrorMsg::InvalidLicenseRequest),
    )
}