|
|
use std::{env, sync::MutexGuard}; |
|
|
|
|
|
use anyhow::{Context, Result, anyhow}; |
|
|
use turbo_rcstr::RcStr; |
|
|
use turbo_tasks::{FxIndexMap, ReadRef, ResolvedVc, Vc}; |
|
|
use turbo_tasks_fs::{FileContent, FileSystemPath}; |
|
|
|
|
|
use crate::{EnvMap, GLOBAL_ENV_LOCK, ProcessEnv, sorted_env_vars}; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
#[turbo_tasks::value] |
|
|
pub struct DotenvProcessEnv { |
|
|
prior: Option<ResolvedVc<Box<dyn ProcessEnv>>>, |
|
|
path: FileSystemPath, |
|
|
} |
|
|
|
|
|
#[turbo_tasks::value_impl] |
|
|
impl DotenvProcessEnv { |
|
|
#[turbo_tasks::function] |
|
|
pub fn new(prior: Option<ResolvedVc<Box<dyn ProcessEnv>>>, path: FileSystemPath) -> Vc<Self> { |
|
|
DotenvProcessEnv { prior, path }.cell() |
|
|
} |
|
|
|
|
|
#[turbo_tasks::function] |
|
|
pub fn read_prior(&self) -> Vc<EnvMap> { |
|
|
match self.prior { |
|
|
None => EnvMap::empty(), |
|
|
Some(p) => p.read_all(), |
|
|
} |
|
|
} |
|
|
|
|
|
#[turbo_tasks::function] |
|
|
pub async fn read_all_with_prior(self: Vc<Self>, prior: Vc<EnvMap>) -> Result<Vc<EnvMap>> { |
|
|
let this = self.await?; |
|
|
let prior = prior.await?; |
|
|
|
|
|
let file = this.path.read().await?; |
|
|
if let FileContent::Content(f) = &*file { |
|
|
let res; |
|
|
let vars; |
|
|
{ |
|
|
let lock = GLOBAL_ENV_LOCK.lock().unwrap(); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
let initial = sorted_env_vars(); |
|
|
|
|
|
restore_env(&initial, &prior, &lock); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
res = dotenv::from_read(f.read()).map(|e| e.load()); |
|
|
|
|
|
vars = sorted_env_vars(); |
|
|
restore_env(&vars, &initial, &lock); |
|
|
} |
|
|
|
|
|
if let Err(e) = res { |
|
|
return Err(e).context(anyhow!( |
|
|
"unable to read {} for env vars", |
|
|
this.path.value_to_string().await? |
|
|
)); |
|
|
} |
|
|
|
|
|
Ok(Vc::cell(vars)) |
|
|
} else { |
|
|
|
|
|
|
|
|
Ok(ReadRef::cell(prior)) |
|
|
} |
|
|
} |
|
|
} |
|
|
|
|
|
#[turbo_tasks::value_impl] |
|
|
impl ProcessEnv for DotenvProcessEnv { |
|
|
#[turbo_tasks::function] |
|
|
fn read_all(self: Vc<Self>) -> Vc<EnvMap> { |
|
|
let prior = self.read_prior(); |
|
|
self.read_all_with_prior(prior) |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
fn restore_env( |
|
|
from: &FxIndexMap<RcStr, RcStr>, |
|
|
to: &FxIndexMap<RcStr, RcStr>, |
|
|
_lock: &MutexGuard<()>, |
|
|
) { |
|
|
for key in from.keys() { |
|
|
if !to.contains_key(key) { |
|
|
unsafe { env::remove_var(key) }; |
|
|
} |
|
|
} |
|
|
for (key, value) in to { |
|
|
match from.get(key) { |
|
|
Some(v) if v == value => {} |
|
|
_ => unsafe { env::set_var(key, value) }, |
|
|
} |
|
|
} |
|
|
} |
|
|
|