
https://github.com/zed-industries/zed/issues/30972 brought up another case where our context is not enough to track the actual source of the issue: we get a general top-level error without inner error. The reason for this was `.ok_or_else(|| anyhow!("failed to read HEAD SHA"))?; ` on the top level. The PR finally reworks the way we use anyhow to reduce such issues (or at least make it simpler to bubble them up later in a fix). On top of that, uses a few more anyhow methods for better readability. * `.ok_or_else(|| anyhow!("..."))`, `map_err` and other similar error conversion/option reporting cases are replaced with `context` and `with_context` calls * in addition to that, various `anyhow!("failed to do ...")` are stripped with `.context("Doing ...")` messages instead to remove the parasitic `failed to` text * `anyhow::ensure!` is used instead of `if ... { return Err(...); }` calls * `anyhow::bail!` is used instead of `return Err(anyhow!(...));` Release Notes: - N/A
41 lines
1.3 KiB
Rust
41 lines
1.3 KiB
Rust
use anyhow::{Context as _, Result};
|
|
use std::fs;
|
|
use std::path::Path;
|
|
|
|
pub fn get_dotenv_vars(current_dir: impl AsRef<Path>) -> Result<Vec<(String, String)>> {
|
|
let current_dir = current_dir.as_ref();
|
|
|
|
let mut vars = Vec::new();
|
|
let env_content =
|
|
fs::read_to_string(current_dir.join(".env.toml")).context("no .env.toml file found")?;
|
|
|
|
add_vars(env_content, &mut vars)?;
|
|
|
|
if let Ok(secret_content) = fs::read_to_string(current_dir.join(".env.secret.toml")) {
|
|
add_vars(secret_content, &mut vars)?;
|
|
}
|
|
|
|
Ok(vars)
|
|
}
|
|
|
|
pub fn load_dotenv() -> Result<()> {
|
|
for (key, value) in get_dotenv_vars("./crates/collab")? {
|
|
unsafe { std::env::set_var(key, value) };
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn add_vars(env_content: String, vars: &mut Vec<(String, String)>) -> Result<()> {
|
|
let env: toml::map::Map<String, toml::Value> = toml::de::from_str(&env_content)?;
|
|
for (key, value) in env {
|
|
let value = match value {
|
|
toml::Value::String(value) => value,
|
|
toml::Value::Integer(value) => value.to_string(),
|
|
toml::Value::Float(value) => value.to_string(),
|
|
toml::Value::Boolean(value) => value.to_string(),
|
|
_ => panic!("unsupported TOML value in .env.toml for key {}", key),
|
|
};
|
|
vars.push((key, value));
|
|
}
|
|
Ok(())
|
|
}
|