cargo_px_env/
lib.rs

1#![doc = include_str!("../README.md")]
2use std::path::PathBuf;
3
4use crate::error::{InvalidUnicodeError, MissingVarError, VarError};
5
6pub mod error;
7
8/// The name of the environment variable that contains the path to the root directory
9/// of the current workspace.
10pub const WORKSPACE_ROOT_DIR_ENV: &str = "CARGO_PX_WORKSPACE_ROOT_DIR";
11/// The name of the environment variable that contains the path to the manifest
12/// of the crate that must be generated.
13pub const GENERATED_PKG_MANIFEST_PATH_ENV: &str = "CARGO_PX_GENERATED_PKG_MANIFEST_PATH";
14
15/// Retrieve the path to the workspace root directory.
16///
17/// It returns an error if the variable is not set or if it contains invalid Unicode data.
18pub fn workspace_root_dir() -> Result<PathBuf, VarError> {
19    px_env_var(WORKSPACE_ROOT_DIR_ENV).map(PathBuf::from)
20}
21
22/// Retrieve the path to the manifest of the crate that must be generated.
23///
24/// It returns an error if the variable is not set or if it contains invalid Unicode data.
25pub fn generated_pkg_manifest_path() -> Result<PathBuf, VarError> {
26    px_env_var(GENERATED_PKG_MANIFEST_PATH_ENV).map(PathBuf::from)
27}
28
29/// Retrieve the value of an env variable set by `cargo px`.
30///
31/// It returns an error if the variable is not set or if it contains invalid Unicode data.
32fn px_env_var(name: &'static str) -> Result<String, VarError> {
33    use std::env::{var, VarError};
34
35    var(name).map_err(|e| match e {
36        VarError::NotPresent => {
37            crate::error::VarError::Missing(MissingVarError { name, source: e })
38        }
39        VarError::NotUnicode(_) => {
40            crate::error::VarError::InvalidUnicode(InvalidUnicodeError { name, source: e })
41        }
42    })
43}