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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
use crate::context::Context;
use crate::data::config::{Conf, NuConfig};

use crate::env::environment::{Env, Environment};
use nu_source::Text;
use parking_lot::Mutex;
use std::sync::Arc;

pub struct EnvironmentSyncer {
    pub env: Arc<Mutex<Box<Environment>>>,
    pub config: Arc<Box<dyn Conf>>,
}

impl Default for EnvironmentSyncer {
    fn default() -> Self {
        Self::new()
    }
}

impl EnvironmentSyncer {
    pub fn new() -> EnvironmentSyncer {
        EnvironmentSyncer {
            env: Arc::new(Mutex::new(Box::new(Environment::new()))),
            config: Arc::new(Box::new(NuConfig::new())),
        }
    }

    #[cfg(test)]
    pub fn set_config(&mut self, config: Box<dyn Conf>) {
        self.config = Arc::new(config);
    }

    pub fn load_environment(&mut self) {
        let config = self.config.clone();

        self.env = Arc::new(Mutex::new(Box::new(Environment::from_config(&*config))));
    }

    pub fn reload(&mut self) {
        self.config.reload();

        let mut environment = self.env.lock();
        environment.morph(&*self.config);
    }

    pub fn sync_env_vars(&mut self, ctx: &mut Context) {
        let mut environment = self.env.lock();

        if let Err(e) = environment.autoenv(ctx.user_recently_used_autoenv_untrust) {
            crate::cli::print_err(e, &Text::from(""));
        }
        ctx.user_recently_used_autoenv_untrust = false;
        if environment.env().is_some() {
            for (name, value) in ctx.with_host(|host| host.vars()) {
                if name != "path" && name != "PATH" {
                    // account for new env vars present in the current session
                    // that aren't loaded from config.
                    environment.add_env(&name, &value);

                    // clear the env var from the session
                    // we are about to replace them
                    ctx.with_host(|host| host.env_rm(std::ffi::OsString::from(name)));
                }
            }

            if let Some(variables) = environment.env() {
                for var in variables.row_entries() {
                    if let Ok(string) = var.1.as_string() {
                        ctx.with_host(|host| {
                            host.env_set(
                                std::ffi::OsString::from(var.0),
                                std::ffi::OsString::from(string),
                            )
                        });
                    }
                }
            }
        }
    }

    pub fn sync_path_vars(&mut self, ctx: &mut Context) {
        let mut environment = self.env.lock();

        if environment.path().is_some() {
            let native_paths = ctx.with_host(|host| host.env_get(std::ffi::OsString::from("PATH")));

            if let Some(native_paths) = native_paths {
                environment.add_path(native_paths);

                ctx.with_host(|host| {
                    host.env_rm(std::ffi::OsString::from("PATH"));
                });
            }

            if let Some(new_paths) = environment.path() {
                let prepared = std::env::join_paths(
                    new_paths
                        .table_entries()
                        .map(|p| p.as_string())
                        .filter_map(Result::ok),
                );

                if let Ok(paths_ready) = prepared {
                    ctx.with_host(|host| {
                        host.env_set(std::ffi::OsString::from("PATH"), paths_ready);
                    });
                }
            }
        }
    }

    #[cfg(test)]
    pub fn clear_env_vars(&mut self, ctx: &mut Context) {
        for (key, _value) in ctx.with_host(|host| host.vars()) {
            if key != "path" && key != "PATH" {
                ctx.with_host(|host| host.env_rm(std::ffi::OsString::from(key)));
            }
        }
    }

    #[cfg(test)]
    pub fn clear_path_var(&mut self, ctx: &mut Context) {
        ctx.with_host(|host| host.env_rm(std::ffi::OsString::from("PATH")));
    }
}

#[cfg(test)]
mod tests {
    use super::EnvironmentSyncer;
    use crate::context::Context;
    use crate::data::config::tests::FakeConfig;
    use crate::env::environment::Env;
    use indexmap::IndexMap;
    use nu_errors::ShellError;
    use nu_test_support::fs::Stub::FileWithContent;
    use nu_test_support::playground::Playground;
    use parking_lot::Mutex;
    use std::path::PathBuf;
    use std::sync::Arc;

