#env-var #compile-time #data-file #variables #environment #env-file #fallback

macro file_env_const

macros for loading data from files or environment variables at compile time

3 releases (breaking)

0.3.0 Nov 27, 2023
0.2.0 Oct 19, 2023
0.1.0 Oct 18, 2023

#863 in Procedural macros

Download history 2/week @ 2024-02-14 14/week @ 2024-02-21 4/week @ 2024-02-28 3/week @ 2024-03-06 20/week @ 2024-03-13 17/week @ 2024-03-27 34/week @ 2024-04-03

51 downloads per month

MIT license

12KB
98 lines

file_env_const

Crates.io Documentation Build status License

This crate provides macros for loading data at compile time from a file or environment variable, with fallback options.

This is useful in the case of building a binary with hard-coded strings which you may wish to inject as environment variables in a build environment (say in CI), or store locally in a file when building offline, with a fallback option in either case.

Examples

Loading a file, with environment fallback

use file_env_const::file_env;
// Read data from file first
const FILE_DATA: &'static str = file_env!("Cargo.toml", "CARGO_PKG_NAME");
let f = std::fs::read_to_string("Cargo.toml").unwrap();
assert_eq!(FILE_DATA, f);

// Tries to read data from file, falls back to environment variable which is the package name
const FALL_BACK_TO_ENV: &'static str = file_env!("file_does_not_exist", "CARGO_PKG_NAME");
assert_eq!(FALL_BACK_TO_ENV, "file_env_const");

// Tries to read data from file, falls back to environment variable which is the package name
const FALL_BACK_TO_DEFAULT: &'static str =
    file_env!("file_does_not_exist", "ENV_NOT_FOUND", "fallback string");
assert_eq!(FALL_BACK_TO_DEFAULT, "fallback string");

Loading an environment variable, with file fallback

use file_env_const::env_file;
// Read data from file first
const ENV_DATA: &'static str = env_file!("CARGO_PKG_NAME", "Cargo.toml");
assert_eq!(ENV_DATA, "file_env_const");

// Tries to read data from file, falls back to environment variable which is the package name
const FALL_BACK_TO_FILE: &'static str = env_file!("ENV_NOT_FOUND", "Cargo.toml");
let f = std::fs::read_to_string("Cargo.toml").unwrap();
assert_eq!(FALL_BACK_TO_FILE, f);

// Tries to read data from file, falls back to environment variable which is the package name
const FALL_BACK_TO_DEFAULT: &'static str =
    env_file!( "ENV_NOT_FOUND", "file_does_not_exist", "fallback string");
assert_eq!(FALL_BACK_TO_DEFAULT, "fallback string");

Dependencies

~320–770KB
~18K SLoC