#env-var #environment #build #env #settings #proc-macro

envtime

Rust的运行时和编译时环境解析

4个版本

0.0.4 2023年6月26日
0.0.3 2023年6月25日
0.0.2 2023年6月25日
0.0.1 2023年6月25日

#609 in 过程宏

每月 35 次下载

MIT 许可证

14KB
147

envtime

此crate提供了一个过程宏,可以在编译时或运行时检索环境变量。

在编译时指定环境变量,则运行时变量将不会被评估。如果在编译时没有指定环境变量,则将在运行时进行评估。

如果设置了编译时变量,编译器将负责进行优化和删除代码。

安装

[dependencies]
envtime = "0.0.4"

语法 & 用法

use envtime::*;

// You can use unwrap_or_else on the envtime macro
let var = envtime!("TEST_NON_ENV").unwrap_or_else(|| String::from("hello"));
assert_eq!(var, String::from("hello"));
// This resolves to "hello" assuming it is not defined at compile time or runtime 

// Lets set a runtime variable to "123"
env::set_var("TEST_RUN_ENV", "123");
let var = envtime!("TEST_RUN_ENV");
assert_eq!(var, Some(String::from("123")));
// And it gets the value at runtime

// Assume we have a compile time variable set to "456"
env::set_var("TEST_COMP_ENV", "123"); // We set the runtime variable to "123"
let var = envtime!("TEST_COMP_ENV");
assert_eq!(var, Some(String::from("456")));
// The runtime variable is ignored, as the macro resolves to 'String::from("456")' at compile time

// Assume we don't have the runtime variable set at first, you can see the default value being used
assert_eq!(envtime_def!("TEST_STR_RUN_ENV", "test"), "test");
env::set_var("TEST_STR_RUN_ENV", "not");
assert_eq!(envtime_def!("TEST_STR_RUN_ENV", "test"), "not");
// Once it is set it resolves to our runtime value

// Assume we have "TEST_BOOL_COMP_ENV" at compile time to "true"
env::set_var("TEST_BOOL_COMP_ENV", "false"); // Sets the runtime-variable, which is ignored
let enable_test = envtime_def!("TEST_BOOL_COMP_ENV", false);  // Resolves to the literal "true"
assert_eq!(enable_test, true);
// With the default value being false, and the runtime value being false, it still evaluates to true

// Example with u8 at runtime
assert_eq!(envtime_def!("TEST_U8_RUN_ENV", 77u8), 77u8);
env::set_var("TEST_U8_RUN_ENV", "53");
assert_eq!(envtime_def!("TEST_U8_RUN_ENV", 77u8), 53u8);

注意

对于整数字面量,强烈建议包括后缀“u8”/“i8”/“u16”/“i16”等。对于字符串字面量,由于编译时和运行时环境的不同,始终使用String::from()。

许可证

本项目采用MIT许可证

依赖

~255–700KB
~17K SLoC