flareapp-core 0.3.0

The core of the Flare client: config, the client, and the worker thread that sends data.
Documentation
//! Reads the `.env` file, so [`Config::new`](crate::Config::new) can take its
//! settings from there without the app loading the file first.
//!
//! The values are kept in memory only. They are never written to the process
//! environment, so the environment of the app does not change.

#[cfg(feature = "dotenv")]
use std::path::Path;

/// The variables of a `.env` file, in the order of the file.
#[derive(Debug, Default)]
pub(crate) struct DotenvFile {
    variables: Vec<(String, String)>,
    /// Why the file was not read completely, when it has an error.
    error: Option<String>,
}

impl DotenvFile {
    /// Reads the `.env` file in the current folder. Returns an empty file when
    /// the folder has no `.env` file.
    ///
    /// This function does not search parent folders. A `.env` file in a parent
    /// folder can change the host that receives the API key of the Flare client.
    #[cfg(feature = "dotenv")]
    pub(crate) fn find() -> Self {
        Self::in_folder(Path::new("."))
    }

    /// Reads the `.env` file in `folder`. This function reads no other file.
    #[cfg(feature = "dotenv")]
    fn in_folder(folder: &Path) -> Self {
        match dotenvy::from_path_iter(folder.join(".env")) {
            Ok(variables) => Self::read(variables),
            Err(error) if error.not_found() => Self::default(),
            Err(error) => Self {
                variables: Vec::new(),
                error: Some(error.to_string()),
            },
        }
    }

    /// Returns an empty file, because the `dotenv` feature is off.
    #[cfg(not(feature = "dotenv"))]
    pub(crate) fn find() -> Self {
        Self::default()
    }

    /// Reads variables until the end of the file, or until the first line that
    /// cannot be parsed.
    #[cfg(feature = "dotenv")]
    fn read<I>(variables: I) -> Self
    where
        I: Iterator<Item = Result<(String, String), dotenvy::Error>>,
    {
        let mut file = Self::default();
        for variable in variables {
            match variable {
                Ok(variable) => file.variables.push(variable),
                Err(error) => {
                    file.error = Some(error.to_string());
                    break;
                }
            }
        }

        file
    }

    /// Returns the value of the variable `name`. When the file sets it more than
    /// once, the first value wins, as when `dotenvy` loads the file.
    pub(crate) fn get(&self, name: &str) -> Option<String> {
        self.variables
            .iter()
            .find(|(variable, _)| variable == name)
            .map(|(_, value)| value.clone())
    }

    /// Returns why the file was not read completely.
    pub(crate) fn error(&self) -> Option<&str> {
        self.error.as_deref()
    }

    #[cfg(test)]
    pub(crate) fn from_variables<const N: usize>(variables: [(&str, &str); N]) -> Self {
        Self {
            variables: variables
                .iter()
                .map(|(name, value)| ((*name).to_owned(), (*value).to_owned()))
                .collect(),
            error: None,
        }
    }

    #[cfg(test)]
    pub(crate) fn with_error(error: &str) -> Self {
        Self {
            variables: Vec::new(),
            error: Some(error.to_owned()),
        }
    }
}

#[cfg(all(test, feature = "dotenv"))]
mod tests {
    use std::io::Cursor;

    use super::*;

    fn parse(contents: &str) -> DotenvFile {
        DotenvFile::read(dotenvy::Iter::new(Cursor::new(contents)))
    }

    /// A file with a comment, a plain value and an exported value in quotes.
    const FILE: &str = "# Flare\nFLARE_KEY=secret\nexport FLARE_ENVIRONMENT=\"staging\"\n";

    #[test]
    fn reads_the_file_in_the_folder() {
        let folder = tempfile::tempdir().unwrap();
        std::fs::write(folder.path().join(".env"), FILE).unwrap();

        let file = DotenvFile::in_folder(folder.path());

        assert_eq!(file.get("FLARE_KEY").as_deref(), Some("secret"));
    }

    #[test]
    fn does_not_read_the_file_of_a_parent_folder() {
        let parent = tempfile::tempdir().unwrap();
        std::fs::write(parent.path().join(".env"), FILE).unwrap();
        let child = parent.path().join("child");
        std::fs::create_dir(&child).unwrap();

        let file = DotenvFile::in_folder(&child);

        assert_eq!(file.get("FLARE_KEY"), None);
        assert_eq!(file.error(), None);
    }

    #[test]
    fn reads_plain_values() {
        assert_eq!(parse(FILE).get("FLARE_KEY").as_deref(), Some("secret"));
    }

    #[test]
    fn reads_exported_values_without_their_quotes() {
        assert_eq!(
            parse(FILE).get("FLARE_ENVIRONMENT").as_deref(),
            Some("staging")
        );
    }

    #[test]
    fn has_no_value_for_a_missing_name() {
        assert_eq!(parse(FILE).get("FLARE_ENDPOINT"), None);
    }

    #[test]
    fn has_no_error_for_a_valid_file() {
        assert_eq!(parse(FILE).error(), None);
    }

    #[test]
    fn first_value_wins() {
        let file = parse("FLARE_KEY=first\nFLARE_KEY=second\n");

        assert_eq!(file.get("FLARE_KEY").as_deref(), Some("first"));
    }

    /// A file with a valid line, an invalid line, and a valid line after it.
    const INVALID_FILE: &str = "FLARE_KEY=secret\nnot valid\nFLARE_ENVIRONMENT=staging\n";

    #[test]
    fn keeps_the_values_before_an_invalid_line() {
        assert_eq!(
            parse(INVALID_FILE).get("FLARE_KEY").as_deref(),
            Some("secret")
        );
    }

    #[test]
    fn stops_at_an_invalid_line() {
        assert_eq!(parse(INVALID_FILE).get("FLARE_ENVIRONMENT"), None);
    }

    #[test]
    fn has_an_error_for_an_invalid_line() {
        let file = parse(INVALID_FILE);

        assert!(file.error().is_some(), "{file:?}");
    }
}