3个版本 (重大更新)
0.3.0 | 2023年11月27日 |
---|---|
0.2.0 | 2023年10月19日 |
0.1.0 | 2023年10月18日 |
1436 in 进程宏
12KB
98 行
file_env_const
此crate提供在编译时从文件或环境变量加载数据并具有后备选项的宏。
当构建具有硬编码字符串的二进制文件时,你可能希望将其作为环境变量注入到构建环境中(例如在CI中),或者当离线构建时在本地文件中存储,两种情况都有后备选项。
示例
加载文件,具有环境后备
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");
加载环境变量,具有文件后备
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");
依赖项
~290–740KB
~18K SLoC