Skip to content

Commit

Permalink
remove let-env, focus on mutating $env (#9574)
Browse files Browse the repository at this point in the history
# Description

For years, Nushell has used `let-env` to set a single environment
variable. As our work on scoping continued, we refined what it meant for
a variable to be in scope using `let` but never updated how `let-env`
would work. Instead, `let-env` confusingly created mutations to the
command's copy of `$env`.

So, to help fix the mental model and point people to the right way of
thinking about what changing the environment means, this PR removes
`let-env` to encourage people to think of it as updating the command's
environment variable via mutation.

Before:

```
let-env FOO = "BAR"
```

Now:

```
$env.FOO = "BAR"
```

It's also a good reminder that the environment owned by the command is
in the `$env` variable rather than global like it is in other shells.

# User-Facing Changes

BREAKING CHANGE BREAKING CHANGE

This completely removes `let-env FOO = "BAR"` so that we can focus on
`$env.FOO = "BAR"`.

# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A
clippy::needless_collect -A clippy::result_large_err` to check that
you're using the standard code style
- `cargo test --workspace` to check that all tests pass
- `cargo run -- crates/nu-std/tests/run.nu` to run the tests for the
standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->

# After / Before Submitting
integration scripts to update:
- ✔️
[starship](https://github.com/starship/starship/blob/master/src/init/starship.nu)
- ✔️
[virtualenv](https://github.com/pypa/virtualenv/blob/main/src/virtualenv/activation/nushell/activate.nu)
- ✔️
[atuin](https://github.com/ellie/atuin/blob/main/atuin/src/shell/atuin.nu)
(PR: atuinsh/atuin#1080)
- ❌
[zoxide](https://github.com/ajeetdsouza/zoxide/blob/main/templates/nushell.txt)
(PR: ajeetdsouza/zoxide#587)
- ✔️
[oh-my-posh](https://github.com/JanDeDobbeleer/oh-my-posh/blob/main/src/shell/scripts/omp.nu)
(pr: JanDeDobbeleer/oh-my-posh#4011)
  • Loading branch information
sophiajt committed Jun 30, 2023
1 parent 11132f7 commit 4af2436
Show file tree
Hide file tree
Showing 51 changed files with 372 additions and 403 deletions.
26 changes: 13 additions & 13 deletions .github/workflows/release-pkg.nu
Original file line number Diff line number Diff line change
Expand Up @@ -15,23 +15,23 @@
# unset CARGO_TARGET_DIR if set (I have to do this in the parent shell to get it to work)
# 2. $env:CARGO_TARGET_DIR = ""
# 2. hide-env CARGO_TARGET_DIR
# 3. let-env TARGET = 'x86_64-pc-windows-msvc'
# 4. let-env TARGET_RUSTFLAGS = ''
# 5. let-env GITHUB_WORKSPACE = 'C:\Users\dschroeder\source\repos\forks\nushell'
# 6. let-env GITHUB_OUTPUT = 'C:\Users\dschroeder\source\repos\forks\nushell\output\out.txt'
# 7. let-env OS = 'windows-latest'
# 3. $env.TARGET = 'x86_64-pc-windows-msvc'
# 4. $env.TARGET_RUSTFLAGS = ''
# 5. $env.GITHUB_WORKSPACE = 'C:\Users\dschroeder\source\repos\forks\nushell'
# 6. $env.GITHUB_OUTPUT = 'C:\Users\dschroeder\source\repos\forks\nushell\output\out.txt'
# 7. $env.OS = 'windows-latest'
# make sure 7z.exe is in your path https://www.7-zip.org/download.html
# 8. let-env Path = ($env.Path | append 'c:\apps\7-zip')
# 8. $env.Path = ($env.Path | append 'c:\apps\7-zip')
# make sure aria2c.exe is in your path https://github.com/aria2/aria2
# 9. let-env Path = ($env.Path | append 'c:\path\to\aria2c')
# 9. $env.Path = ($env.Path | append 'c:\path\to\aria2c')
# make sure you have the wixtools installed https://wixtoolset.org/
# 10. let-env Path = ($env.Path | append 'C:\Users\dschroeder\AppData\Local\tauri\WixTools')
# 10. $env.Path = ($env.Path | append 'C:\Users\dschroeder\AppData\Local\tauri\WixTools')
# You need to run the release-pkg twice. The first pass, with _EXTRA_ as 'bin', makes the output
# folder and builds everything. The second pass, that generates the msi file, with _EXTRA_ as 'msi'
# 11. let-env _EXTRA_ = 'bin'
# 11. $env._EXTRA_ = 'bin'
# 12. source .github\workflows\release-pkg.nu
# 13. cd ..
# 14. let-env _EXTRA_ = 'msi'
# 14. $env._EXTRA_ = 'msi'
# 15. source .github\workflows\release-pkg.nu
# After msi is generated, you have to update winget-pkgs repo, you'll need to patch the release
# by deleting the existing msi and uploading this new msi. Then you'll need to update the hash
Expand Down Expand Up @@ -73,17 +73,17 @@ if $os in [$USE_UBUNTU, 'macos-latest'] {
match $target {
'aarch64-unknown-linux-gnu' => {
sudo apt-get install gcc-aarch64-linux-gnu -y
let-env CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER = 'aarch64-linux-gnu-gcc'
$env.CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER = 'aarch64-linux-gnu-gcc'
cargo-build-nu $flags
}
'riscv64gc-unknown-linux-gnu' => {
sudo apt-get install gcc-riscv64-linux-gnu -y
let-env CARGO_TARGET_RISCV64GC_UNKNOWN_LINUX_GNU_LINKER = 'riscv64-linux-gnu-gcc'
$env.CARGO_TARGET_RISCV64GC_UNKNOWN_LINUX_GNU_LINKER = 'riscv64-linux-gnu-gcc'
cargo-build-nu $flags
}
'armv7-unknown-linux-gnueabihf' => {
sudo apt-get install pkg-config gcc-arm-linux-gnueabihf -y
let-env CARGO_TARGET_ARMV7_UNKNOWN_LINUX_GNUEABIHF_LINKER = 'arm-linux-gnueabihf-gcc'
$env.CARGO_TARGET_ARMV7_UNKNOWN_LINUX_GNUEABIHF_LINKER = 'arm-linux-gnueabihf-gcc'
cargo-build-nu $flags
}
_ => {
Expand Down
2 changes: 1 addition & 1 deletion crates/nu-cmd-lang/src/core_commands/def_env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ impl Command for DefEnv {
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Set environment variable by call a custom command",
example: r#"def-env foo [] { let-env BAR = "BAZ" }; foo; $env.BAR"#,
example: r#"def-env foo [] { $env.BAR = "BAZ" }; foo; $env.BAR"#,
result: Some(Value::test_string("BAZ")),
}]
}
Expand Down
2 changes: 1 addition & 1 deletion crates/nu-cmd-lang/src/core_commands/export_def_env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export def-env cd_with_fallback [arg = ""] {
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Define a custom command that participates in the environment in a module and call it",
example: r#"module foo { export def-env bar [] { let-env FOO_BAR = "BAZ" } }; use foo bar; bar; $env.FOO_BAR"#,
example: r#"module foo { export def-env bar [] { $env.FOO_BAR = "BAZ" } }; use foo bar; bar; $env.FOO_BAR"#,
result: Some(Value::test_string("BAZ")),
}]
}
Expand Down
2 changes: 1 addition & 1 deletion crates/nu-cmd-lang/src/core_commands/hide_env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ impl Command for HideEnv {
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Hide an environment variable",
example: r#"let-env HZ_ENV_ABC = 1; hide-env HZ_ENV_ABC; 'HZ_ENV_ABC' in (env).name"#,
example: r#"$env.HZ_ENV_ABC = 1; hide-env HZ_ENV_ABC; 'HZ_ENV_ABC' in (env).name"#,
result: Some(Value::test_bool(false)),
}]
}
Expand Down
4 changes: 2 additions & 2 deletions crates/nu-cmd-lang/src/core_commands/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,12 @@ impl Command for Module {
},
Example {
description: "Define an environment variable in a module",
example: r#"module foo { export-env { let-env FOO = "BAZ" } }; use foo; $env.FOO"#,
example: r#"module foo { export-env { $env.FOO = "BAZ" } }; use foo; $env.FOO"#,
result: Some(Value::test_string("BAZ")),
},
Example {
description: "Define a custom command that participates in the environment in a module and call it",
example: r#"module foo { export def-env bar [] { let-env FOO_BAR = "BAZ" } }; use foo bar; bar; $env.FOO_BAR"#,
example: r#"module foo { export def-env bar [] { $env.FOO_BAR = "BAZ" } }; use foo bar; bar; $env.FOO_BAR"#,
result: Some(Value::test_string("BAZ")),
},
]
Expand Down
2 changes: 1 addition & 1 deletion crates/nu-cmd-lang/src/core_commands/overlay/hide.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ impl Command for OverlayHide {
},
Example {
description: "Hide the last activated overlay",
example: r#"module spam { export-env { let-env FOO = "foo" } }
example: r#"module spam { export-env { $env.FOO = "foo" } }
overlay use spam
overlay hide"#,
result: None,
Expand Down
2 changes: 1 addition & 1 deletion crates/nu-cmd-lang/src/core_commands/overlay/use_.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ impl Command for OverlayUse {
},
Example {
description: "Create an overlay from a file",
example: r#"'export-env { let-env FOO = "foo" }' | save spam.nu
example: r#"'export-env { $env.FOO = "foo" }' | save spam.nu
overlay use spam.nu
$env.FOO"#,
result: None,
Expand Down
4 changes: 2 additions & 2 deletions crates/nu-color-config/src/style_computer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ fn test_computable_style_closure_basic() {
use nu_test_support::{nu, nu_repl_code, playground::Playground};
Playground::setup("computable_style_closure_basic", |dirs, _| {
let inp = [
r#"let-env config = {
r#"$env.config = {
color_config: {
string: {|e| touch ($e + '.obj'); 'red' }
}
Expand All @@ -256,7 +256,7 @@ fn test_computable_style_closure_basic() {
fn test_computable_style_closure_errors() {
use nu_test_support::{nu, nu_repl_code};
let inp = [
r#"let-env config = {
r#"$env.config = {
color_config: {
string: {|e| $e + 2 }
}
Expand Down
8 changes: 4 additions & 4 deletions crates/nu-command/src/debug/view_source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,8 +163,8 @@ impl Command for ViewSource {
},
Example {
description: "View the source of a custom command, which participates in the caller environment",
example: r#"def-env foo [] { let-env BAR = 'BAZ' }; view source foo"#,
result: Some(Value::test_string("def foo [] { let-env BAR = 'BAZ' }")),
example: r#"def-env foo [] { $env.BAR = 'BAZ' }; view source foo"#,
result: Some(Value::test_string("def foo [] { $env.BAR = 'BAZ' }")),
},
Example {
description: "View the source of a custom command with flags and arguments",
Expand All @@ -173,8 +173,8 @@ impl Command for ViewSource {
},
Example {
description: "View the source of a module",
example: r#"module mod-foo { export-env { let-env FOO_ENV = 'BAZ' } }; view source mod-foo"#,
result: Some(Value::test_string(" export-env { let-env FOO_ENV = 'BAZ' }")),
example: r#"module mod-foo { export-env { $env.FOO_ENV = 'BAZ' } }; view source mod-foo"#,
result: Some(Value::test_string(" export-env { $env.FOO_ENV = 'BAZ' }")),
},
Example {
description: "View the source of an alias",
Expand Down
2 changes: 1 addition & 1 deletion crates/nu-command/src/default_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -315,8 +315,8 @@ pub fn add_shell_command_context(mut engine_state: EngineState) -> EngineState {

// Env
bind_command! {
LetEnvDeprecated,
ExportEnv,
LetEnv,
LoadEnv,
SourceEnv,
WithEnv,
Expand Down
43 changes: 43 additions & 0 deletions crates/nu-command/src/deprecated/let_env.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{Category, PipelineData, ShellError, Signature, SyntaxShape, Type};

#[derive(Clone)]
pub struct LetEnvDeprecated;

impl Command for LetEnvDeprecated {
fn name(&self) -> &str {
"let-env"
}

fn signature(&self) -> Signature {
Signature::build(self.name())
.input_output_types(vec![(Type::Nothing, Type::Nothing)])
.allow_variants_without_examples(true)
.required("var_name", SyntaxShape::String, "variable name")
.required(
"initial_value",
SyntaxShape::Keyword(b"=".to_vec(), Box::new(SyntaxShape::MathExpression)),
"equals sign followed by value",
)
.category(Category::Deprecated)
}

fn usage(&self) -> &str {
"`let-env FOO = ...` is deprecated, use `$env.FOO = ...` instead."
}

fn run(
&self,
_: &EngineState,
_: &mut Stack,
call: &Call,
_: PipelineData,
) -> Result<PipelineData, ShellError> {
Err(nu_protocol::ShellError::DeprecatedCommand(
self.name().to_string(),
"$nu.<environment variable> = ...".to_owned(),
call.head,
))
}
}
2 changes: 2 additions & 0 deletions crates/nu-command/src/deprecated/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
mod collect;
mod deprecated_commands;
mod hash_base64;
mod let_env;
mod lpad;
mod math_eval;
mod rpad;
Expand All @@ -12,6 +13,7 @@ mod str_int;
pub use collect::StrCollectDeprecated;
pub use deprecated_commands::*;
pub use hash_base64::HashBase64;
pub use let_env::LetEnvDeprecated;
pub use lpad::LPadDeprecated;
pub use math_eval::SubCommand as MathEvalDeprecated;
pub use rpad::RPadDeprecated;
Expand Down
4 changes: 2 additions & 2 deletions crates/nu-command/src/env/export_env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,14 +57,14 @@ impl Command for ExportEnv {
vec![
Example {
description: "Set an environment variable",
example: r#"export-env { let-env SPAM = 'eggs' }"#,
example: r#"export-env { $env.SPAM = 'eggs' }"#,
result: Some(Value::Nothing {
span: Span::test_data(),
}),
},
Example {
description: "Set an environment variable and examine its value",
example: r#"export-env { let-env SPAM = 'eggs' }; $env.SPAM"#,
example: r#"export-env { $env.SPAM = 'eggs' }; $env.SPAM"#,
result: Some(Value::test_string("eggs")),
},
]
Expand Down
72 changes: 0 additions & 72 deletions crates/nu-command/src/env/let_env.rs

This file was deleted.

2 changes: 0 additions & 2 deletions crates/nu-command/src/env/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
mod config;
mod export_env;
mod let_env;
mod load_env;
mod source_env;
mod with_env;
Expand All @@ -10,7 +9,6 @@ pub use config::ConfigMeta;
pub use config::ConfigNu;
pub use config::ConfigReset;
pub use export_env::ExportEnv;
pub use let_env::LetEnv;
pub use load_env::LoadEnv;
pub use source_env::SourceEnv;
pub use with_env::WithEnv;
7 changes: 3 additions & 4 deletions crates/nu-command/src/example_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ pub fn test_examples(cmd: impl Command + 'static) {
#[cfg(test)]
mod test_examples {
use super::super::{
Ansi, Date, Enumerate, Flatten, From, Get, Into, IntoString, LetEnv, Math, MathEuler,
MathPi, MathRound, ParEach, Path, PathParse, Random, Sort, SortBy, Split, SplitColumn,
SplitRow, Str, StrJoin, StrLength, StrReplace, Update, Url, Values, Wrap,
Ansi, Date, Enumerate, Flatten, From, Get, Into, IntoString, Math, MathEuler, MathPi,
MathRound, ParEach, Path, PathParse, Random, Sort, SortBy, Split, SplitColumn, SplitRow,
Str, StrJoin, StrLength, StrReplace, Update, Url, Values, Wrap,
};
use crate::{Each, To};
use nu_cmd_lang::example_support::{
Expand Down Expand Up @@ -78,7 +78,6 @@ mod test_examples {
working_set.add_decl(Box::new(Into));
working_set.add_decl(Box::new(IntoString));
working_set.add_decl(Box::new(Let));
working_set.add_decl(Box::new(LetEnv));
working_set.add_decl(Box::new(Math));
working_set.add_decl(Box::new(MathEuler));
working_set.add_decl(Box::new(MathPi));
Expand Down
6 changes: 3 additions & 3 deletions crates/nu-command/tests/commands/nu_check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ fn parse_module_success_2() {
r#"
# foo.nu
export-env { let-env MYNAME = "Arthur, King of the Britons" }
export-env { $env.MYNAME = "Arthur, King of the Britons" }
"#,
)]);

Expand Down Expand Up @@ -749,7 +749,7 @@ fn parse_script_with_nested_scripts_success() {
.with_files(vec![FileWithContentToBeTrimmed(
"foo.nu",
r#"
let-env FOO = 'foo'
$env.FOO = 'foo'
"#,
)]);

Expand All @@ -772,7 +772,7 @@ fn nu_check_respects_file_pwd() {
.with_files(vec![FileWithContentToBeTrimmed(
"lol/lol.nu",
r#"
let-env RETURN = (nu-check ../foo.nu)
$env.RETURN = (nu-check ../foo.nu)
"#,
)])
.with_files(vec![FileWithContentToBeTrimmed(
Expand Down
2 changes: 1 addition & 1 deletion crates/nu-command/tests/commands/redirection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ fn same_target_redirection_with_too_much_stderr_not_hang_nushell() {
nu!(
cwd: dirs.test(), pipeline(
r#"
let-env LARGE = (open --raw a_large_file.txt);
$env.LARGE = (open --raw a_large_file.txt);
nu --testbin echo_env_stderr LARGE out+err> another_large_file.txt
"#
),
Expand Down
2 changes: 1 addition & 1 deletion crates/nu-command/tests/commands/rm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ fn errors_if_attempting_to_delete_home() {
Playground::setup("rm_test_8", |dirs, _| {
let actual = nu!(
cwd: dirs.root(),
"let-env HOME = myhome ; rm -rf ~"
"$env.HOME = myhome ; rm -rf ~"
);

assert!(actual.err.contains("please use -I or -i"));
Expand Down

0 comments on commit 4af2436

Please sign in to comment.