This commit is contained in:
Thorsten Sommer 2023-11-10 18:41:52 +01:00
commit 593e5beafc
Signed by: tsommer
GPG Key ID: 371BBA77A02C0108
9 changed files with 235 additions and 0 deletions

81
.gitignore vendored Normal file
View File

@ -0,0 +1,81 @@
/target
### JetBrains template
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# AWS User-specific
.idea/**/aws.xml
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# mpeltonen/sbt-idea plugin
.idea_modules/
# Cursive Clojure plugin
.idea/replstate.xml
# SonarLint plugin
.idea/sonarlint/
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
### Rust template
# Generated by Cargo
# will have compiled files and executables
debug/
target/
# These are backup files generated by rustfmt
**/*.rs.bk
# MSVC Windows builds of rustc generate these, which store debugging information
*.pdb
# Added by cargo
#
# already existing elements were commented out
#/target
/Cargo.lock

8
.idea/.gitignore vendored Normal file
View File

@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

11
.idea/envhead.iml Normal file
View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="EMPTY_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

8
.idea/modules.xml Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/envhead.iml" filepath="$PROJECT_DIR$/.idea/envhead.iml" />
</modules>
</component>
</project>

6
.idea/vcs.xml Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

19
Cargo.toml Normal file
View File

@ -0,0 +1,19 @@
[package]
name = "envhead"
version = "1.0.0"
edition = "2021"
authors = ["Thorsten Sommer"]
description = "A crate to build environment variable names using a static prefix. Works great with the popular clap crate."
license = "MIT"
homepage = "https://devops.tsommer.org/open-source/rust/crates/envhead"
repository = "https://devops.tsommer.org/open-source/rust/crates/envhead"
readme = "README.md"
keywords = ["cli", "shell", "clap", "os"]
categories = ["command-line-interface", "development-tools::procedural-macro-helpers"]
[lib]
proc-macro = true
[dependencies]
quote = "1.0.33"
syn = "2.0.39"

19
LICENSE Normal file
View File

@ -0,0 +1,19 @@
Copyright (c) 2023 Thorsten Sommer
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

64
README.md Normal file
View File

@ -0,0 +1,64 @@
# Envhead
Envhead is a crate that creates environment variable names using a static prefix. The desired prefix is defined in your build script `build.rs`.
### Usage
First, you should define the prefix in your `build.rs` file. In this example, we will use `MY_APP` as the prefix:
```rust
fn main() {
println!("cargo:rustc-env=ENV_HEAD_PREFIX=MY_APP");
}
```
When the `ENV_HEAD_PREFIX` variable is not defined, `ENV` is used as the default prefix.
Then, in your code, you can use the `envhead!` macro to create environment variable names.
```rust
use envhead::envhead;
fn main() {
let env_var = envhead!("server_port");
// Prints "MY_APP_SERVER_PORT":
println!("{}", env_var);
}
```
You might find it useful to use `envhead` together with `clap` to create environment variable names for your command line arguments:
```rust
use clap::Args;
use envhead::envhead;
#[derive(Debug, Args)]
pub struct ServerArgs {
#[arg(
short = 'p', long,
required = false,
value_name = "port",
value_hint = clap::ValueHint::Other,
help = "The server's port.",
default_value_t = 8000,
env = envhead!("server_port"),
)]
pub port: u16,
#[arg(
long,
required = true,
value_name = "SECRET_TOKEN",
value_hint = clap::ValueHint::Other,
help = "The secret token to authenticate the client.",
env = envhead!("server_secret_token"),
)]
pub secret_token: Option<String>,
}
```
# Changelog
### Version 1.0.0
- Initial release

19
src/lib.rs Normal file
View File

@ -0,0 +1,19 @@
extern crate proc_macro;
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, LitStr};
/// This macro is used to get the environment variable prefixed with the `ENV_LEAD_PREFIX` environment variable.
/// If `ENV_LEAD_PREFIX` is not set, it will default to `ENV`. The given string will be converted to uppercase.
#[proc_macro]
pub fn envhead(input: TokenStream) -> TokenStream {
let prefix = option_env!("ENV_HEAD_PREFIX").unwrap_or("ENV");
let input = parse_macro_input!(input as LitStr);
let value = input.value();
let upper_value = format!("{}_{}", prefix.to_uppercase(), value.to_uppercase());
let expanded = quote! {
#upper_value
};
TokenStream::from(expanded)
}