    #[test]
    fn syncs_env_if_new_env_entry_in_session_is_not_in_configuration_file() -> Result<(), ShellError>
    {
        let mut ctx = Context::basic()?;
        ctx.host = Arc::new(Mutex::new(Box::new(crate::env::host::FakeHost::new())));

        let mut expected = IndexMap::new();
        expected.insert(
            "SHELL".to_string(),
            "/usr/bin/you_already_made_the_nu_choice".to_string(),
        );
        expected.insert("USER".to_string(), "NUNO".to_string());

        Playground::setup("syncs_env_test_1", |dirs, sandbox| {
            sandbox.with_files(vec![FileWithContent(
                "configuration.toml",
                r#"
                    [env]
                    SHELL = "/usr/bin/you_already_made_the_nu_choice"
                "#,
            )]);

            let mut file = dirs.test().clone();
            file.push("configuration.toml");

            let fake_config = FakeConfig::new(&file);
            let mut actual = EnvironmentSyncer::new();
            actual.set_config(Box::new(fake_config));

            // Here, the environment variables from the current session
            // are cleared since we will load and set them from the
            // configuration file (if any)
            actual.clear_env_vars(&mut ctx);

            // We explicitly simulate and add the USER variable to the current
            // session's environment variables with the value "NUNO".
            ctx.with_host(|test_host| {
                test_host.env_set(
                    std::ffi::OsString::from("USER"),
                    std::ffi::OsString::from("NUNO"),
                )
            });

            // Nu loads the environment variables from the configuration file (if any)
            actual.load_environment();

            // By this point, Nu has already loaded the environment variables
            // stored in the configuration file. Before continuing we check
            // if any new environment variables have been added from the ones loaded
            // in the configuration file.
            //
            // Nu sees the missing "USER" variable and accounts for it.
            actual.sync_env_vars(&mut ctx);

            // Confirms session environment variables are replaced from Nu configuration file
            // including the newer one accounted for.
            ctx.with_host(|test_host| {
                let var_user = test_host
                    .env_get(std::ffi::OsString::from("USER"))
                    .expect("Couldn't get USER var from host.")
                    .into_string()
                    .expect("Couldn't convert to string.");

                let var_shell = test_host
                    .env_get(std::ffi::OsString::from("SHELL"))
                    .expect("Couldn't get SHELL var from host.")
                    .into_string()
                    .expect("Couldn't convert to string.");

                let mut found = IndexMap::new();
                found.insert("SHELL".to_string(), var_shell);
                found.insert("USER".to_string(), var_user);

                for k in found.keys() {
                    assert!(expected.contains_key(k));
                }
            });

            // Now confirm in-memory environment variables synced appropriately
            // including the newer one accounted for.
            let environment = actual.env.lock();

            let mut vars = IndexMap::new();
            environment
                .env()
                .expect("No variables in the environment.")
                .row_entries()
                .for_each(|(name, value)| {
                    vars.insert(
                        name.to_string(),
                        value.as_string().expect("Couldn't convert to string"),
                    );
                });
            for k in expected.keys() {
                assert!(vars.contains_key(k));
            }
        });
        Ok(())
    }

    #[test]
    fn nu_envs_have_higher_priority_and_does_not_get_overwritten() -> Result<(), ShellError> {
        let mut ctx = Context::basic()?;
        ctx.host = Arc::new(Mutex::new(Box::new(crate::env::host::FakeHost::new())));

        let mut expected = IndexMap::new();
        expected.insert(
            "SHELL".to_string(),
            "/usr/bin/you_already_made_the_nu_choice".to_string(),
        );

        Playground::setup("syncs_env_test_2", |dirs, sandbox| {
            sandbox.with_files(vec![FileWithContent(
                "configuration.toml",
                r#"
                    [env]
                    SHELL = "/usr/bin/you_already_made_the_nu_choice"
                "#,
            )]);

            let mut file = dirs.test().clone();
            file.push("configuration.toml");

            let fake_config = FakeConfig::new(&file);
            let mut actual = EnvironmentSyncer::new();
            actual.set_config(Box::new(fake_config));

            actual.clear_env_vars(&mut ctx);

            ctx.with_host(|test_host| {
                test_host.env_set(
                    std::ffi::OsString::from("SHELL"),
                    std::ffi::OsString::from("/usr/bin/sh"),
                )
            });

            actual.load_environment();
            actual.sync_env_vars(&mut ctx);

            ctx.with_host(|test_host| {
                let var_shell = test_host
                    .env_get(std::ffi::OsString::from("SHELL"))
                    .expect("Couldn't get SHELL var from host.")
                    .into_string()
                    .expect("Couldn't convert to string.");

                let mut found = IndexMap::new();
                found.insert("SHELL".to_string(), var_shell);

                for k in found.keys() {
                    assert!(expected.contains_key(k));
                }
            });

            let environment = actual.env.lock();

            let mut vars = IndexMap::new();
            environment
                .env()
                .expect("No variables in the environment.")
                .row_entries()
                .for_each(|(name, value)| {
                    vars.insert(
                        name.to_string(),
                        value.as_string().expect("couldn't convert to string"),
                    );
                });
            for k in expected.keys() {
                assert!(vars.contains_key(k));
            }
        });

        Ok(())
    }

