use std::env; use std::fs::File; use std::io::Write; use std::str::FromStr; fn parse_value_from_config_with_default( key: &str, default: Option, ) -> Result { // Retrieve the value of the environment variable match env::var(key) { Ok(value) => match value.parse::() { Ok(val) => Ok(val), Err(_) => { Err(format!("env var '{}' with value '{}' cannot be parsed into type '{2}'. Please set an env var can be parsed into '{2}'", key, value, std::any::type_name::())) } }, Err(_) => match default { Some(val) => Ok(val), None => { eprintln!("MAX_LOGGER_CAPACITY environment variable is not set"); Err(format!("env '{}' is not set and there are no defaults for it. Please set it in your env.", key)) } }, } } fn main() { println!("cargo:rerun-if-env-changed=QUICKLOG_MAX_SERIALIZE_BUFFER_CAPACITY"); let max_buffer_capacity = match parse_value_from_config_with_default( "QUICKLOG_MAX_SERIALIZE_BUFFER_CAPACITY", Some(1_000_000_usize), ) { Ok(val) => val, Err(err) => { println!("cargo:warning={}", err); 1_000_000 } }; println!("cargo:rerun-if-env-changed=QUICKLOG_MAX_LOGGER_CAPACITY"); let max_logger_capacity = match parse_value_from_config_with_default( "QUICKLOG_MAX_LOGGER_CAPACITY", Some(1_000_000_usize), ) { Ok(val) => val, Err(err) => { println!("cargo:warning={}", err); 1_000_000 } }; // Generate the Rust source code let rust_code = format!( "// This file was generated by `build.rs`, do not modify this file manually! /// Sets max capacity of logging queue, can be set through env var `QUICKLOG_MAX_LOGGER_CAPACITY`. pub const MAX_LOGGER_CAPACITY: usize = {}; /// Sets max capacity of byte buffer used for serialization with `^` prefix in logging, can be set through `QUICKLOG_MAX_SERIALIZE_BUFFER_CAPACITY`. pub const MAX_SERIALIZE_BUFFER_CAPACITY: usize = {}; ", max_logger_capacity, max_buffer_capacity ); // Write the code to a file let dest_path = std::path::Path::new("").join("src/constants.rs"); match File::create(dest_path) { Ok(mut file) => { if let Err(err) = file.write_all(rust_code.as_bytes()) { println!("cargo:warning={}", err) } } Err(err) => println!("cargo:warning={}", err), } }