## Description
On unix, importing a module that imports one of its parents back through
a `..` path never
terminates and nushell dies with a segfault instead of reporting a
circular import (#18731):
```nu
mkdir /tmp/nucrash/c/i
"export module i" | save /tmp/nucrash/c/mod.nu
"use ../mod.nu" | save /tmp/nucrash/c/i/mod.nu
nu -c "use /tmp/nucrash/c"
# Segmentation fault (core dumped)
```
The parser builds these paths with `std::path::absolute`, which drops
`.` components but keeps
`..` on unix, because a `..` component is not the same thing as the
parent directory once
symlinks are in play. `FileStack`, which is what detects circular
imports, compared those paths
as they were, so `/tmp/nucrash/c/mod.nu` and
`/tmp/nucrash/c/i/../mod.nu` looked like two
different files. Each trip around the cycle appended another `/i/..` to
the path, so the import
never repeated itself, the check never fired, and the parser recursed
until the stack ran out.
That also explains why the symptom is not the same everywhere. Whether
you get a crash depends
on which limit the growing path hits first: on macOS the path stops
resolving before the stack
runs out, so it surfaces as a `module_not_found` naming a path with
several hundred `../i`
components in it, as @pickx saw on the issue. Windows was already fine,
because
`std::path::absolute` resolves `..` there, so the same repro reports
`nu::parser::circular_import`
today. This makes the other platforms behave that way too.
Files on the stack are now identified by their canonical path, which
resolves `..` along with
symlinks pointing at a file that is already being parsed. The path a
file was actually reached
by is kept as it was, since that is what error messages show and what
the files it imports are
resolved against, so nothing else changes. Paths with no file behind
them, such as the virtual
paths of the standard library, fall back to expanding `.` and `..`
textually.
Legitimate `..` imports are unaffected: a module importing a sibling
through `../other/mod.nu`
still resolves and is not reported as circular
(`module_nested_imports_in_dirs` covers this).
Tested on Linux, where the repro now prints a circular import error and
exits 1 instead of
dying on SIGSEGV, and on Windows, where behavior is unchanged. The new
regression test fails
on Linux without the fix and passes with it.
## User-facing changes (Release notes)
Fixed a crash when importing a module that imports one of its parents
back through a `..` path,
for example a `c/i/mod.nu` containing `use ../mod.nu`. Nushell reported
a circular import on
Windows but crashed on other platforms, and now reports the circular
import everywhere.
## Additional notes
fixes#18731
## Description
This PR replaces all the `Playground::setup` calls with the new injected
`Playground`.
Most of the changes are done via [this
script](https://tangled.org/cptpiepmatz.de/nushell_playground_asr) which
uses the rust-analyzer internals to replace code via the AST.
All the test should behave exactly the same as before but they don't
need to manually set up a playground anymore. Also this removes quite a
lot of lines, which is nice.
## User-facing changes (Release notes)
n/a
---
<sub>Stack created with <a
href="https://github.com/github/gh-stack">GitHub Stacks CLI</a> • <a
href="https://gh.io/stacks-feedback">Give Feedback 💬</a></sub>
## Description
Working on a module at the prompt had a few traps, raised on #10995.
`use spam` and `overlay use spam` kept the loaded copy after the file
changed, while `use spam.nu` read it again. Directory modules had it
worst, because `use pkg` read the disk the first time and memory every
time after. By-name imports now read the file again when it, or anything
it imports, changed. With an unchanged file, or a module written at the
prompt, they behave as before.
Reloading also left old definitions behind. A command deleted from the
file kept working through `use`, `hide`, `overlay use --reload` and
`overlay hide` followed by `overlay use`, and a name you didn't import
again kept running the old code. A reload now hides what the new version
no longer exports, and moves every name still showing the old version to
the new one. A command you defined yourself with the same name stays,
and so does one you imported directly from a module this one used to
re-export.
`hide spam` after `use spam.nu *` silently did nothing, and now hides
the module's commands however they were imported.
Changing overlays moved you. `overlay hide` went back to the directory
you activated the overlay from, and bringing a hidden overlay back with
`overlay use <name>` or `overlay new` went to the directory it was
hidden in. `PWD` and `OLDPWD` now stay put unless the module's
`export-env` changes directory.
The first change could have sent more people into an existing trap. An
unclosed delimiter in a file that `use` or `source` loads left the REPL
at the `:::` prompt with nothing you could type to finish the line. The
validator now counts only errors in the line itself as unfinished input.
## User-facing changes (Release notes)
- `use <name>` and `overlay use <name>` now read the module's file again
if it changed, the same as `use <path>`.
- Reloading a module now removes commands, aliases, type aliases,
constants and submodules that were deleted from its file, and moves
names you imported earlier to the new version.
- `hide <module>` now hides a module's commands after `use <module> *`,
as well as after `use <module>`.
- Fixed the REPL getting stuck at the `:::` prompt when `use` or
`source` loaded a file with an unclosed delimiter. You now see the
error.
### Breaking changes
- `overlay hide`, `overlay use` and `overlay new` no longer change the
current directory, unless the module's `export-env` does. `--keep-env
[PWD]` still works but is no longer needed. A script that used a
temporary overlay as a scoped `cd` has to `cd` back itself.
- `use <name>` and `overlay use <name>` now report parse errors in the
module's file, where they used to keep the loaded copy. A hook that runs
`use toolkit` on every `cd` shows them until the file is fixed.
## Additional notes
Related to #10995.
This reverses two choices that existing tests had recorded. #13170 said
`use voice` "will still use the module which is saved in EngineState",
so one assertion in `use_submodules` flipped. Four tests asserted that
changing overlays moves you, so they're renamed with the new expected
value: `overlay_hide_in_export_env_keeps_cd`,
`use_overlay_hide_keeps_cd`, `source_env_overlay_hide_keeps_cd` and
`overlay_reactivate_with_module_name_keeps_pwd`.
By-name imports only check modules from an earlier source unit, so
loading a module tree reads no extra files. Loading a 120-module `export
module x.nu; export use x` tree takes 57.7 ms before and 58.2 ms after
on a debug build. Loading that tree and then running a by-name `use` of
it in a later source unit, which reads its 120 files, takes 77.1 ms
before and 80.6 ms after.
Only a reload removes a module's name. `hide <module>` keeps it on
purpose, so `hide spam; use spam` still works.
## Description
When a module is a directory with a `mod.nu` inside, its name was taken
with `file_stem()`, which treats everything after the last dot as an
extension. So a directory called `a.b` became a module called `a`.
```nushell
mkdir a.b
'export def foo [] { "foo" }' | save a.b/mod.nu
use a.b
scope modules | where name =~ '^a' | get name
# [a]
a.b foo
# error, the command is `a foo`
```
Directories don't have an extension to strip, so now the module name is
the full directory name. `use a.b` gives a module `a.b` and `a.b foo`
works. File modules like `spam.nu` still drop the `.nu` like before.
This also means `a` and `a.b` directories no longer clash.
Added `module_dir_name_keeps_dots` in `tests/modules/mod.rs`. It fails
on main and passes with the fix.
## User-facing changes (Release notes)
Breaking change. Module directories with a dot in their name now keep
the full name. `use a.b` creates module `a.b` (commands like `a.b foo`)
where it used to create `a` (`a foo`). The same goes for overlays, so
`overlay use a.b` now gives overlay `a.b`. A directory named `foo.nu/`
is now `foo.nu` instead of `foo`. Scripts that call these commands by
the short name need updating.
## Additional notes
Fixes#16311
Check each module once when deciding whether to reload a cached module
## Description
When a module that has already been parsed is imported again,
`parse_module_file` calls `module_needs_reloading` to check whether any
file in the module's tree has changed on disk. That walk recurses
through `submodules` and `imported_modules` without tracking which
modules it has visited, so a module reachable through several paths is
re-read once per *path*.
That's common in practice: a `mod.nu` that `export use`s its sibling
files, where most siblings also `use` a few shared helpers. In the repro
from the issue, every extra `use nested` of a 9-file module re-reads its
files ~133 times; with a real 22-file library it's ~412 reads per
import. Linux mostly hides this because file opens are cheap, but on
Windows it dominates parse time, and the LSP pays it on every keystroke.
This PR adds a `seen` set for the duration of the walk, so each
reachable module's file is read at most once per check. Skipping an
already-seen module is safe: `any()` short-circuits on the first change,
so a module seen again has already been found unchanged. I also
extracted the read-and-compare into a separate `module_file_changed`
function.
Measured on Windows with the repro script from the issue (`nu -n
repro.nu`):
| importers | before | after |
| --------: | -----: | ----: |
| 1 | 34.9 ms | 28.4 ms |
| 2 | 51.2 ms | 29.2 ms |
| 5 | 97.5 ms | 32.4 ms |
| 10 | 179.0 ms | 38.3 ms |
Per extra importer: **16.0 ms → 1.1 ms**. In my real-world case (a
13-file module importing a 22-file library from most of its files),
parsing on Windows went from ~3.1 s to the point where the LSP is
responsive again.
## User-facing changes (Release notes)
Improved performance when the same module is imported from many places.
Nushell no longer re-reads a module's files once for every import path
when checking whether a cached module has changed. This especially
speeds up parsing and the language server on Windows for libraries whose
files import each other.
## Additional notes
- fixes#19226
- `cargo test -p nu-parser` and `cargo test --test tests -- modules::`
pass; the second runs the module reload tests, including the new
`reload_module_reached_through_several_imports`.
- Behaviour is unchanged: a modified file anywhere in the tree still
triggers a reload. Only repeat visits of the same module within one
check are skipped.
<!--
Thanks for contributing to Nushell!
Before submitting, please read the contributing guide:
https://github.com/nushell/nushell/blob/main/CONTRIBUTING.md
This template helps reviewers understand your changes and allows us to
generate high-quality release notes.
-->
## Description
<!--
Explain what this PR does and why.
This section is intentionally flexible:
- Describe the problem
- Explain your approach
- Include technical details if relevant
Good examples:
- "In this PR, I fixed..."
- "In this PR, I added support for..."
- "This change improves X by..."
Write as much or as little as needed for reviewers to understand your
changes.
-->
This PR updates the tests for modules.
## User-facing changes (Release notes)
<!--
This section is used (mostly as-is) for https://www.nushell.sh/blog/
Describe how Nushell behavior changes from a user's perspective.
Do NOT describe internal Rust changes here.
Write in a release note style, for example:
- "Added support for..."
- "Fixed an issue where..."
- "Nushell now supports..."
- "Improved performance of..."
If your changes do NOT affect users (internal refactors, cleanup, etc.),
just write:
- "n/a"
- "nan"
- or similar
This tells us the change should not appear in the changelog.
Tips:
- Focus on observable behavior
- Include examples if helpful
- Keep it concise
You can:
- Write a short paragraph (will appear as a bullet point), OR
- Use headings (###) if your change needs more structure
Avoid writing things like:
- "In this PR, I refactored..."
- "This updates internal code..."
You may leave this blank until the PR is ready.
-->
n/a
---
<sub>Stack created with <a
href="https://github.com/github/gh-stack">GitHub Stacks CLI</a> • <a
href="https://gh.io/stacks-feedback">Give Feedback 💬</a></sub>
## Description
Currently, importing a module also imports its exported sub-modules.
```nushell
use std/dirs
dirs_ # completion triggered
# => dirs
# => dirs add
# => dirs drop
# => dirs goto
# => dirs next
# => dirs prev
# => dirs shells-aliases dexit
# => dirs shells-aliases enter
# => dirs shells-aliases g
# => dirs shells-aliases n
# => dirs shells-aliases p
# => dirs shells-aliases shells
```
This is unexpected (and really annoying).
Also, while it imports the sub-module's definitions, it does not run the
sub-module's `export-env` block.
With this PR:
```nushell
use std/dirs
dirs_ # completion triggered
# => dirs
# => dirs add
# => dirs drop
# => dirs goto
# => dirs next
# => dirs prev
```
To use the aliases, one just needs to `use std/dirs shells-aliases *`
## User-facing changes (Release notes)
Importing a module no longer implicitly imports its exported
sub-modules.
```nushell
export module foo {
export def bar [] {}
export module sub {
export def baz [] {}
}
}
use foo
foo bar # valid
foo sub baz # invalid, `sub` is not implicitly imported
```
To have your modules keep the old behavior, you will need to export the
modules contents explicitly:
```nushell
export module foo {
export def bar [] {}
export module sub {
export def baz [] {}
}
export use sub
}
use foo
foo bar # valid
foo sub baz # valid
```
> [!NOTE]
> `use`ing a module inside another module does *not* run the imported
module's `export-env` block.
> (See [`export-env` runs only when the use call is
evaluated](https://www.nushell.sh/book/modules/creating_modules.html#export-env-runs-only-when-the-use-call-is-evaluated))
> Thus, explicit `use`s as recommended above will not run `export-env`
blocks, which is inline with how the previous implicit imports worked.
<!--
Thank you for improving Nushell!
Please, read our contributing guide:
https://github.com/nushell/nushell/blob/main/CONTRIBUTING.md
-->
This PR enables the clippy lint `needless_raw_strings` to avoid raw
strings where they aren't needed. We have a lot of them and I don't
think that's that nice tbh.
## Release notes summary - What our users need to know
<!--
This section will be included as part of our release notes. See the
contributing guide for more details.
Please include only details relevant for users here. Motivation and
technical details can be added above or below this section.
You may leave this section blank until your PR is finalized. Ask a core
team member if you need help filling this section.
-->
n/a
Fixes#13776
# User-Facing Changes
Arguments to aliased externals no longer include nested import paths:
```diff
module foo { export alias bar = ^echo }
use foo
foo bar baz
-bar baz
+baz
```
# Description
Fixes: https://github.com/nushell/nushell/issues/12099
Currently if user run `use voice.nu`, and file is unchanged, then run
`use voice.nu` again. nushell will use the module directly, even if
submodule inside `voice.nu` is changed.
After discussed with @kubouch, I think it's ok to re-parse the module
file when:
1. It exports sub modules which are defined by a file
2. It uses other modules which are defined by a file
## About the change:
To achieve the behavior, we need to add 2 attributes to `Module`:
1. `imported_modules`: it tracks the other modules is imported by the
givem `module`, e.g: `use foo.nu`
2. `file`: the path of a module, if a module is defined by a file, it
will be `Some(path)`, or else it will be `None`.
After the change:
use voice.nu always read the file and parse it.
use voice will still use the module which is saved in EngineState.
# User-Facing Changes
use `xxx.nu` will read the file and parse it if it exports submodules or
uses submodules
# Tests + Formatting
Done
---------
Co-authored-by: Jakub Žádník <kubouch@gmail.com>
# Description
Judiciously try to avoid allocations/clone by changing the signature of
functions
- **Don't pass str by value unnecessarily if only read**
- **Don't require a vec in `Sandbox::with_files`**
- **Remove unnecessary string clone**
- **Fixup unnecessary borrow**
- **Use `&str` in shape color instead**
- **Vec -> Slice**
- **Elide string clone**
- **Elide `Path` clone**
- **Take &str to elide clone in tests**
# User-Facing Changes
None
# Tests + Formatting
This touches many tests purely in changing from owned to borrowed/static
data
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx
you can also mention related issues, PRs or discussions!
-->
Closes#11561
# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.
Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->
This PR will allow string interpolation at parse time.
Since the actual config hasn't been loaded at parse time, this uses the
`get_config()` method on `StateWorkingSet`. So file sizes and datetimes
(I think those are the only things whose string representations depend
on the config) may be formatted differently from how users have
configured things, which may come as a surprise to some. It does seem
unlikely that anyone would be formatting file sizes or date times at
parse time. Still, something to think about if/before this PR merged.
Also, I changed the `ModuleNotFound` error to include the name of the
module.
# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->
Users will be able to do stuff like:
```nu
const x = [1 2 3]
const y = $"foo($x)" // foo[1, 2, 3]
```
The main use case is `use`-ing and `source`-ing files at parse time:
```nu
const file = "foo.nu"
use $"($file)"
```
If the module isn't found, you'll see an error like this:
```
Error: nu::parser::module_not_found
× Module not found.
╭─[entry #3:1:1]
1 │ use $"($file)"
· ─────┬────
· ╰── module foo.nu not found
╰────
help: module files and their paths must be available before your script is run as parsing occurs before anything is evaluated
```
# 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` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use std testing; testing run-tests --path
crates/nu-std"` 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 Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
Although there's user-facing changes, there's probably no need to change
the docs since people probably already expect string interpolation to
work at parse time.
Edit: @kubouch pointed out that we'd need to document the fact that
stuff like file sizes and datetimes won't get formatted according to
user's runtime configs, so I'll make a PR to nushell.github.io after
this one
should
- close https://github.com/nushell/nushell/issues/11133
# Description
to allow more freedom when writing complex modules, we are disabling the
auto-export of director modules.
the change was as simple as removing the crawling of files and modules
next to any `mod.nu` and update the standard library.
# User-Facing Changes
users will have to explicitely use `export module <mod>` to define
submodules and `export use <mod> <cmd>` to re-export definitions, e.g.
```nushell
# my-module/mod.nu
export module foo.nu # export a submodule
export use bar.nu bar-1 # re-export an internal command
export def top [] {
print "`top` from `mod.nu`"
}
```
```nushell
# my-module/foo.nu
export def "foo-1" [] {
print "`foo-1` from `lib/foo.nu`"
}
export def "foo-2" [] {
print "`foo-2` from `lib/foo.nu`"
}
```
```nushell
# my-module/bar.nu
export def "bar-1" [] {
print "`bar-1` from `lib/bar.nu`"
}
```
# Tests + Formatting
i had to add `export module` calls in the `tests/modules/samples/spam`
directory module and allow the `not_allowed` module to not give an
error, it is just empty, which is fine.
# After Submitting
- mention in the release note
- update the following repos
```
#┬─────name─────┬version┬─type─┬─────────repo─────────
0│nu-git-manager│0.4.0 │module│amtoine/nu-git-manager
1│nu-scripts │0.1.0 │module│amtoine/scripts
2│nu-zellij │0.1.0 │module│amtoine/zellij-layouts
3│nu-scripts │0.1.0 │module│nushell/nu_scripts
4│nupm │0.1.0 │module│nushell/nupm
─┴──────────────┴───────┴──────┴──────────────────────
```
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx
you can also mention related issues, PRs or discussions!
-->
# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.
Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->
https://github.com/nushell/nushell/pull/9773 introduced constants to
modules and allowed to export them, but only within one level. This PR:
* allows recursive exporting of constants from all submodules
* fixes submodule imports in a list import pattern
* makes sure exported constants are actual constants
Should unblock https://github.com/nushell/nushell/pull/9678
### Example:
```nushell
module spam {
export module eggs {
export module bacon {
export const viking = 'eats'
}
}
}
use spam
print $spam.eggs.bacon.viking # prints 'eats'
use spam [eggs]
print $eggs.bacon.viking # prints 'eats'
use spam eggs bacon viking
print $viking # prints 'eats'
```
### Limitation 1:
Considering the above `spam` module, attempting to get `eggs bacon` from
`spam` module doesn't work directly:
```nushell
use spam [ eggs bacon ] # attempts to load `eggs`, then `bacon`
use spam [ "eggs bacon" ] # obviously wrong name for a constant, but doesn't work also for commands
```
Workaround (for example):
```nushell
use spam eggs
use eggs [ bacon ]
print $bacon.viking # prints 'eats'
```
I'm thinking I'll just leave it in, as you can easily work around this.
It is also a limitation of the import pattern in general, not just
constants.
### Limitation 2:
`overlay use` successfully imports the constants, but `overlay hide`
does not hide them, even though it seems to hide normal variables
successfully. This needs more investigation.
# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->
Allows recursive constant exports from submodules.
# 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 -- -c "use std testing; testing run-tests --path
crates/nu-std"` 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 Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx
you can also mention related issues, PRs or discussions!
-->
# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.
Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->
This PR cleans up tests in the `tests/` directory by removing
unnecessary code.
Part of #8670.
- [x] const_/mod.rs
- [x] eval/mod.rs
- [x] hooks/mod.rs
- [x] modules/mod.rs
- [x] overlays/mod.rs
- [x] parsing/mod.rs
- [x] scope/mod.rs
- [x] shell/environment/env.rs
- [x] shell/environment/nu_env.rs
- [x] shell/mod.rs
- [x] shell/pipeline/commands/external.rs
- [x] shell/pipeline/commands/internal.rs
- [x] shell/pipeline/mod.rs
# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->
# 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 Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
# 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)
# Description
This PR is just a minor development improvement. While working on
another feature, I noticed that the root crate lists the super useful
`pretty_assertions` in the root crate but doesn't use it in most tests.
With this change `pretty_assertions::assert_eq!` is used instead of
`core::assert_eq!` for better diffs when debugging the tests.
I thought of adding the dependency to other crates but I decided not to
since I didn't want a huge disruptive PR :)
# Description
This PR adds an alternative alias implementation. Old aliases still work
but you need to use `old-alias` instead of `alias`.
Instead of replacing spans in the original code and re-parsing, which
proved to be extremely error-prone and a constant source of panics, the
new implementation creates a new command that references the old
command. Consider the new alias defined as `alias ll = ls -l`. The
parser creates a new command called `ll` and remembers that it is
actually a `ls` command called with the `-l` flag. Then, when the parser
sees the `ll` command, it will translate it to `ls -l` and passes to it
any parameters that were passed to the call to `ll`. It works quite
similar to how known externals defined with `extern` are implemented.
The new alias implementation should work the same way as the old
aliases, including exporting from modules, referencing both known and
unknown externals. It seems to preserve custom completions and pipeline
metadata. It is quite robust in most cases but there are some rough
edges (see later).
Fixes https://github.com/nushell/nushell/issues/7648,
https://github.com/nushell/nushell/issues/8026,
https://github.com/nushell/nushell/issues/7512,
https://github.com/nushell/nushell/issues/5780,
https://github.com/nushell/nushell/issues/7754
No effect: https://github.com/nushell/nushell/issues/8122 (we might
revisit the completions code after this PR)
Should use custom command instead:
https://github.com/nushell/nushell/issues/6048
# User-Facing Changes
Since aliases are now basically commands, it has some new implications:
1. `alias spam = "spam"` (requires command call)
* **workaround**: use `alias spam = echo "spam"`
2. `def foo [] { 'foo' }; alias foo = ls -l` (foo defined more than
once)
* **workaround**: use different name (commands also have this
limitation)
4. `alias ls = (ls | sort-by type name -i)`
* **workaround**: Use custom command. _The common issue with this is
that it is currently not easy to pass flags through custom commands and
command referencing itself will lead to stack overflow. Both of these
issues are meant to be addressed._
5. TODO: Help messages, `which` command, `$nu.scope.aliases`, etc.
* Should we treat the aliases as commands or should they be separated
from regular commands?
6. Needs better error message and syntax highlight for recursed alias
(`alias f = f`)
7. Can't create alias with the same name as existing command (`alias ls
= ls -a`)
* Might be possible to add support for it (not 100% sure)
8. Standalone `alias` doesn't list aliases anymore
9. Can't alias parser keywords (e.g., stuff like `alias ou = overlay
use` won't work)
* TODO: Needs a better error message when attempting to do so
# 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` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass
# After Submitting
If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
* start working on source-env
* WIP
* Get most tests working, still one to go
* Fix file-relative paths; Report parser error
* Fix merge conflicts; Restore source as deprecated
* Tests: Use source-env; Remove redundant tests
* Fmt
* Respect hidden env vars
* Fix file-relative eval for source-env
* Add file-relative eval to "overlay use"
* Use FILE_PWD only in source-env and "overlay use"
* Ignore new tests for now
This will be another issue
* Throw an error if setting FILE_PWD manually
* Fix source-related test failures
* Fix nu-check to respect FILE_PWD
* Fix corrupted spans in source-env shell errors
* Fix up some references to old source
* Remove deprecation message
* Re-introduce deleted tests
Co-authored-by: kubouch <kubouch@gmail.com>
* Allow private imports inside modules
Can call `use ...` inside modules now.
* Add more tests
* Add a leak test
* Refactor exportables; Prepare for 'export use'
* Fix description
* Implement 'export use' command
This allows re-exporting module's commands and aliases from another
module.
* Add more tests; Fix import pattern list strings
The import pattern strings didn't trim the surrounding quotes.
* Add ignored test