hhh 1.0.1

The hhh Binary File Processor
Documentation
// hhh
// Copyright (c) 2023 by Stacy Prowell.  All rights reserved.
// https://gitlab.com/sprowell/hhh

//! Read a configuration file.

use crate::{directives::parse_directive, options::HhhArgs};
use std::path::Path;
use trivet::{
    errors::{io_error, syntax_error},
    parse_from_path,
    parser::ParseResult,
    Loc,
};

/// Read a configuration file and execute all the directives found in the file.
pub fn read_configuration_file(path: &Path, config: &mut HhhArgs) -> ParseResult<()> {
    let mut parser = match parse_from_path(&path.to_path_buf()) {
        Ok(parser) => parser,
        Err(error) => return Err(io_error(Loc::Internal, error)),
    };

    // Parse directives from the file.
    parser.consume_ws();
    while !parser.is_at_eof() {
        let loc = parser.loc();
        let directive = parse_directive(&mut parser, config)?;
        match directive.execute(config) {
            None => {}
            Some(msg) => {
                return Err(syntax_error(loc, &msg));
            }
        }
        parser.consume_ws();
    }

    Ok(())
}

#[cfg(test)]
mod test {
    use super::read_configuration_file;
    use crate::options::HhhArgs;
    use std::path::PathBuf;

    #[test]
    fn read_configuration_file_test() {
        let path = PathBuf::from("test_files/test.config");
        let mut config = HhhArgs::default();
        read_configuration_file(&path, &mut config).unwrap();
        assert!(config.radix_prefixes);
        assert!(config.no_ascii);
        assert_eq!(
            config.get_variable("x"),
            Some(vec![0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0x40u8, 0x00u8])
        );
        assert_eq!(config.bias, 0x4000);

        let path = PathBuf::from("does-not-exist");
        assert!(read_configuration_file(&path, &mut config).is_err());

        let path = PathBuf::from("test_files/bad.config");
        assert!(read_configuration_file(&path, &mut config).is_err());
    }
}