Skip to content

Commit

Permalink
feat: env vars in path (#4)
Browse files Browse the repository at this point in the history
* add: regex crate

* feat: add in ability to use {{ENV_VAR}} inside of the path

* chg: update documentation to include env var usage
  • Loading branch information
whutchinson98 authored Jun 15, 2024
1 parent 1ea0991 commit 27c5099
Show file tree
Hide file tree
Showing 4 changed files with 98 additions and 5 deletions.
43 changes: 41 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ keywords = [
[dependencies]
anyhow = "1.0.72"
clap = { version="4.3.12", features=["derive"] }
regex = "1.10.4"
serde = {version = "1.0.171", features = ["derive"]}
serde_json = "1.0.117"
sha2 = "0.10.8"
Expand Down
12 changes: 10 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ A simple configurable cd wrapper that provides powerful utilities for customizin

## Features

- **Per Directory Environment Variables**
- **Per Directory Environment Variables**
- **Auto Load .env files in Directories**
- **Auto Execute Commands in Directories**
- **Per Directory Aliases**
Expand Down Expand Up @@ -178,7 +178,7 @@ dirs = [
]
```

## Configuration
## Configuration
### Global Configuration Options
```toml
[config]
Expand Down Expand Up @@ -244,6 +244,14 @@ dirs = [
]
```

### Using CDWE Environment Variables in the paths

If you want to use something like **$HOME** or any other environment variable
set in a path, you can do so by wrapping the environment variable inside of
`{{}}`. Using **$HOME** as an example, you would do {{HOME}}. This can make
using one cdwe.toml across many machines nice if you have different users but a
similar directory structure for each user.

## Uninstalling
1. Run cdwe-remove to clean up all shell artifacts
```bash
Expand Down
47 changes: 46 additions & 1 deletion src/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,19 @@ pub struct Cache {
values: DirCacheMap,
}

/// Inserts any cdwe path environment variables into itself and returns
/// updated path
fn insert_env_var_into_path(re: &regex::Regex, path: &str) -> String {
re.replace_all(path, |caps: &regex::Captures| {
if let Some(value) = std::env::var(&caps[1]).ok() {
value // If the env var exists, replace with its value
} else {
caps[0].to_string() // If not, keep the original text
}
})
.to_string()
}

impl Cache {
pub fn new(shell: String, hash: String, values: DirCacheMap) -> Self {
Cache {
Expand All @@ -35,6 +48,9 @@ impl Cache {
pub fn from_config(config: &Config, config_hash: &str) -> Self {
let mut values: DirCacheMap = HashMap::new();

// Captures the content within {{}}
let re = regex::Regex::new(r"\{\{(.*?)\}\}").unwrap();

for directory in &config.directories {
let variables: Vec<EnvVariable> = match &directory.vars {
Some(EnvVariableStruct::HashMap(hash_map)) => hash_map
Expand Down Expand Up @@ -67,7 +83,8 @@ impl Cache {
aliases,
};

values.insert(directory.path.clone(), dir_cache);
let result = insert_env_var_into_path(&re, directory.path.as_str());
values.insert(result, dir_cache);
}

let shell = match &config.config {
Expand Down Expand Up @@ -116,3 +133,31 @@ pub fn write_cache(cache: &Cache, home: &str) -> Result<()> {

Ok(())
}

#[cfg(test)]
mod tests {
use super::insert_env_var_into_path;

#[test]
fn test_insert_env_var_into_path() {
let re = regex::Regex::new(r"\{\{(.*?)\}\}").unwrap();
std::env::set_var("TEST_HOME", "/home/user");
std::env::set_var("TEST_NAME", "testing");
assert_eq!(
insert_env_var_into_path(&re, "{{TEST_HOME}}/testing"),
"/home/user/testing"
);
assert_eq!(
insert_env_var_into_path(&re, "{{TEST_HOME}}/{{TEST_NAME}}"),
"/home/user/testing"
);
assert_eq!(
insert_env_var_into_path(&re, "{{DOES_NOT_EXIST}}/{{TEST_NAME}}"),
"{{DOES_NOT_EXIST}}/testing"
);
assert_eq!(
insert_env_var_into_path(&re, "/home/user/testing"),
"/home/user/testing"
);
}
}

0 comments on commit 27c5099

Please sign in to comment.