nushell/crates/nu-command/src/debug/view_source.rs
JT 4af24363c2
remove let-env, focus on mutating $env (#9574)
# 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: https://github.com/ellie/atuin/pull/1080)
- 
[zoxide](https://github.com/ajeetdsouza/zoxide/blob/main/templates/nushell.txt)
(PR: https://github.com/ajeetdsouza/zoxide/pull/587)
- ✔️
[oh-my-posh](https://github.com/JanDeDobbeleer/oh-my-posh/blob/main/src/shell/scripts/omp.nu)
(pr: https://github.com/JanDeDobbeleer/oh-my-posh/pull/4011)
2023-07-01 07:57:51 +12:00

187 lines
8.3 KiB
Rust

use nu_engine::CallExt;
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, SyntaxShape, Type,
Value,
};
use std::fmt::Write;
#[derive(Clone)]
pub struct ViewSource;
impl Command for ViewSource {
fn name(&self) -> &str {
"view source"
}
fn usage(&self) -> &str {
"View a block, module, or a definition."
}
fn signature(&self) -> nu_protocol::Signature {
Signature::build("view source")
.input_output_types(vec![(Type::Nothing, Type::String)])
.required("item", SyntaxShape::Any, "name or block to view")
.category(Category::Debug)
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let arg: Value = call.req(engine_state, stack, 0)?;
let arg_span = arg.span()?;
match arg {
Value::Block { val: block_id, .. } | Value::Closure { val: block_id, .. } => {
let block = engine_state.get_block(block_id);
if let Some(span) = block.span {
let contents = engine_state.get_span_contents(&span);
Ok(Value::string(String::from_utf8_lossy(contents), call.head)
.into_pipeline_data())
} else {
Ok(Value::string("<internal command>", call.head).into_pipeline_data())
}
}
Value::String { val, .. } => {
if let Some(decl_id) = engine_state.find_decl(val.as_bytes(), &[]) {
// arg is a command
let decl = engine_state.get_decl(decl_id);
let sig = decl.signature();
let vec_of_required = &sig.required_positional;
let vec_of_optional = &sig.optional_positional;
let rest = &sig.rest_positional;
let vec_of_flags = &sig.named;
// gets vector of positionals.
if let Some(block_id) = decl.get_block_id() {
let block = engine_state.get_block(block_id);
if let Some(block_span) = block.span {
let contents = engine_state.get_span_contents(&block_span);
// name of function
let mut final_contents = format!("def {val} [ ");
for n in vec_of_required {
let _ = write!(&mut final_contents, "{}: {} ", n.name, n.shape);
// positional argu,emts
}
for n in vec_of_optional {
let _ = write!(&mut final_contents, "{}?: {} ", n.name, n.shape);
}
for n in vec_of_flags {
// skip adding the help flag
if n.long == "help" {
continue;
}
let _ = write!(&mut final_contents, "--{}", n.long);
if let Some(short) = n.short {
let _ = write!(&mut final_contents, "(-{})", short);
}
if let Some(arg) = &n.arg {
let _ = write!(&mut final_contents, ": {}", arg);
}
final_contents.push(' ');
}
if let Some(rest_arg) = rest {
let _ = write!(
&mut final_contents,
"...{}:{}",
rest_arg.name, rest_arg.shape
);
}
final_contents.push_str("] ");
final_contents.push_str(&String::from_utf8_lossy(contents));
Ok(Value::string(final_contents, call.head).into_pipeline_data())
} else {
Err(ShellError::GenericError(
"Cannot view value".to_string(),
"the command does not have a viewable block".to_string(),
Some(arg_span),
None,
Vec::new(),
))
}
} else {
Err(ShellError::GenericError(
"Cannot view value".to_string(),
"the command does not have a viewable block".to_string(),
Some(arg_span),
None,
Vec::new(),
))
}
} else if let Some(module_id) = engine_state.find_module(val.as_bytes(), &[]) {
// arg is a module
let module = engine_state.get_module(module_id);
if let Some(module_span) = module.span {
let contents = engine_state.get_span_contents(&module_span);
Ok(Value::string(String::from_utf8_lossy(contents), call.head)
.into_pipeline_data())
} else {
Err(ShellError::GenericError(
"Cannot view value".to_string(),
"the module does not have a viewable block".to_string(),
Some(arg_span),
None,
Vec::new(),
))
}
} else {
Err(ShellError::GenericError(
"Cannot view value".to_string(),
"this name does not correspond to a viewable value".to_string(),
Some(arg_span),
None,
Vec::new(),
))
}
}
_ => Err(ShellError::GenericError(
"Cannot view value".to_string(),
"this value cannot be viewed".to_string(),
Some(arg_span),
None,
Vec::new(),
)),
}
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "View the source of a code block",
example: r#"let abc = {|| echo 'hi' }; view source $abc"#,
result: Some(Value::test_string("{|| echo 'hi' }")),
},
Example {
description: "View the source of a custom command",
example: r#"def hi [] { echo 'Hi!' }; view source hi"#,
result: Some(Value::test_string("def hi [] { echo 'Hi!' }")),
},
Example {
description: "View the source of a custom command, which participates in the caller environment",
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",
example: r#"def test [a?:any --b:int ...rest:string] { echo 'test' }; view source test"#,
result: Some(Value::test_string("def test [ a?: any --b: int ...rest: string] { echo 'test' }")),
},
Example {
description: "View the source of a module",
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",
example: r#"alias hello = echo hi; view source hello"#,
result: Some(Value::test_string("echo hi")),
},
]
}
}