    #[test]
    fn syncs_path_if_new_path_entry_in_session_is_not_in_configuration_file(
    ) -> Result<(), ShellError> {
        let mut ctx = Context::basic()?;
        ctx.host = Arc::new(Mutex::new(Box::new(crate::env::host::FakeHost::new())));

        let expected = std::env::join_paths(vec![
            PathBuf::from("/Users/andresrobalino/.volta/bin"),
            PathBuf::from("/Users/mosqueteros/bin"),
            PathBuf::from("/path/to/be/added"),
        ])
        .expect("Couldn't join paths.")
        .into_string()
        .expect("Couldn't convert to string.");

        Playground::setup("syncs_path_test_1", |dirs, sandbox| {
            sandbox.with_files(vec![FileWithContent(
                "configuration.toml",
                r#"
                    path = ["/Users/andresrobalino/.volta/bin", "/Users/mosqueteros/bin"]
                "#,
            )]);

            let mut file = dirs.test().clone();
            file.push("configuration.toml");

            let fake_config = FakeConfig::new(&file);
            let mut actual = EnvironmentSyncer::new();
            actual.set_config(Box::new(fake_config));

            // Here, the environment variables from the current session
            // are cleared since we will load and set them from the
            // configuration file (if any)
            actual.clear_path_var(&mut ctx);

            // We explicitly simulate and add the PATH variable to the current
            // session with the path "/path/to/be/added".
            ctx.with_host(|test_host| {
                test_host.env_set(
                    std::ffi::OsString::from("PATH"),
                    std::env::join_paths(vec![PathBuf::from("/path/to/be/added")])
                        .expect("Couldn't join paths."),
                )
            });

            // Nu loads the path variables from the configuration file (if any)
            actual.load_environment();

            // By this point, Nu has already loaded environment path variable
            // stored in the configuration file. Before continuing we check
            // if any new paths have been added from the ones loaded in the
            // configuration file.
            //
            // Nu sees the missing "/path/to/be/added" and accounts for it.
            actual.sync_path_vars(&mut ctx);

            ctx.with_host(|test_host| {
                let actual = test_host
                    .env_get(std::ffi::OsString::from("PATH"))
                    .expect("Couldn't get PATH var from host.")
                    .into_string()
                    .expect("Couldn't convert to string.");

                assert_eq!(actual, expected);
            });

            let environment = actual.env.lock();

            let paths = std::env::join_paths(
                &environment
                    .path()
                    .expect("No path variable in the environment.")
                    .table_entries()
                    .map(|value| value.as_string().expect("Couldn't convert to string"))
                    .map(PathBuf::from)
                    .collect::<Vec<_>>(),
            )
            .expect("Couldn't join paths.")
            .into_string()
            .expect("Couldn't convert to string.");

            assert_eq!(paths, expected);
        });

        Ok(())
    }

    #[test]
    fn nu_paths_have_higher_priority_and_new_paths_get_appended_to_the_end(
    ) -> Result<(), ShellError> {
        let mut ctx = Context::basic()?;
        ctx.host = Arc::new(Mutex::new(Box::new(crate::env::host::FakeHost::new())));

        let expected = std::env::join_paths(vec![
            PathBuf::from("/Users/andresrobalino/.volta/bin"),
            PathBuf::from("/Users/mosqueteros/bin"),
            PathBuf::from("/path/to/be/added"),
        ])
        .expect("Couldn't join paths.")
        .into_string()
        .expect("Couldn't convert to string.");

        Playground::setup("syncs_path_test_2", |dirs, sandbox| {
            sandbox.with_files(vec![FileWithContent(
                "configuration.toml",
                r#"
                    path = ["/Users/andresrobalino/.volta/bin", "/Users/mosqueteros/bin"]
                "#,
            )]);

            let mut file = dirs.test().clone();
            file.push("configuration.toml");

            let fake_config = FakeConfig::new(&file);
            let mut actual = EnvironmentSyncer::new();
            actual.set_config(Box::new(fake_config));

            actual.clear_path_var(&mut ctx);

            ctx.with_host(|test_host| {
                test_host.env_set(
                    std::ffi::OsString::from("PATH"),
                    std::env::join_paths(vec![PathBuf::from("/path/to/be/added")])
                        .expect("Couldn't join paths."),
                )
            });

            actual.load_environment();
            actual.sync_path_vars(&mut ctx);

            ctx.with_host(|test_host| {
                let actual = test_host
                    .env_get(std::ffi::OsString::from("PATH"))
                    .expect("Couldn't get PATH var from host.")
                    .into_string()
                    .expect("Couldn't convert to string.");

                assert_eq!(actual, expected);
            });

            let environment = actual.env.lock();

            let paths = std::env::join_paths(
                &environment
                    .path()
                    .expect("No path variable in the environment.")
                    .table_entries()
                    .map(|value| value.as_string().expect("Couldn't convert to string"))
                    .map(PathBuf::from)
                    .collect::<Vec<_>>(),
            )
            .expect("Couldn't join paths.")
            .into_string()
            .expect("Couldn't convert to string.");

            assert_eq!(paths, expected);
        });

        Ok(())
    }
}