File size: 3,294 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
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};

/// Load the environment variables defined via a dotenv file, with an
/// optional prior state that we can lookup already defined variables
/// from.
#[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();

                // Unfortunately, dotenvy only looks up variable references from the global env.
                // So we must mutate while we process. Afterwards, we can restore the initial
                // state.
                let initial = sorted_env_vars();

                restore_env(&initial, &prior, &lock);

                // from_read will load parse and evaluate the Read, and set variables
                // into the global env. If a later dotenv defines an already defined
                // var, it'll be ignored.
                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 {
            // We want to cell the value here and not just return the Vc.
            // This is important to avoid Vc changes when adding/removing the env file.
            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)
    }
}

/// Restores the global env variables to mirror `to`.
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) },
        }
    }
}