Compare commits

..

1 Commits

Author SHA1 Message Date
777f746127 Update release script to nu v0.71 and use ubuntu-20.04 to build nu binary (#7290)
# Description

1. Update nu to v0.71 for release script
2. Remove the usage of `set-output` see:
https://github.blog/changelog/2022-10-11-github-actions-deprecating-save-state-and-set-output-commands/
3. Use `ubuntu-20.04` instead of `ubuntu-latest` to fix #7282 

To check the workflow running result see:
https://github.com/hustcer/nu-release/actions/runs/3588720720/jobs/6040412953

# 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` 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.
2022-12-06 06:17:06 +13:00
2002 changed files with 102375 additions and 220650 deletions

View File

@ -26,8 +26,3 @@ rustflags = ["-C", "link-args=-stack:10000000", "-C", "target-feature=+crt-stati
# [target.aarch64-apple-darwin] # [target.aarch64-apple-darwin]
# linker = "clang" # linker = "clang"
# rustflags = ["-C", "link-arg=-fuse-ld=mold"] # rustflags = ["-C", "link-arg=-fuse-ld=mold"]
[target.aarch64-apple-darwin]
# We can guarantee that this target will always run on a CPU with _at least_
# these capabilities, so let's optimize for them
rustflags = ["-Ctarget-cpu=apple-m1"]

2
.gitattributes vendored
View File

@ -1,2 +0,0 @@
# Example of a `.gitattributes` file which reclassifies `.nu` files as Nushell:
*.nu linguist-language=Nushell

View File

@ -1,5 +0,0 @@
#!/usr/bin/env nu
use ../toolkit.nu fmt
fmt --check --verbose

View File

@ -1,6 +0,0 @@
#!/usr/bin/env nu
use ../toolkit.nu [fmt, clippy]
fmt --check --verbose
clippy --verbose

View File

@ -1 +0,0 @@
This directory is intended for templates to automatically create issues with the [create-an-issue](https://github.com/JasonEtco/create-an-issue) action.

View File

@ -1,16 +0,0 @@
---
name: Nightly build of release binaries failed
about: Used to submit issues related to binaries release workflow
title: 'Attention: Nightly build of release binaries failed'
labels: ['build-package', 'priority']
assignees: ''
---
**Nightly build of release binaries failed**
Hi there:
If you see me here that means there is a release failure for the nightly build
Please **click the status badge** to see more details: [![Nightly Build](https://github.com/nushell/nushell/actions/workflows/nightly-build.yml/badge.svg)](https://github.com/nushell/nushell/actions/workflows/nightly-build.yml)

View File

@ -1,6 +1,5 @@
name: Bug Report name: Bug Report
description: Create a report to help us improve description: Create a report to help us improve
labels: ["needs-triage"]
body: body:
- type: textarea - type: textarea
id: description id: description
@ -13,7 +12,7 @@ body:
id: repro id: repro
attributes: attributes:
label: How to reproduce label: How to reproduce
description: Steps to reproduce the behavior (including succinct code examples or screenshots of the observed behavior) description: Steps to reproduce the behavior
placeholder: | placeholder: |
1. 1.
2. 2.
@ -28,6 +27,13 @@ body:
placeholder: I expected nu to... placeholder: I expected nu to...
validations: validations:
required: true required: true
- type: textarea
id: screenshots
attributes:
label: Screenshots
description: Please add any relevant screenshots here, if any
validations:
required: false
- type: textarea - type: textarea
id: config id: config
attributes: attributes:
@ -48,3 +54,10 @@ body:
| installed_plugins | binaryview, chart bar, chart line, fetch, from bson, from sqlite, inc, match, post, ps, query json, s3, selector, start, sys, textview, to bson, to sqlite, tree, xpath | | installed_plugins | binaryview, chart bar, chart line, fetch, from bson, from sqlite, inc, match, post, ps, query json, s3, selector, start, sys, textview, to bson, to sqlite, tree, xpath |
validations: validations:
required: true required: true
- type: textarea
id: context
attributes:
label: Additional context
description: Add any other context about the problem here.
validations:
required: false

View File

@ -1,6 +1,6 @@
name: Feature Request name: Feature Request
description: "When you want a new feature for something that doesn't already exist" description: "When you want a new feature for something that doesn't already exist"
labels: ["needs-triage", "enhancement"] labels: "enhancement"
body: body:
- type: textarea - type: textarea
id: problem id: problem

View File

@ -1,40 +0,0 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
# docs
# https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
version: 2
updates:
- package-ecosystem: "cargo"
directory: "/"
schedule:
interval: "weekly"
# We release on Tuesdays and open dependabot PRs will rebase after the
# version bump and thus consume unnecessary workers during release, thus
# let's open new ones on Wednesday
day: "wednesday"
ignore:
- dependency-name: "*"
update-types: ["version-update:semver-patch"]
groups:
# Only update polars as a whole as there are many subcrates that need to
# be updated at once. We explicitly depend on some of them, so batch their
# updates to not take up dependabot PR slots with dysfunctional PRs
polars:
patterns:
- "polars"
- "polars-*"
# uutils/coreutils also versions all their workspace crates the same at the moment
# Most of them have bleeding edge version requirements (some not)
# see: https://github.com/uutils/coreutils/blob/main/Cargo.toml
uutils:
patterns:
- "uucore"
- "uu_*"
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
day: "wednesday"

View File

@ -1,40 +1,24 @@
<!--
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 # 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. _(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.)_
# User-Facing Changes # User-Facing Changes
<!-- List of all changes that impact the user experience here. This helps us keep track of breaking changes. -->
_(List of all changes that impact the user experience here. This helps us keep track of breaking changes.)_
# Tests + Formatting # Tests + Formatting
<!--
Don't forget to add tests that cover your changes. Don't forget to add tests that cover your changes.
Make sure you've run and fixed any issues with these commands: 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 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 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 (on Windows make sure to [enable developer mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging)) - `cargo test --workspace` to check that all tests pass
- `cargo run -- -c "use toolkit.nu; toolkit test stdlib"` 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 # 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 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.

View File

@ -1,25 +0,0 @@
name: Security audit
on:
pull_request:
paths:
- '**/Cargo.toml'
- '**/Cargo.lock'
push:
branches:
- main
env:
RUST_BACKTRACE: 1
CARGO_TERM_COLOR: always
CLICOLOR: 1
jobs:
security_audit:
runs-on: ubuntu-latest
# Prevent sudden announcement of a new advisory from failing ci:
continue-on-error: true
steps:
- uses: actions/checkout@v4.1.7
- uses: rustsec/audit-check@v2.0.0
with:
token: ${{ secrets.GITHUB_TOKEN }}

View File

@ -1,12 +0,0 @@
let toolchain_spec = open rust-toolchain.toml | get toolchain.channel
let msrv_spec = open Cargo.toml | get package.rust-version
# This check is conservative in the sense that we use `rust-toolchain.toml`'s
# override to ensure that this is the upper-bound for the minimum supported
# rust version
if $toolchain_spec != $msrv_spec {
print -e "Mismatching rust compiler versions specified in `Cargo.toml` and `rust-toolchain.toml`"
print -e $"Cargo.toml: ($msrv_spec)"
print -e $"rust-toolchain.toml: ($toolchain_spec)"
exit 1
}

View File

@ -1,164 +1,150 @@
on: on:
pull_request: pull_request:
push: push: # Run CI on the main branch after every merge. This is important to fill the GitHub Actions cache in a way that pull requests can see it
branches: branches:
- main - main
name: continuous-integration name: continuous-integration
env:
NUSHELL_CARGO_PROFILE: ci
NU_LOG_LEVEL: DEBUG
# If changing these settings also change toolkit.nu
CLIPPY_OPTIONS: "-D warnings -D clippy::unwrap_used -D clippy::unchecked_duration_subtraction"
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref && github.ref || github.run_id }}
cancel-in-progress: true
jobs: jobs:
fmt-clippy: nu-fmt-clippy:
strategy: strategy:
fail-fast: true fail-fast: true
matrix: matrix:
# Pinning to Ubuntu 20.04 because building on newer Ubuntu versions causes linux-gnu platform: [windows-latest, macos-latest, ubuntu-latest]
# builds to link against a too-new-for-many-Linux-installs glibc version. Consider rust:
# revisiting this when 20.04 is closer to EOL (April 2025) - stable
#
# Using macOS 13 runner because 14 is based on the M1 and has half as much RAM (7 GB,
# instead of 14 GB) which is too little for us right now. Revisit when `dfr` commands are
# removed and we're only building the `polars` plugin instead
platform: [windows-latest, macos-13, ubuntu-20.04]
runs-on: ${{ matrix.platform }} runs-on: ${{ matrix.platform }}
env:
NUSHELL_CARGO_TARGET: ci
steps: steps:
- uses: actions/checkout@v4.1.7 - uses: actions/checkout@v3
- name: Setup Rust toolchain and cache - name: Setup Rust toolchain and cache
uses: actions-rust-lang/setup-rust-toolchain@v1.10.1 uses: actions-rust-lang/setup-rust-toolchain@v1.3.4
- name: cargo fmt - name: Rustfmt
run: cargo fmt --all -- --check uses: actions-rs/cargo@v1.0.1
with:
command: fmt
args: --all -- --check
# If changing these settings also change toolkit.nu
- name: Clippy - name: Clippy
run: cargo clippy --workspace --exclude nu_plugin_* -- $CLIPPY_OPTIONS uses: actions-rs/cargo@v1.0.1
with:
command: clippy
args: --workspace --exclude nu_plugin_* -- -D warnings -D clippy::unwrap_used -A clippy::needless_collect
# In tests we don't have to deny unwrap nu-tests:
- name: Clippy of tests env:
run: cargo clippy --tests --workspace --exclude nu_plugin_* -- -D warnings NUSHELL_CARGO_TARGET: ci
- name: Clippy of benchmarks
run: cargo clippy --benches --workspace --exclude nu_plugin_* -- -D warnings
tests:
strategy: strategy:
fail-fast: true fail-fast: true
matrix: matrix:
platform: [windows-latest, macos-latest, ubuntu-20.04] platform: [windows-latest, macos-latest, ubuntu-latest]
style: [default, dataframe]
rust:
- stable
include:
- style: default
flags: ""
- style: dataframe
flags: "--features=dataframe"
exclude:
# only test dataframes on Ubuntu (the fastest platform)
- platform: windows-latest
style: dataframe
- platform: macos-latest
style: dataframe
runs-on: ${{ matrix.platform }} runs-on: ${{ matrix.platform }}
steps: steps:
- uses: actions/checkout@v4.1.7 - uses: actions/checkout@v3
- name: Setup Rust toolchain and cache - name: Setup Rust toolchain and cache
uses: actions-rust-lang/setup-rust-toolchain@v1.10.1 uses: actions-rust-lang/setup-rust-toolchain@v1.3.4
- name: Tests - name: Tests
run: cargo test --workspace --profile ci --exclude nu_plugin_* uses: actions-rs/cargo@v1.0.1
- name: Check for clean repo with:
shell: bash command: test
run: | args: --workspace --profile ci --exclude nu_plugin_* ${{ matrix.flags }}
if [ -n "$(git status --porcelain)" ]; then
echo "there are changes"; python-virtualenv:
git status --porcelain env:
exit 1 NUSHELL_CARGO_TARGET: ci
else
echo "no changes in working directory";
fi
std-lib-and-python-virtualenv:
strategy: strategy:
fail-fast: true fail-fast: true
matrix: matrix:
platform: [ubuntu-20.04, macos-latest, windows-latest] platform: [ubuntu-latest, macos-latest, windows-latest]
rust:
- stable
py: py:
- py - py
runs-on: ${{ matrix.platform }} runs-on: ${{ matrix.platform }}
steps: steps:
- uses: actions/checkout@v4.1.7 - uses: actions/checkout@v3
- name: Setup Rust toolchain and cache - name: Setup Rust toolchain and cache
uses: actions-rust-lang/setup-rust-toolchain@v1.10.1 uses: actions-rust-lang/setup-rust-toolchain@v1.3.4
- name: Install Nushell - name: Install Nushell
run: cargo install --path . --locked --no-default-features uses: actions-rs/cargo@v1.0.1
with:
- name: Standard library tests command: install
run: nu -c 'use crates/nu-std/testing.nu; testing run-tests --path crates/nu-std' args: --locked --path=. --profile ci --no-default-features
- name: Ensure that Cargo.toml MSRV and rust-toolchain.toml use the same version
run: nu .github/workflows/check-msrv.nu
- name: Setup Python - name: Setup Python
uses: actions/setup-python@v5 uses: actions/setup-python@v4
with: with:
python-version: "3.10" python-version: "3.10"
- run: python -m pip install tox
- name: Install virtualenv - name: Install virtualenv
run: pip install virtualenv run: git clone https://github.com/pypa/virtualenv.git
shell: bash shell: bash
- name: Test Nushell in virtualenv - name: Test Nushell in virtualenv
run: nu scripts/test_virtualenv.nu run: cd virtualenv && tox -e ${{ matrix.py }} -- -k nushell
shell: bash shell: bash
- name: Check for clean repo # Build+test plugins on their own, without the rest of Nu. This helps with CI parallelization and
shell: bash # also helps test that the plugins build without any feature unification shenanigans
run: |
if [ -n "$(git status --porcelain)" ]; then
echo "there are changes";
git status --porcelain
exit 1
else
echo "no changes in working directory";
fi
plugins: plugins:
env:
NUSHELL_CARGO_TARGET: ci
strategy: strategy:
fail-fast: true fail-fast: true
matrix: matrix:
# Using macOS 13 runner because 14 is based on the M1 and has half as much RAM (7 GB, platform: [windows-latest, macos-latest, ubuntu-latest]
# instead of 14 GB) which is too little for us right now. rust:
# - stable
# Failure occurring with clippy for rust 1.77.2
platform: [windows-latest, macos-13, ubuntu-20.04]
runs-on: ${{ matrix.platform }} runs-on: ${{ matrix.platform }}
steps: steps:
- uses: actions/checkout@v4.1.7 - uses: actions/checkout@v3
- name: Setup Rust toolchain and cache - name: Setup Rust toolchain and cache
uses: actions-rust-lang/setup-rust-toolchain@v1.10.1 uses: actions-rust-lang/setup-rust-toolchain@v1.3.4
- name: Clippy - name: Clippy
run: cargo clippy --package nu_plugin_* -- $CLIPPY_OPTIONS uses: actions-rs/cargo@v1.0.1
with:
command: clippy
args: --package nu_plugin_* ${{ matrix.flags }} -- -D warnings -D clippy::unwrap_used -A clippy::needless_collect
- name: Tests - name: Tests
run: cargo test --profile ci --package nu_plugin_* uses: actions-rs/cargo@v1.0.1
with:
- name: Check for clean repo command: test
shell: bash args: --profile ci --package nu_plugin_*
run: |
if [ -n "$(git status --porcelain)" ]; then
echo "there are changes";
git status --porcelain
exit 1
else
echo "no changes in working directory";
fi

41
.github/workflows/manual.yml vendored Normal file
View File

@ -0,0 +1,41 @@
# This is a basic workflow that is manually triggered
# Don't run it unless you know what you are doing
name: Manual Workflow for Winget Submission
# Controls when the action will run. Workflow runs when manually triggered using the UI
# or API.
on:
workflow_dispatch:
# Inputs the workflow accepts.
inputs:
ver:
# Friendly description to be shown in the UI instead of 'ver'
description: 'The nushell version to release'
# Default value if no value is explicitly provided
default: '0.66.0'
# Input has to be provided for the workflow to run
required: true
uri:
# Friendly description to be shown in the UI instead of 'uri'
description: 'The nushell windows .msi package URI to publish'
# Default value if no value is explicitly provided
default: 'https://github.com/nushell/nushell/releases/download/0.66.0/nu-0.66.0-x86_64-pc-windows-msvc.msi'
# Input has to be provided for the workflow to run
required: true
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
# This workflow contains a single job
rls-winget-pkg:
name: Publish winget package manually
# The type of runner that the job will run on
runs-on: windows-latest
# Steps represent a sequence of tasks that will be executed as part of the job
steps:
# Runs commands using the runners shell
- name: Submit package to Windows Package Manager Community Repository Manually
run: |
iwr https://github.com/microsoft/winget-create/releases/download/v1.0.4.0/wingetcreate.exe -OutFile wingetcreate.exe
.\wingetcreate.exe update Nushell.Nushell -s -v ${{ github.event.inputs.ver }} -u ${{ github.event.inputs.uri }} -t ${{ secrets.NUSHELL_PAT }}

View File

@ -1,30 +0,0 @@
# Description:
# - Add milestone to a merged PR automatically
# - Add milestone to a closed issue that has a merged PR fix (if any)
name: Milestone Action
on:
issues:
types: [closed]
pull_request_target:
types: [closed]
jobs:
update-milestone:
runs-on: ubuntu-latest
name: Milestone Update
steps:
- name: Set Milestone for PR
uses: hustcer/milestone-action@main
if: github.event.pull_request.merged == true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Bind milestone to closed issue that has a merged PR fix
- name: Set Milestone for Issue
uses: hustcer/milestone-action@main
if: github.event.issue.state == 'closed'
with:
action: bind-issue
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@ -1,218 +0,0 @@
#
# REF:
# 1. https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstrategymatrixinclude
# 2. https://github.com/JasonEtco/create-an-issue
# 3. https://docs.github.com/en/actions/learn-github-actions/variables
# 4. https://github.com/actions/github-script
#
name: Nightly Build
on:
push:
branches:
- nightly # Just for test purpose only with the nightly repo
# This schedule will run only from the default branch
schedule:
- cron: '15 0 * * *' # run at 00:15 AM UTC
defaults:
run:
shell: bash
jobs:
prepare:
name: Prepare
runs-on: ubuntu-latest
# This job is required by the release job, so we should make it run both from Nushell repo and nightly repo
# if: github.repository == 'nushell/nightly'
steps:
- name: Checkout
uses: actions/checkout@v4
if: github.repository == 'nushell/nightly'
with:
ref: main
fetch-depth: 0
# Configure PAT here: https://github.com/settings/tokens for the push operation in the following steps
token: ${{ secrets.WORKFLOW_TOKEN }}
- name: Setup Nushell
uses: hustcer/setup-nu@v3
if: github.repository == 'nushell/nightly'
with:
version: 0.98.0
# Synchronize the main branch of nightly repo with the main branch of Nushell official repo
- name: Prepare for Nightly Release
shell: nu {0}
if: github.repository == 'nushell/nightly'
run: |
cd $env.GITHUB_WORKSPACE
git checkout main
# We can't push if no user name and email are configured
git config user.name 'hustcer'
git config user.email 'hustcer@outlook.com'
git pull origin main
git remote add src https://github.com/nushell/nushell.git
git fetch src main
# All the changes will be overwritten by the upstream main branch
git reset --hard src/main
git push origin main -f
let sha_short = (git rev-parse --short origin/main | str trim | str substring 0..7)
let tag_name = $'nightly-($sha_short)'
if (git ls-remote --tags origin $tag_name | is-empty) {
git tag -a $tag_name -m $'Nightly build from ($sha_short)'
git push origin --tags
}
standard:
name: Nu
needs: prepare
strategy:
fail-fast: false
matrix:
target:
- aarch64-apple-darwin
- x86_64-apple-darwin
- x86_64-pc-windows-msvc
- aarch64-pc-windows-msvc
- x86_64-unknown-linux-gnu
- x86_64-unknown-linux-musl
- aarch64-unknown-linux-gnu
- aarch64-unknown-linux-musl
- armv7-unknown-linux-gnueabihf
- armv7-unknown-linux-musleabihf
- riscv64gc-unknown-linux-gnu
- loongarch64-unknown-linux-gnu
extra: ['bin']
include:
- target: aarch64-apple-darwin
os: macos-latest
- target: x86_64-apple-darwin
os: macos-latest
- target: x86_64-pc-windows-msvc
extra: 'bin'
os: windows-latest
- target: x86_64-pc-windows-msvc
extra: msi
os: windows-latest
- target: aarch64-pc-windows-msvc
extra: 'bin'
os: windows-latest
- target: aarch64-pc-windows-msvc
extra: msi
os: windows-latest
- target: x86_64-unknown-linux-gnu
os: ubuntu-22.04
- target: x86_64-unknown-linux-musl
os: ubuntu-22.04
- target: aarch64-unknown-linux-gnu
os: ubuntu-22.04
- target: aarch64-unknown-linux-musl
os: ubuntu-22.04
- target: armv7-unknown-linux-gnueabihf
os: ubuntu-22.04
- target: armv7-unknown-linux-musleabihf
os: ubuntu-22.04
- target: riscv64gc-unknown-linux-gnu
os: ubuntu-latest
- target: loongarch64-unknown-linux-gnu
os: ubuntu-22.04
runs-on: ${{matrix.os}}
steps:
- uses: actions/checkout@v4
with:
ref: main
fetch-depth: 0
- name: Update Rust Toolchain Target
run: |
echo "targets = ['${{matrix.target}}']" >> rust-toolchain.toml
- name: Setup Rust toolchain and cache
uses: actions-rust-lang/setup-rust-toolchain@v1.10.1
# WARN: Keep the rustflags to prevent from the winget submission error: `CAQuietExec: Error 0xc0000135`
with:
rustflags: ''
- name: Setup Nushell
uses: hustcer/setup-nu@v3
with:
version: 0.98.0
- name: Release Nu Binary
id: nu
run: nu .github/workflows/release-pkg.nu
env:
OS: ${{ matrix.os }}
REF: ${{ github.ref }}
TARGET: ${{ matrix.target }}
_EXTRA_: ${{ matrix.extra }}
- name: Create an Issue for Release Failure
if: ${{ failure() }}
uses: JasonEtco/create-an-issue@v2.9.2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
update_existing: true
search_existing: open
filename: .github/AUTO_ISSUE_TEMPLATE/nightly-build-fail.md
- name: Set Outputs of Short SHA
id: vars
run: |
echo "date=$(date -u +'%Y-%m-%d')" >> $GITHUB_OUTPUT
sha_short=$(git rev-parse --short HEAD)
echo "sha_short=${sha_short:0:7}" >> $GITHUB_OUTPUT
# REF: https://github.com/marketplace/actions/gh-release
# Create a release only in nushell/nightly repo
- name: Publish Archive
uses: softprops/action-gh-release@v2.0.8
if: ${{ startsWith(github.repository, 'nushell/nightly') }}
with:
prerelease: true
files: ${{ steps.nu.outputs.archive }}
tag_name: nightly-${{ steps.vars.outputs.sha_short }}
name: Nu-nightly-${{ steps.vars.outputs.date }}-${{ steps.vars.outputs.sha_short }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
cleanup:
name: Cleanup
# Should only run in nushell/nightly repo
if: github.repository == 'nushell/nightly'
runs-on: ubuntu-latest
steps:
# Sleep for 30 minutes, waiting for the release to be published
- name: Waiting for Release
run: sleep 1800
- uses: actions/checkout@v4
with:
ref: main
- name: Setup Nushell
uses: hustcer/setup-nu@v3
with:
version: 0.98.0
# Keep the last a few releases
- name: Delete Older Releases
shell: nu {0}
run: |
let KEEP_COUNT = 10
let deprecated = (http get https://api.github.com/repos/nushell/nightly/releases | sort-by -r created_at | select tag_name id | range $KEEP_COUNT..)
for release in $deprecated {
print $'Deleting tag ($release.tag_name)'
git push origin --delete $release.tag_name
print $'Deleting release ($release.tag_name)'
let delete_url = $'https://api.github.com/repos/nushell/nightly/releases/($release.id)'
let version = "X-GitHub-Api-Version: 2022-11-28"
let accept = "Accept: application/vnd.github+json"
let auth = "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}"
# http delete $delete_url -H $version -H $auth -H $accept
curl -L -X DELETE -H $accept -H $auth -H $version $delete_url
}

View File

@ -6,111 +6,48 @@
# REF: # REF:
# 1. https://github.com/volks73/cargo-wix # 1. https://github.com/volks73/cargo-wix
# Instructions for manually creating an MSI for Winget Releases when they fail
# Added 2022-11-29 when Windows packaging wouldn't work
# Updated again on 2023-02-23 because msis are still failing validation
# To run this manual for windows here are the steps I take
# checkout the release you want to publish
# 1. git checkout 0.86.0
# 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. $env.TARGET = 'x86_64-pc-windows-msvc'
# 4. $env.GITHUB_WORKSPACE = 'D:\nushell'
# 5. $env.GITHUB_OUTPUT = 'D:\nushell\output\out.txt'
# 6. $env.OS = 'windows-latest'
# make sure 7z.exe is in your path https://www.7-zip.org/download.html
# 7. $env.Path = ($env.Path | append 'c:\apps\7-zip')
# make sure aria2c.exe is in your path https://github.com/aria2/aria2
# 8. $env.Path = ($env.Path | append 'c:\path\to\aria2c')
# make sure you have the wixtools installed https://wixtoolset.org/
# 9. $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'
# 10. $env._EXTRA_ = 'bin'
# 11. source .github\workflows\release-pkg.nu
# 12. cd ..
# 13. $env._EXTRA_ = 'msi'
# 14. 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
# on the winget-pkgs PR. To generate the hash, run this command
# 15. open target\wix\nu-0.74.0-x86_64-pc-windows-msvc.msi | hash sha256
# Then, just take the output and put it in the winget-pkgs PR for the hash on the msi
# The main binary file to be released # The main binary file to be released
let bin = 'nu' let bin = 'nu'
let os = $env.OS let os = $env.OS
let target = $env.TARGET let target = $env.TARGET
# Repo source dir like `/home/runner/work/nushell/nushell` # Repo source dir like `/home/runner/work/nushell/nushell`
let src = $env.GITHUB_WORKSPACE let src = $env.GITHUB_WORKSPACE
let flags = $env.TARGET_RUSTFLAGS
let dist = $'($env.GITHUB_WORKSPACE)/output' let dist = $'($env.GITHUB_WORKSPACE)/output'
let version = (open Cargo.toml | get package.version) let version = (open Cargo.toml | get package.version)
print $'Debugging info:' $'Debugging info:'
print { version: $version, bin: $bin, os: $os, target: $target, src: $src, dist: $dist }; hr-line -b print { version: $version, bin: $bin, os: $os, target: $target, src: $src, flags: $flags, dist: $dist }; hr-line -b
# $env # $env
let USE_UBUNTU = $os starts-with ubuntu let USE_UBUNTU = 'ubuntu-20.04'
print $'(char nl)Packaging ($bin) v($version) for ($target) in ($src)...'; hr-line -b $'(char nl)Packaging ($bin) v($version) for ($target) in ($src)...'; hr-line -b
if not ('Cargo.lock' | path exists) { cargo generate-lockfile } if not ('Cargo.lock' | path exists) { cargo generate-lockfile }
print $'Start building ($bin)...'; hr-line $'Start building ($bin)...'; hr-line
# ---------------------------------------------------------------------------- # ----------------------------------------------------------------------------
# Build for Ubuntu and macOS # Build for Ubuntu and macOS
# ---------------------------------------------------------------------------- # ----------------------------------------------------------------------------
if $os in ['macos-latest'] or $USE_UBUNTU { if $os in [$USE_UBUNTU, 'macos-latest'] {
if $USE_UBUNTU { if $os == $USE_UBUNTU {
sudo apt update
sudo apt-get install libxcb-composite0-dev -y sudo apt-get install libxcb-composite0-dev -y
} }
match $target { if $target == 'aarch64-unknown-linux-gnu' {
'aarch64-unknown-linux-gnu' => { sudo apt-get install gcc-aarch64-linux-gnu -y
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
cargo-build-nu } else if $target == 'armv7-unknown-linux-gnueabihf' {
} sudo apt-get install pkg-config gcc-arm-linux-gnueabihf -y
'riscv64gc-unknown-linux-gnu' => { let-env CARGO_TARGET_ARMV7_UNKNOWN_LINUX_GNUEABIHF_LINKER = 'arm-linux-gnueabihf-gcc'
sudo apt-get install gcc-riscv64-linux-gnu -y cargo-build-nu $flags
$env.CARGO_TARGET_RISCV64GC_UNKNOWN_LINUX_GNU_LINKER = 'riscv64-linux-gnu-gcc' } else {
cargo-build-nu # musl-tools to fix 'Failed to find tool. Is `musl-gcc` installed?'
} # Actually just for x86_64-unknown-linux-musl target
'armv7-unknown-linux-gnueabihf' => { if $os == $USE_UBUNTU { sudo apt install musl-tools -y }
sudo apt-get install pkg-config gcc-arm-linux-gnueabihf -y cargo-build-nu $flags
$env.CARGO_TARGET_ARMV7_UNKNOWN_LINUX_GNUEABIHF_LINKER = 'arm-linux-gnueabihf-gcc'
cargo-build-nu
}
'aarch64-unknown-linux-musl' => {
aria2c https://musl.cc/aarch64-linux-musl-cross.tgz
tar -xf aarch64-linux-musl-cross.tgz -C $env.HOME
$env.PATH = ($env.PATH | split row (char esep) | prepend $'($env.HOME)/aarch64-linux-musl-cross/bin')
$env.CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER = 'aarch64-linux-musl-gcc'
cargo-build-nu
}
'armv7-unknown-linux-musleabihf' => {
aria2c https://musl.cc/armv7r-linux-musleabihf-cross.tgz
tar -xf armv7r-linux-musleabihf-cross.tgz -C $env.HOME
$env.PATH = ($env.PATH | split row (char esep) | prepend $'($env.HOME)/armv7r-linux-musleabihf-cross/bin')
$env.CARGO_TARGET_ARMV7_UNKNOWN_LINUX_MUSLEABIHF_LINKER = 'armv7r-linux-musleabihf-gcc'
cargo-build-nu
}
'loongarch64-unknown-linux-gnu' => {
aria2c https://github.com/loongson/build-tools/releases/download/2024.08.08/x86_64-cross-tools-loongarch64-binutils_2.43-gcc_14.2.0-glibc_2.40.tar.xz
tar xf x86_64-cross-tools-loongarch64-*.tar.xz
$env.PATH = ($env.PATH | split row (char esep) | prepend $'($env.PWD)/cross-tools/bin')
$env.CARGO_TARGET_LOONGARCH64_UNKNOWN_LINUX_GNU_LINKER = 'loongarch64-unknown-linux-gnu-gcc'
cargo-build-nu
}
_ => {
# musl-tools to fix 'Failed to find tool. Is `musl-gcc` installed?'
# Actually just for x86_64-unknown-linux-musl target
if $USE_UBUNTU { sudo apt install musl-tools -y }
cargo-build-nu
}
} }
} }
@ -118,7 +55,11 @@ if $os in ['macos-latest'] or $USE_UBUNTU {
# Build for Windows without static-link-openssl feature # Build for Windows without static-link-openssl feature
# ---------------------------------------------------------------------------- # ----------------------------------------------------------------------------
if $os in ['windows-latest'] { if $os in ['windows-latest'] {
cargo-build-nu if ($flags | str trim | is-empty) {
cargo build --release --all --target $target
} else {
cargo build --release --all --target $target $flags
}
} }
# ---------------------------------------------------------------------------- # ----------------------------------------------------------------------------
@ -127,50 +68,41 @@ if $os in ['windows-latest'] {
let suffix = if $os == 'windows-latest' { '.exe' } let suffix = if $os == 'windows-latest' { '.exe' }
# nu, nu_plugin_* were all included # nu, nu_plugin_* were all included
let executable = $'target/($target)/release/($bin)*($suffix)' let executable = $'target/($target)/release/($bin)*($suffix)'
print $'Current executable file: ($executable)' $'Current executable file: ($executable)'
cd $src; mkdir $dist; cd $src; mkdir $dist;
rm -rf ...(glob $'target/($target)/release/*.d') ...(glob $'target/($target)/release/nu_pretty_hex*') rm -rf $'target/($target)/release/*.d' $'target/($target)/release/nu_pretty_hex*'
print $'(char nl)All executable files:'; hr-line $'(char nl)All executable files:'; hr-line
# We have to use `print` here to make sure the command output is displayed ls -f $executable
print (ls -f ($executable | into glob)); sleep 1sec
print $'(char nl)Copying release files...'; hr-line $'(char nl)Copying release files...'; hr-line
"To use the included Nushell plugins, register the binaries with the `plugin add` command to tell Nu where to find the plugin. cp -v README.release.txt $'($dist)/README.txt'
Then you can use `plugin use` to load the plugin into your session. [LICENSE $executable] | each {|it| cp -rv $it $dist } | flatten
For example:
> plugin add ./nu_plugin_query $'(char nl)Check binary release version detail:'; hr-line
> plugin use query
For more information, refer to https://www.nushell.sh/book/plugins.html
" | save $'($dist)/README.txt' -f
[LICENSE ...(glob $executable)] | each {|it| cp -rv $it $dist } | flatten
print $'(char nl)Check binary release version detail:'; hr-line
let ver = if $os == 'windows-latest' { let ver = if $os == 'windows-latest' {
(do -i { .\output\nu.exe -c 'version' }) | str join (do -i { ./output/nu.exe -c 'version' }) | str join
} else { } else {
(do -i { ./output/nu -c 'version' }) | str join (do -i { ./output/nu -c 'version' }) | str join
} }
if ($ver | str trim | is-empty) { if ($ver | str trim | is-empty) {
print $'(ansi r)Incompatible Nu binary: The binary cross compiled is not runnable on current arch...(ansi reset)' $'(ansi r)Incompatible nu binary...(ansi reset)'
} else { print $ver } } else { $ver }
# ---------------------------------------------------------------------------- # ----------------------------------------------------------------------------
# Create a release archive and send it to output for the following steps # Create a release archive and send it to output for the following steps
# ---------------------------------------------------------------------------- # ----------------------------------------------------------------------------
cd $dist; print $'(char nl)Creating release archive...'; hr-line cd $dist; $'(char nl)Creating release archive...'; hr-line
if $os in ['macos-latest'] or $USE_UBUNTU { if $os in [$USE_UBUNTU, 'macos-latest'] {
let files = (ls | get name) let files = (ls | get name)
let dest = $'($bin)-($version)-($target)' let dest = $'($bin)-($version)-($target)'
let archive = $'($dist)/($dest).tar.gz' let archive = $'($dist)/($dest).tar.gz'
mkdir $dest mkdir $dest
$files | each {|it| cp -v $it $dest } $files | each {|it| mv $it $dest } | ignore
print $'(char nl)(ansi g)Archive contents:(ansi reset)'; hr-line; ls $dest | print $'(char nl)(ansi g)Archive contents:(ansi reset)'; hr-line; ls $dest
tar -czf $archive $dest tar -czf $archive $dest
print $'archive: ---> ($archive)'; ls $archive print $'archive: ---> ($archive)'; ls $archive
@ -181,56 +113,47 @@ if $os in ['macos-latest'] or $USE_UBUNTU {
let releaseStem = $'($bin)-($version)-($target)' let releaseStem = $'($bin)-($version)-($target)'
print $'(char nl)Download less related stuffs...'; hr-line $'(char nl)Download less related stuffs...'; hr-line
# todo: less-v661 is out but is released as a zip file. maybe we should switch to that and extract it?
aria2c https://github.com/jftuga/less-Windows/releases/download/less-v608/less.exe -o less.exe aria2c https://github.com/jftuga/less-Windows/releases/download/less-v608/less.exe -o less.exe
# the below was renamed because it was failing to download for darren. it should work but it wasn't aria2c https://raw.githubusercontent.com/jftuga/less-Windows/master/LICENSE -o LICENSE-for-less.txt
# todo: maybe we should get rid of this aria2c dependency and just use http get?
#aria2c https://raw.githubusercontent.com/jftuga/less-Windows/master/LICENSE -o LICENSE-for-less.txt
aria2c https://github.com/jftuga/less-Windows/blob/master/LICENSE -o LICENSE-for-less.txt
# Create Windows msi release package # Create Windows msi release package
if (get-env _EXTRA_) == 'msi' { if (get-env _EXTRA_) == 'msi' {
let wixRelease = $'($src)/target/wix/($releaseStem).msi' let wixRelease = $'($src)/target/wix/($releaseStem).msi'
print $'(char nl)Start creating Windows msi package with the following contents...' $'(char nl)Start creating Windows msi package...'
cd $src; hr-line cd $src; hr-line
# Wix need the binaries be stored in target/release/ # Wix need the binaries be stored in target/release/
cp -r ($'($dist)/*' | into glob) target/release/ cp -r $'($dist)/*' target/release/
ls target/release/* | print cargo install cargo-wix --version 0.3.3
cargo install cargo-wix --version 0.3.8
cargo wix --no-build --nocapture --package nu --output $wixRelease cargo wix --no-build --nocapture --package nu --output $wixRelease
# Workaround for https://github.com/softprops/action-gh-release/issues/280 print $'archive: ---> ($wixRelease)';
let archive = ($wixRelease | str replace --all '\' '/') echo $"archive=($wixRelease)" | save --append $env.GITHUB_OUTPUT
print $'archive: ---> ($archive)';
echo $"archive=($archive)" | save --append $env.GITHUB_OUTPUT
} else { } else {
print $'(char nl)(ansi g)Archive contents:(ansi reset)'; hr-line; ls | print $'(char nl)(ansi g)Archive contents:(ansi reset)'; hr-line; ls
let archive = $'($dist)/($releaseStem).zip' let archive = $'($dist)/($releaseStem).zip'
7z a $archive ...(glob *) 7z a $archive *
print $'archive: ---> ($archive)';
let pkg = (ls -f $archive | get name) let pkg = (ls -f $archive | get name)
if not ($pkg | is-empty) { if not ($pkg | is-empty) {
# Workaround for https://github.com/softprops/action-gh-release/issues/280 echo $"archive=($pkg | get 0)" | save --append $env.GITHUB_OUTPUT
let archive = ($pkg | get 0 | str replace --all '\' '/')
print $'archive: ---> ($archive)'
echo $"archive=($archive)" | save --append $env.GITHUB_OUTPUT
} }
} }
} }
def 'cargo-build-nu' [] { def 'cargo-build-nu' [ options: string ] {
if $os == 'windows-latest' { if ($options | str trim | is-empty) {
cargo build --release --all --target $target
} else {
cargo build --release --all --target $target --features=static-link-openssl cargo build --release --all --target $target --features=static-link-openssl
} else {
cargo build --release --all --target $target --features=static-link-openssl $options
} }
} }
# Print a horizontal line marker # Print a horizontal line marker
def 'hr-line' [ def 'hr-line' [
--blank-line(-b) --blank-line(-b): bool
] { ] {
print $'(ansi g)---------------------------------------------------------------------------->(ansi reset)' print $'(ansi g)---------------------------------------------------------------------------->(ansi reset)'
if $blank_line { char nl } if $blank_line { char nl }

View File

@ -14,80 +14,67 @@ defaults:
shell: bash shell: bash
jobs: jobs:
release: all:
name: Nu name: All
strategy: strategy:
fail-fast: false
matrix: matrix:
target: target:
- aarch64-apple-darwin - aarch64-apple-darwin
- x86_64-apple-darwin - x86_64-apple-darwin
- x86_64-pc-windows-msvc - x86_64-pc-windows-msvc
- aarch64-pc-windows-msvc
- x86_64-unknown-linux-gnu - x86_64-unknown-linux-gnu
- x86_64-unknown-linux-musl - x86_64-unknown-linux-musl
- aarch64-unknown-linux-gnu - aarch64-unknown-linux-gnu
- aarch64-unknown-linux-musl
- armv7-unknown-linux-gnueabihf - armv7-unknown-linux-gnueabihf
- armv7-unknown-linux-musleabihf
- riscv64gc-unknown-linux-gnu
- loongarch64-unknown-linux-gnu
extra: ['bin'] extra: ['bin']
include: include:
- target: aarch64-apple-darwin - target: aarch64-apple-darwin
os: macos-latest os: macos-latest
target_rustflags: ''
- target: x86_64-apple-darwin - target: x86_64-apple-darwin
os: macos-latest os: macos-latest
target_rustflags: ''
- target: x86_64-pc-windows-msvc - target: x86_64-pc-windows-msvc
extra: 'bin' extra: 'bin'
os: windows-latest os: windows-latest
target_rustflags: ''
- target: x86_64-pc-windows-msvc - target: x86_64-pc-windows-msvc
extra: msi extra: msi
os: windows-latest os: windows-latest
- target: aarch64-pc-windows-msvc target_rustflags: ''
extra: 'bin'
os: windows-latest
- target: aarch64-pc-windows-msvc
extra: msi
os: windows-latest
- target: x86_64-unknown-linux-gnu - target: x86_64-unknown-linux-gnu
os: ubuntu-22.04 os: ubuntu-20.04
target_rustflags: ''
- target: x86_64-unknown-linux-musl - target: x86_64-unknown-linux-musl
os: ubuntu-22.04 os: ubuntu-20.04
target_rustflags: ''
- target: aarch64-unknown-linux-gnu - target: aarch64-unknown-linux-gnu
os: ubuntu-22.04 os: ubuntu-20.04
- target: aarch64-unknown-linux-musl target_rustflags: ''
os: ubuntu-22.04
- target: armv7-unknown-linux-gnueabihf - target: armv7-unknown-linux-gnueabihf
os: ubuntu-22.04 os: ubuntu-20.04
- target: armv7-unknown-linux-musleabihf target_rustflags: ''
os: ubuntu-22.04
- target: riscv64gc-unknown-linux-gnu
os: ubuntu-latest
- target: loongarch64-unknown-linux-gnu
os: ubuntu-22.04
runs-on: ${{matrix.os}} runs-on: ${{matrix.os}}
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v3.1.0
- name: Update Rust Toolchain Target - name: Install Rust Toolchain Components
run: | uses: actions-rs/toolchain@v1.0.6
echo "targets = ['${{matrix.target}}']" >> rust-toolchain.toml
- name: Setup Rust toolchain
uses: actions-rust-lang/setup-rust-toolchain@v1.10.1
# WARN: Keep the rustflags to prevent from the winget submission error: `CAQuietExec: Error 0xc0000135`
with: with:
cache: false override: true
rustflags: '' profile: minimal
toolchain: stable
target: ${{ matrix.target }}
- name: Setup Nushell - name: Setup Nushell
uses: hustcer/setup-nu@v3 uses: hustcer/setup-nu@v3
with: with:
version: 0.98.0 version: 0.71.0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Release Nu Binary - name: Release Nu Binary
id: nu id: nu
@ -97,36 +84,14 @@ jobs:
REF: ${{ github.ref }} REF: ${{ github.ref }}
TARGET: ${{ matrix.target }} TARGET: ${{ matrix.target }}
_EXTRA_: ${{ matrix.extra }} _EXTRA_: ${{ matrix.extra }}
TARGET_RUSTFLAGS: ${{ matrix.target_rustflags }}
# REF: https://github.com/marketplace/actions/gh-release # REF: https://github.com/marketplace/actions/gh-release
- name: Publish Archive - name: Publish Archive
uses: softprops/action-gh-release@v2.0.8 uses: softprops/action-gh-release@v0.1.13
if: ${{ startsWith(github.ref, 'refs/tags/') }} if: ${{ startsWith(github.ref, 'refs/tags/') }}
with: with:
draft: true draft: true
files: ${{ steps.nu.outputs.archive }} files: ${{ steps.nu.outputs.archive }}
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
sha256sum:
needs: release
name: Create Sha256sum
runs-on: ubuntu-latest
steps:
- name: Download Release Archives
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: >-
gh release download ${{ github.ref_name }}
--repo ${{ github.repository }}
--pattern '*'
--dir release
- name: Create Checksums
run: cd release && shasum -a 256 * > ../SHA256SUMS
- name: Publish Checksums
uses: softprops/action-gh-release@v2.0.8
with:
draft: true
files: SHA256SUMS
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

28
.github/workflows/stale.yml vendored Normal file
View File

@ -0,0 +1,28 @@
name: 'Close stale issues and PRs'
#on: [workflow_dispatch]
on:
schedule:
- cron: '30 1 * * *'
permissions:
issues: write
pull-requests: write
jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v3
with:
#debug-only: true
ascending: true
operations-per-run: 520
enable-statistics: true
repo-token: ${{ secrets.GITHUB_TOKEN }}
close-issue-message: 'This issue has been marked stale for more than 100000 days without activity. Closing this issue, but if you find that the issue is still valid, please reopen.'
close-pr-message: 'This PR has been marked stale for more than 100 days without activity. Closing this PR, but if you are still working on it, please reopen.'
days-before-issue-stale: 90
days-before-pr-stale: 45
days-before-issue-close: 100000
days-before-pr-close: 100
exempt-issue-labels: 'exempt,keep'

View File

@ -1,13 +0,0 @@
name: Typos
on: [pull_request]
jobs:
run:
name: Spell Check with Typos
runs-on: ubuntu-latest
steps:
- name: Checkout Actions Repository
uses: actions/checkout@v4.1.7
- name: Check spelling
uses: crate-ci/typos@v1.26.0

View File

@ -1,29 +1,19 @@
name: Submit Nushell package to Windows Package Manager Community Repository name: Submit Nushell package to Windows Package Manager Community Repository
on: on:
release:
types: [released]
workflow_dispatch: workflow_dispatch:
inputs: release:
tag_name: types: [published]
description: 'Specific tag name'
required: true
type: string
jobs: jobs:
winget: winget:
name: Publish winget package name: Publish winget package
runs-on: ubuntu-latest runs-on: windows-latest
steps: steps:
- name: Submit package to Windows Package Manager Community Repository - name: Submit package to Windows Package Manager Community Repository
uses: vedantmgoyal2009/winget-releaser@v2 run: |
with: iwr https://github.com/microsoft/winget-create/releases/download/v1.0.4.0/wingetcreate.exe -OutFile wingetcreate.exe
identifier: Nushell.Nushell $github = Get-Content '${{ github.event_path }}' | ConvertFrom-Json
# Exclude all `*-msvc-full.msi` full release files, $installerUrl = $github.release.assets | Where-Object -Property name -match 'windows-msvc.msi' | Select -ExpandProperty browser_download_url -First 1
# and only the default `*msvc.msi` files will be included .\wingetcreate.exe update Nushell.Nushell -s -v $github.release.tag_name -u $installerUrl -t ${{ secrets.NUSHELL_PAT }}
installers-regex: 'msvc\.msi$'
version: ${{ inputs.tag_name || github.event.release.tag_name }}
release-tag: ${{ inputs.tag_name || github.event.release.tag_name }}
token: ${{ secrets.NUSHELL_PAT }}
fork-user: fdncred

13
.gitignore vendored
View File

@ -22,9 +22,6 @@ debian/nu/
# VSCode's IDE items # VSCode's IDE items
.vscode/* .vscode/*
# JetBrains' Fleet IDE
.fleet/*
# Visual Studio Extension SourceGear Rust items # Visual Studio Extension SourceGear Rust items
VSWorkspaceSettings.json VSWorkspaceSettings.json
unstable_cargo_features.txt unstable_cargo_features.txt
@ -41,12 +38,4 @@ tarpaulin-report.html
.vs/* .vs/*
*.rsproj *.rsproj
*.rsproj.user *.rsproj.user
*.sln *.sln
*.code-workspace
# direnv
.direnv/
.envrc
# pre-commit-hooks
.pre-commit-config.yaml

View File

@ -1,26 +0,0 @@
cff-version: 1.2.0
title: 'Nushell'
message: >-
If you use this software and wish to cite it,
you can use the metadata from this file.
type: software
authors:
- name: "The Nushell Project Team"
identifiers:
- type: url
value: 'https://github.com/nushell/nushell'
description: Repository
repository-code: 'https://github.com/nushell/nushell'
url: 'https://www.nushell.sh/'
abstract: >-
The goal of the Nushell project is to take the Unix
philosophy of shells, where pipes connect simple commands
together, and bring it to the modern style of development.
Thus, rather than being either a shell, or a programming
language, Nushell connects both by bringing a rich
programming language and a full-featured shell together
into one package.
keywords:
- nushell
- shell
license: MIT

View File

@ -2,25 +2,7 @@
Welcome to Nushell and thank you for considering contributing! Welcome to Nushell and thank you for considering contributing!
## Table of contents ## Review Process
- [Proposing design changes](#proposing-design-changes)
- [Developing](#developing)
- [Setup](#setup)
- [Tests](#tests)
- [Useful commands](#useful-commands)
- [Debugging tips](#debugging-tips)
- [Git etiquette](#git-etiquette)
- [License](#license)
## Other helpful resources
More resources can be found in the nascent [developer documentation](devdocs/README.md) in this repo.
- [Developer FAQ](devdocs/FAQ.md)
- [Platform support policy](devdocs/PLATFORM_SUPPORT.md)
- [Our Rust style](devdocs/rust_style.md)
## Proposing design changes
First of all, before diving into the code, if you want to create a new feature, change something significantly, and especially if the change is user-facing, it is a good practice to first get an approval from the core team before starting to work on it. First of all, before diving into the code, if you want to create a new feature, change something significantly, and especially if the change is user-facing, it is a good practice to first get an approval from the core team before starting to work on it.
This saves both your and our time if we realize the change needs to go another direction before spending time on it. This saves both your and our time if we realize the change needs to go another direction before spending time on it.
@ -51,186 +33,69 @@ cargo build
### Tests ### Tests
It is good practice to cover your changes with a test. Also, try to think about corner cases and various ways how your changes could break. Cover those in the tests as well. It is a good practice to cover your changes with a test. Also, try to think about corner cases and various ways how your changes could break. Cover those in the tests as well.
Tests can be found in different places: Tests can be found in different places:
* `/tests` * `/tests`
* `src/tests`
* command examples * command examples
* crate-specific tests * crate-specific tests
Most of the tests are built upon the `nu-test-support` crate. For testing specific features, such as running Nushell in a REPL mode, we have so called "testbins". For simple tests, you can find `run_test()` and `fail_test()` functions. The most comprehensive test suite we have is the `nu-test-support` crate. For testing specific features, such as running Nushell in a REPL mode, we have so called "testbins". For simple tests, you can find `run_test()` and `fail_test()` functions.
### Useful Commands ### Useful Commands
As Nushell is built using a cargo workspace consisting of multiple crates keep in mind that you may need to pass additional flags compared to how you may be used to it from a single crate project.
Read cargo's documentation for more details: https://doc.rust-lang.org/cargo/reference/workspaces.html
- Build and run Nushell: - Build and run Nushell:
```nushell ```shell
cargo run cargo run
``` ```
- Build and run with dataframe support.
```shell
cargo run --features=dataframe
```
- Run Clippy on Nushell: - Run Clippy on Nushell:
```nushell ```shell
cargo clippy --workspace -- -D warnings -D clippy::unwrap_used cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A clippy::needless_collect
```
or via the `toolkit.nu` command:
```nushell
use toolkit.nu clippy
clippy
``` ```
- Run all tests: - Run all tests:
```nushell ```shell
cargo test --workspace cargo test --workspace
``` ```
or via the `toolkit.nu` command:
```nushell
use toolkit.nu test
test
```
- Run all tests for a specific command - Run all tests for a specific command
```nushell ```shell
cargo test --package nu-cli --test main -- commands::<command_name_here> cargo test --package nu-cli --test main -- commands::<command_name_here>
``` ```
- Check to see if there are code formatting issues - Check to see if there are code formatting issues
```nushell ```shell
cargo fmt --all -- --check cargo fmt --all -- --check
``` ```
or via the `toolkit.nu` command:
```nushell
use toolkit.nu fmt
fmt --check
```
- Format the code in the project - Format the code in the project
```nushell ```shell
cargo fmt --all cargo fmt --all
``` ```
or via the `toolkit.nu` command:
```nushell
use toolkit.nu fmt
fmt
```
- Set up `git` hooks to check formatting and run `clippy` before committing and pushing:
```nushell
use toolkit.nu setup-git-hooks
setup-git-hooks
```
_Unfortunately, this hook isn't available on Windows._
### Debugging Tips ### Debugging Tips
- To view verbose logs when developing, enable the `trace` log level. - To view verbose logs when developing, enable the `trace` log level.
```nushell ```shell
cargo run --release -- --log-level trace cargo run --release -- --log-level trace
``` ```
- To redirect trace logs to a file, enable the `--log-target file` switch. - To redirect trace logs to a file, enable the `--log-target file` switch.
```nushell ```shell
cargo run --release -- --log-level trace --log-target file cargo run --release -- --log-level trace --log-target file
open $"($nu.temp-path)/nu-($nu.pid).log" open $"($nu.temp-path)/nu-($nu.pid).log"
``` ```
## Git etiquette
As nushell thrives on its broad base of volunteer contributors and maintainers with different backgrounds we have a few guidelines for how we best utilize git and GitHub for our contributions. We strive to balance three goals with those recommendations:
1. The **volunteer maintainers and contributors** can easily follow the changes you propose, gauge the impact, and come to help you or make a decision.
2. **You as a contributor** can focus most of your time on improving the quality of the nushell project and contributing your expertise to the code or documentation.
3. Making sure we can trace back *why* decisions were made in the past.
This includes discarded approaches. Also we want to quickly identify regressions and fix when something broke.
### How we merge PRs
In general the maintainers **squash** all changes of your PR into a single commit when merging.
This keeps a clean enough linear history, while not forcing you to conform to a too strict style while iterating in your PR or fixing small problems. As an added benefit the commits on the `main` branch are tied to the discussion that happened in the PR through their `#1234` issue number.
> **Note**
> **Pro advice:** In some circumstances, we can agree on rebase-merging a particularly large but connected PR as a series of atomic commits onto the `main` branch to ensure we can more easily revert or bisect particular aspects.
### A good PR makes a change!
As a result of this PR-centric strategy and the general goal that the reviewers should easily understand your change, the **PR title and description matters** a great deal!
Make sure your description is **concise** but contains all relevant information and context.
This means demonstrating what changes, ideally through nushell code or output **examples**.
Furthermore links to technical documentation or instructions for folks that want to play with your change make the review process much easier.
> **Note**
> Try to follow the suggestions in our PR message template to make sure we can quickly focus on the technical merits and impact on the users.
#### A PR should limit itself to a single functional change or related set of same changes.
Mixing different changes in the same PR will make the review process much harder. A PR might get stuck on one aspect while we would actually like to land another change. Furthermore, if we are forced to revert a change, mixing and matching different aspects makes fixing bugs or regressions much harder.
Thus, please try to **separate out unrelated changes**!
**Don't** mix unrelated refactors with a potentially contested change.
Stylistic fixes and housekeeping can be bundled up into singular PRs.
#### Guidelines for the PR title
The PR title should be concise but contain everything for a contributor to know if they should help out in the review of this particular change.
**DON'T**
- `Update file/in/some/deeply/nested/path.rs`
- Why are you making this change?
- `Fix 2134`
- What has to be fixed?
- Hard to follow when not online on GitHub.
- ``Ignore `~` expansion``
- In what context should this change take effect?
- `[feature] refactor the whole parser and also make nushell indentation-sensitive, upgrade to using Cpython. Let me know what you think!`
- Be concise
- Maybe break up into smaller commits or PRs if the title already appears too long?
**DO**
- Mention the nushell feature or command that is affected.
- ``Fix URL parsing in `http get` (issue #1234)``
- You can mention the issue number if other context is there.
- In general, mention all related issues in the description to crosslink (e.g. `Fixes #1234`, `Closes #6789`)
- For internal changes mention the area or symbols affected if it helps to clarify
- ``Factor out `quote_string()` from parser to reuse in `explore` ``
### Review process / Merge conflicts
> **Note**
> Keep in mind that the maintainers are volunteers that need to allocate their attention to several different areas and active PRs. We will try to get back to you as soon as possible.
You can help us to make the review process a smooth experience:
- Testing:
- We generally review in detail after all the tests pass. Let us know if there is a problem you want to discuss to fix a test failure or forces us to accept a breaking change.
- If you fix a bug, it is highly recommended that you add a test that reproduces the original issue/panic in a minimal form.
- In general, added tests help us to understand which assumptions go into a particular addition/change.
- Try to also test corner cases where those assumptions might break. This can be more valuable than simply adding many similar tests.
- Commit history inside a PR during code review:
- Good **atomic commits** can help follow larger changes, but we are not pedantic.
- We don't shame fixup commits while you try to figure out a problem. They can help others see what you tried and what didn't work. (see our [squash policy](#how-we-merge-prs))
- During active review constant **force pushing** just to amend changes can be confusing!
- GitHub's UI presents reviewers with less options to compare diffs
- fetched branches for experimentation become invalid!
- the notification a maintainer receives has a low signal-to-noise ratio
- Git pros *can* use their judgement to rebase/squash to clean up the history *if it aids the understanding* of a larger change during review
- Merge conflicts:
- In general you should take care of resolving merge conflicts.
- Use your judgement whether to `git merge main` or to `git rebase main`
- Choose what simplifies having confidence in the conflict resolution and the review. **Merge commits in your branch are OK** in the squash model.
- Feel free to notify your reviewers or affected PR authors if your change might cause larger conflicts with another change.
- During the rollup of multiple PRs, we may choose to resolve merge conflicts and CI failures ourselves. (Allow maintainers to push to your branch to enable us to do this quickly.)
## License
We use the [MIT License](https://github.com/nushell/nushell/blob/main/LICENSE) in all of our Nushell projects. If you are including or referencing a crate that uses the [GPL License](https://www.gnu.org/licenses/gpl-3.0.en.html#license-text) unfortunately we will not be able to accept your PR.

6006
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,17 +1,16 @@
[package] [package]
authors = ["The Nushell Project Developers"] authors = ["The Nushell Project Developers"]
build = "scripts/build.rs"
default-run = "nu" default-run = "nu"
description = "A new type of shell" description = "A new type of shell"
documentation = "https://www.nushell.sh/book/" documentation = "https://www.nushell.sh/book/"
edition = "2021" edition = "2018"
exclude = ["images"] exclude = ["images"]
homepage = "https://www.nushell.sh" homepage = "https://www.nushell.sh"
license = "MIT" license = "MIT"
name = "nu" name = "nu"
repository = "https://github.com/nushell/nushell" repository = "https://github.com/nushell/nushell"
rust-version = "1.79.0" rust-version = "1.60"
version = "0.99.1" version = "0.72.1"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@ -24,269 +23,97 @@ pkg-fmt = "zip"
[workspace] [workspace]
members = [ members = [
"crates/nu-cli", "crates/nu-cli",
"crates/nu-engine", "crates/nu-engine",
"crates/nu-parser", "crates/nu-parser",
"crates/nu-system", "crates/nu-system",
"crates/nu-cmd-base", "crates/nu-command",
"crates/nu-cmd-extra", "crates/nu-protocol",
"crates/nu-cmd-lang", "crates/nu-plugin",
"crates/nu-cmd-plugin", "crates/nu_plugin_inc",
"crates/nu-command", "crates/nu_plugin_gstat",
"crates/nu-color-config", "crates/nu_plugin_example",
"crates/nu-explore", "crates/nu_plugin_query",
"crates/nu-json", "crates/nu_plugin_custom_values",
"crates/nu-lsp", "crates/nu-utils",
"crates/nu-pretty-hex",
"crates/nu-protocol",
"crates/nu-derive-value",
"crates/nu-plugin",
"crates/nu-plugin-core",
"crates/nu-plugin-engine",
"crates/nu-plugin-protocol",
"crates/nu-plugin-test-support",
"crates/nu_plugin_inc",
"crates/nu_plugin_gstat",
"crates/nu_plugin_example",
"crates/nu_plugin_query",
"crates/nu_plugin_custom_values",
"crates/nu_plugin_formats",
"crates/nu_plugin_polars",
"crates/nu_plugin_stress_internals",
"crates/nu-std",
"crates/nu-table",
"crates/nu-term-grid",
"crates/nu-test-support",
"crates/nu-utils",
"crates/nuon",
] ]
[workspace.dependencies]
alphanumeric-sort = "1.5"
ansi-str = "0.8"
anyhow = "1.0.82"
base64 = "0.22.1"
bracoxide = "0.1.2"
brotli = "5.0"
byteorder = "1.5"
bytes = "1"
bytesize = "1.3"
calamine = "0.24.0"
chardetng = "0.1.17"
chrono = { default-features = false, version = "0.4.34" }
chrono-humanize = "0.2.3"
chrono-tz = "0.8"
crossbeam-channel = "0.5.8"
crossterm = "0.28.1"
csv = "1.3"
ctrlc = "3.4"
dialoguer = { default-features = false, version = "0.11" }
digest = { default-features = false, version = "0.10" }
dirs = "5.0"
dirs-sys = "0.4"
dtparse = "2.0"
encoding_rs = "0.8"
fancy-regex = "0.13"
filesize = "0.2"
filetime = "0.2"
fuzzy-matcher = "0.3"
heck = "0.5.0"
human-date-parser = "0.2.0"
indexmap = "2.6"
indicatif = "0.17"
interprocess = "2.2.0"
is_executable = "1.0"
itertools = "0.13"
libc = "0.2"
libproc = "0.14"
log = "0.4"
lru = "0.12"
lscolors = { version = "0.17", default-features = false }
lsp-server = "0.7.5"
lsp-types = "0.95.0"
mach2 = "0.4"
md5 = { version = "0.10", package = "md-5" }
miette = "7.2"
mime = "0.3.17"
mime_guess = "2.0"
mockito = { version = "1.5", default-features = false }
multipart-rs = "0.1.11"
native-tls = "0.2"
nix = { version = "0.29", default-features = false }
notify-debouncer-full = { version = "0.3", default-features = false }
nu-ansi-term = "0.50.1"
num-format = "0.4"
num-traits = "0.2"
omnipath = "0.1"
once_cell = "1.20"
open = "5.3"
os_pipe = { version = "1.2", features = ["io_safety"] }
pathdiff = "0.2"
percent-encoding = "2"
pretty_assertions = "1.4"
print-positions = "0.6"
proc-macro-error = { version = "1.0", default-features = false }
proc-macro2 = "1.0"
procfs = "0.16.0"
pwd = "1.3"
quick-xml = "0.32.0"
quickcheck = "1.0"
quickcheck_macros = "1.0"
quote = "1.0"
rand = "0.8"
rand_chacha = "0.3.1"
ratatui = "0.26"
rayon = "1.10"
reedline = "0.36.0"
regex = "1.9.5"
rmp = "0.8"
rmp-serde = "1.3"
ropey = "1.6.1"
roxmltree = "0.19"
rstest = { version = "0.18", default-features = false }
rusqlite = "0.31"
rust-embed = "8.5.0"
serde = { version = "1.0" }
serde_json = "1.0"
serde_urlencoded = "0.7.1"
serde_yaml = "0.9"
sha2 = "0.10"
strip-ansi-escapes = "0.2.0"
syn = "2.0"
sysinfo = "0.30"
tabled = { version = "0.16.0", default-features = false }
tempfile = "3.13"
terminal_size = "0.3"
titlecase = "2.0"
toml = "0.8"
trash = "3.3"
umask = "2.1"
unicode-segmentation = "1.12"
unicode-width = "0.1"
ureq = { version = "2.10", default-features = false }
url = "2.2"
uu_cp = "0.0.27"
uu_mkdir = "0.0.27"
uu_mktemp = "0.0.27"
uu_mv = "0.0.27"
uu_whoami = "0.0.27"
uu_uname = "0.0.27"
uucore = "0.0.27"
uuid = "1.10.0"
v_htmlescape = "0.15.0"
wax = "0.6"
which = "6.0.0"
windows = "0.54"
windows-sys = "0.48"
winreg = "0.52"
[workspace.lints.clippy]
# Warning: workspace lints affect library code as well as tests, so don't enable lints that would be too noisy in tests like that.
# todo = "warn"
unchecked_duration_subtraction = "warn"
[lints]
workspace = true
[dependencies] [dependencies]
nu-cli = { path = "./crates/nu-cli", version = "0.99.1" } chrono = { version = "0.4.23", features = ["serde"] }
nu-cmd-base = { path = "./crates/nu-cmd-base", version = "0.99.1" } crossterm = "0.24.0"
nu-cmd-lang = { path = "./crates/nu-cmd-lang", version = "0.99.1" } ctrlc = "3.2.1"
nu-cmd-plugin = { path = "./crates/nu-cmd-plugin", version = "0.99.1", optional = true } log = "0.4"
nu-cmd-extra = { path = "./crates/nu-cmd-extra", version = "0.99.1" } miette = { version = "5.1.0", features = ["fancy-no-backtrace"] }
nu-command = { path = "./crates/nu-command", version = "0.99.1" } nu-ansi-term = "0.46.0"
nu-engine = { path = "./crates/nu-engine", version = "0.99.1" } nu-cli = { path="./crates/nu-cli", version = "0.72.1" }
nu-explore = { path = "./crates/nu-explore", version = "0.99.1" } nu-color-config = { path = "./crates/nu-color-config", version = "0.72.1" }
nu-lsp = { path = "./crates/nu-lsp/", version = "0.99.1" } nu-command = { path="./crates/nu-command", version = "0.72.1" }
nu-parser = { path = "./crates/nu-parser", version = "0.99.1" } nu-engine = { path="./crates/nu-engine", version = "0.72.1" }
nu-path = { path = "./crates/nu-path", version = "0.99.1" } nu-json = { path="./crates/nu-json", version = "0.72.1" }
nu-plugin-engine = { path = "./crates/nu-plugin-engine", optional = true, version = "0.99.1" } nu-parser = { path="./crates/nu-parser", version = "0.72.1" }
nu-protocol = { path = "./crates/nu-protocol", version = "0.99.1" } nu-path = { path="./crates/nu-path", version = "0.72.1" }
nu-std = { path = "./crates/nu-std", version = "0.99.1" } nu-plugin = { path = "./crates/nu-plugin", optional = true, version = "0.72.1" }
nu-system = { path = "./crates/nu-system", version = "0.99.1" } nu-pretty-hex = { path = "./crates/nu-pretty-hex", version = "0.72.1" }
nu-utils = { path = "./crates/nu-utils", version = "0.99.1" } nu-protocol = { path = "./crates/nu-protocol", version = "0.72.1" }
reedline = { workspace = true, features = ["bashisms", "sqlite"] } nu-system = { path = "./crates/nu-system", version = "0.72.1" }
nu-table = { path = "./crates/nu-table", version = "0.72.1" }
nu-term-grid = { path = "./crates/nu-term-grid", version = "0.72.1" }
nu-utils = { path = "./crates/nu-utils", version = "0.72.1" }
reedline = { version = "0.14.0", features = ["bashisms", "sqlite"]}
crossterm = { workspace = true } rayon = "1.5.1"
ctrlc = { workspace = true } is_executable = "1.0.1"
dirs = { workspace = true } simplelog = "0.12.0"
log = { workspace = true } time = "0.3.12"
miette = { workspace = true, features = ["fancy-no-backtrace", "fancy"] }
mimalloc = { version = "0.1.42", default-features = false, optional = true }
multipart-rs = { workspace = true }
serde_json = { workspace = true }
simplelog = "0.12"
time = "0.3"
[target.'cfg(not(target_os = "windows"))'.dependencies] [target.'cfg(not(target_os = "windows"))'.dependencies]
# Our dependencies don't use OpenSSL on Windows # Our dependencies don't use OpenSSL on Windows
openssl = { version = "0.10", features = ["vendored"], optional = true } openssl = { version = "0.10.38", features = ["vendored"], optional = true }
signal-hook = { version = "0.3.14", default-features = false }
[target.'cfg(windows)'.build-dependencies] [target.'cfg(windows)'.build-dependencies]
winresource = "0.1" winres = "0.1"
[target.'cfg(target_family = "unix")'.dependencies] [target.'cfg(target_family = "unix")'.dependencies]
nix = { workspace = true, default-features = false, features = [ nix = { version = "0.25", default-features = false, features = ["signal", "process", "fs", "term"]}
"signal", atty = "0.2"
"process",
"fs",
"term",
] }
[dev-dependencies] [dev-dependencies]
nu-test-support = { path = "./crates/nu-test-support", version = "0.99.1" } nu-test-support = { path="./crates/nu-test-support", version = "0.72.1" }
nu-plugin-protocol = { path = "./crates/nu-plugin-protocol", version = "0.99.1" } tempfile = "3.2.0"
nu-plugin-core = { path = "./crates/nu-plugin-core", version = "0.99.1" } assert_cmd = "2.0.2"
assert_cmd = "2.0" pretty_assertions = "1.0.0"
dirs = { workspace = true } serial_test = "0.8.0"
tango-bench = "0.6" hamcrest2 = "0.3.0"
pretty_assertions = { workspace = true } rstest = {version = "0.15.0", default-features = false}
regex = { workspace = true } itertools = "0.10.3"
rstest = { workspace = true, default-features = false }
serial_test = "3.1"
tempfile = { workspace = true }
[features] [features]
plugin = [ plugin = ["nu-plugin", "nu-cli/plugin", "nu-parser/plugin", "nu-command/plugin", "nu-protocol/plugin", "nu-engine/plugin"]
"nu-plugin-engine", # extra used to be more useful but now it's the same as default. Leaving it in for backcompat with existing build scripts
"nu-cmd-plugin", extra = ["default"]
"nu-cli/plugin", default = ["plugin", "which-support", "trash-support", "sqlite"]
"nu-parser/plugin",
"nu-command/plugin",
"nu-protocol/plugin",
"nu-engine/plugin",
]
default = [
"plugin",
"trash-support",
"sqlite",
"mimalloc",
]
stable = ["default"] stable = ["default"]
# NOTE: individual features are also passed to `nu-cmd-lang` that uses them to generate the feature matrix in the `version` command wasi = []
# Enable to statically link OpenSSL (perl is required, to build OpenSSL https://docs.rs/openssl/latest/openssl/); # Enable to statically link OpenSSL; otherwise the system version will be used. Not enabled by default because it takes a while to build
# otherwise the system version will be used. Not enabled by default because it takes a while to build static-link-openssl = ["dep:openssl"]
static-link-openssl = ["dep:openssl", "nu-cmd-lang/static-link-openssl"]
mimalloc = ["nu-cmd-lang/mimalloc", "dep:mimalloc"]
# Optional system clipboard support in `reedline`, this behavior has problematic compatibility with some systems.
# Missing X server/ Wayland can cause issues
system-clipboard = [
"reedline/system_clipboard",
"nu-cli/system-clipboard",
"nu-cmd-lang/system-clipboard",
]
# Stable (Default) # Stable (Default)
trash-support = ["nu-command/trash-support", "nu-cmd-lang/trash-support"] which-support = ["nu-command/which-support"]
trash-support = ["nu-command/trash-support"]
# Extra
# Dataframe feature for nushell
dataframe = ["nu-command/dataframe"]
# SQLite commands for nushell # SQLite commands for nushell
sqlite = ["nu-command/sqlite", "nu-cmd-lang/sqlite"] sqlite = ["nu-command/sqlite"]
[profile.release] [profile.release]
opt-level = "s" # Optimize for size opt-level = "s" # Optimize for size
strip = "debuginfo" strip = "debuginfo"
lto = "thin" lto = "thin"
@ -308,16 +135,8 @@ debug = false
[[bin]] [[bin]]
name = "nu" name = "nu"
path = "src/main.rs" path = "src/main.rs"
bench = false
# To use a development version of a dependency please use a global override here # To use a development version of a dependency please use a global override here
# changing versions in each sub-crate of the workspace is tedious # changing versions in each sub-crate of the workspace is tedious
[patch.crates-io] [patch.crates-io]
# reedline = { git = "https://github.com/nushell/reedline", branch = "main" } # reedline = { git = "https://github.com/nushell/reedline.git", branch = "main" }
# nu-ansi-term = {git = "https://github.com/nushell/nu-ansi-term.git", branch = "main"}
# Run all benchmarks with `cargo bench`
# Run individual benchmarks like `cargo bench -- <regex>` e.g. `cargo bench -- parse`
[[bench]]
name = "benchmarks"
harness = false

View File

@ -1,18 +0,0 @@
# Configuration for cross-rs: https://github.com/cross-rs/cross
# Run cross-rs like this:
# cross build --target aarch64-unknown-linux-gnu --release
# or
# cross build --target aarch64-unknown-linux-musl --release --features=static-link-openssl
[target.aarch64-unknown-linux-gnu]
pre-build = [
"dpkg --add-architecture $CROSS_DEB_ARCH",
"apt-get update && apt-get install --assume-yes libssl-dev:$CROSS_DEB_ARCH clang"
]
# NOTE: for musl you will need to build with --features=static-link-openssl
[target.aarch64-unknown-linux-musl]
pre-build = [
"dpkg --add-architecture $CROSS_DEB_ARCH",
"apt-get update && apt-get install --assume-yes clang"
]

View File

@ -1,6 +1,6 @@
MIT License MIT License
Copyright (c) 2019 - 2023 The Nushell Project Developers Copyright (c) 2019 - 2022 The Nushell Project Developers
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

View File

@ -1,28 +1,27 @@
# Nushell <!-- omit in toc --> # Nushell <!-- omit in toc -->
[![Crates.io](https://img.shields.io/crates/v/nu.svg)](https://crates.io/crates/nu) [![Crates.io](https://img.shields.io/crates/v/nu.svg)](https://crates.io/crates/nu)
[![Build Status](https://img.shields.io/github/actions/workflow/status/nushell/nushell/ci.yml?branch=main)](https://github.com/nushell/nushell/actions) ![Build Status](https://img.shields.io/github/workflow/status/nushell/nushell/continuous-integration)
[![Nightly Build](https://github.com/nushell/nushell/actions/workflows/nightly-build.yml/badge.svg)](https://github.com/nushell/nushell/actions/workflows/nightly-build.yml)
[![Discord](https://img.shields.io/discord/601130461678272522.svg?logo=discord)](https://discord.gg/NtAbbGn) [![Discord](https://img.shields.io/discord/601130461678272522.svg?logo=discord)](https://discord.gg/NtAbbGn)
[![The Changelog #363](https://img.shields.io/badge/The%20Changelog-%23363-61c192.svg)](https://changelog.com/podcast/363) [![The Changelog #363](https://img.shields.io/badge/The%20Changelog-%23363-61c192.svg)](https://changelog.com/podcast/363)
[![@nu_shell](https://img.shields.io/badge/twitter-@nu_shell-1DA1F3?style=flat-square)](https://twitter.com/nu_shell) [![@nu_shell](https://img.shields.io/badge/twitter-@nu_shell-1DA1F3?style=flat-square)](https://twitter.com/nu_shell)
[![GitHub commit activity](https://img.shields.io/github/commit-activity/m/nushell/nushell)](https://github.com/nushell/nushell/graphs/commit-activity) ![GitHub commit activity](https://img.shields.io/github/commit-activity/m/nushell/nushell)
[![GitHub contributors](https://img.shields.io/github/contributors/nushell/nushell)](https://github.com/nushell/nushell/graphs/contributors) ![GitHub contributors](https://img.shields.io/github/contributors/nushell/nushell)
A new type of shell. A new type of shell.
![Example of nushell](assets/nushell-autocomplete6.gif "Example of nushell") ![Example of nushell](images/nushell-autocomplete6.gif "Example of nushell")
## Table of Contents <!-- omit in toc --> ## Table of Contents <!-- omit in toc -->
- [Status](#status) - [Status](#status)
- [Learning About Nu](#learning-about-nu) - [Learning About Nu](#learning-about-nu)
- [Installation](#installation) - [Installation](#installation)
- [Configuration](#configuration)
- [Philosophy](#philosophy) - [Philosophy](#philosophy)
- [Pipelines](#pipelines) - [Pipelines](#pipelines)
- [Opening files](#opening-files) - [Opening files](#opening-files)
- [Plugins](#plugins) - [Plugins](#plugins)
- [Goals](#goals) - [Goals](#goals)
- [Progress](#progress)
- [Officially Supported By](#officially-supported-by) - [Officially Supported By](#officially-supported-by)
- [Contributing](#contributing) - [Contributing](#contributing)
- [License](#license) - [License](#license)
@ -33,7 +32,7 @@ This project has reached a minimum-viable-product level of quality. Many people
## Learning About Nu ## Learning About Nu
The [Nushell book](https://www.nushell.sh/book/) is the primary source of Nushell documentation. You can find [a full list of Nu commands in the book](https://www.nushell.sh/commands/), and we have many examples of using Nu in our [cookbook](https://www.nushell.sh/cookbook/). The [Nushell book](https://www.nushell.sh/book/) is the primary source of Nushell documentation. You can find [a full list of Nu commands in the book](https://www.nushell.sh/book/command_reference.html), and we have many examples of using Nu in our [cookbook](https://www.nushell.sh/cookbook/).
We're also active on [Discord](https://discord.gg/NtAbbGn) and [Twitter](https://twitter.com/nu_shell); come and chat with us! We're also active on [Discord](https://discord.gg/NtAbbGn) and [Twitter](https://twitter.com/nu_shell); come and chat with us!
@ -48,29 +47,12 @@ brew install nushell
winget install nushell winget install nushell
``` ```
To use `Nu` in GitHub Action, check [setup-nu](https://github.com/marketplace/actions/setup-nu) for more detail. To use `Nu` in Github Action, check [setup-nu](https://github.com/marketplace/actions/setup-nu) for more detail.
Detailed installation instructions can be found in the [installation chapter of the book](https://www.nushell.sh/book/installation.html). Nu is available via many package managers: Detailed installation instructions can be found in the [installation chapter of the book](https://www.nushell.sh/book/installation.html). Nu is available via many package managers:
[![Packaging status](https://repology.org/badge/vertical-allrepos/nushell.svg?columns=3)](https://repology.org/project/nushell/versions) [![Packaging status](https://repology.org/badge/vertical-allrepos/nushell.svg)](https://repology.org/project/nushell/versions)
For details about which platforms the Nushell team actively supports, see [our platform support policy](devdocs/PLATFORM_SUPPORT.md).
## Configuration
The default configurations can be found at [sample_config](crates/nu-utils/src/sample_config)
which are the configuration files one gets when they startup Nushell for the first time.
It sets all of the default configuration to run Nushell. From here one can
then customize this file for their specific needs.
To see where *config.nu* is located on your system simply type this command.
```rust
$nu.config-path
```
Please see our [book](https://www.nushell.sh) for all of the Nushell documentation.
## Philosophy ## Philosophy
@ -192,14 +174,11 @@ These binaries interact with nu via a simple JSON-RPC protocol where the command
If the plugin is a filter, data streams to it one element at a time, and it can stream data back in return via stdin/stdout. If the plugin is a filter, data streams to it one element at a time, and it can stream data back in return via stdin/stdout.
If the plugin is a sink, it is given the full vector of final data and is given free reign over stdin/stdout to use as it pleases. If the plugin is a sink, it is given the full vector of final data and is given free reign over stdin/stdout to use as it pleases.
The [awesome-nu repo](https://github.com/nushell/awesome-nu#plugins) lists a variety of nu-plugins while the [showcase repo](https://github.com/nushell/showcase) *shows* off informative blog posts that have been written about Nushell along with videos that highlight technical
topics that have been presented.
## Goals ## Goals
Nu adheres closely to a set of goals that make up its design philosophy. As features are added, they are checked against these goals. Nu adheres closely to a set of goals that make up its design philosophy. As features are added, they are checked against these goals.
- First and foremost, Nu is cross-platform. Commands and techniques should work across platforms and Nu has [first-class support for Windows, macOS, and Linux](devdocs/PLATFORM_SUPPORT.md). - First and foremost, Nu is cross-platform. Commands and techniques should work across platforms and Nu has first-class support for Windows, macOS, and Linux.
- Nu ensures compatibility with existing platform-specific executables. - Nu ensures compatibility with existing platform-specific executables.
@ -209,6 +188,27 @@ Nu adheres closely to a set of goals that make up its design philosophy. As feat
- Finally, Nu views data functionally. Rather than using mutation, pipelines act as a means to load, change, and save data without mutable state. - Finally, Nu views data functionally. Rather than using mutation, pipelines act as a means to load, change, and save data without mutable state.
## Progress
Nu is under heavy development and will naturally change as it matures. The chart below isn't meant to be exhaustive, but it helps give an idea for some of the areas of development and their relative maturity:
| Features | Not started | Prototype | MVP | Preview | Mature | Notes |
| ------------- | :---------: | :-------: | :-: | :-----: | :----: | -------------------------------------------------------------------- |
| Aliases | | | | X | | Aliases allow for shortening large commands, while passing flags |
| Notebook | | X | | | | Initial jupyter support, but it loses state and lacks features |
| File ops | | | | X | | cp, mv, rm, mkdir have some support, but lacking others |
| Environment | | | | X | | Temporary environment and scoped environment variables |
| Shells | | | | X | | Basic value and file shells, but no opt-in/opt-out for commands |
| Protocol | | | | X | | Streaming protocol is serviceable |
| Plugins | | | X | | | Plugins work on one row at a time, lack batching and expression eval |
| Errors | | | | X | | Error reporting works, but could use usability polish |
| Documentation | | | X | | | Book updated to latest release, including usage examples |
| Paging | | | | X | | Textview has paging, but we'd like paging for tables |
| Functions | | | | X | | Functions and aliases are supported |
| Variables | | | | X | | Nu supports variables and environment variables |
| Completions | | | | X | | Completions for filepaths |
| Type-checking | | | | x | | Commands check basic types, and input/output types |
## Officially Supported By ## Officially Supported By
Please submit an issue or PR to be added to this list. Please submit an issue or PR to be added to this list.
@ -218,18 +218,13 @@ Please submit an issue or PR to be added to this list.
- [oh-my-posh](https://ohmyposh.dev) - [oh-my-posh](https://ohmyposh.dev)
- [Couchbase Shell](https://couchbase.sh) - [Couchbase Shell](https://couchbase.sh)
- [virtualenv](https://github.com/pypa/virtualenv) - [virtualenv](https://github.com/pypa/virtualenv)
- [atuin](https://github.com/ellie/atuin)
- [clap](https://github.com/clap-rs/clap/tree/master/clap_complete_nushell)
- [Dorothy](http://github.com/bevry/dorothy)
- [Direnv](https://github.com/direnv/direnv/blob/master/docs/hook.md#nushell)
- [x-cmd](https://x-cmd.com/mod/nu)
## Contributing ## Contributing
See [Contributing](CONTRIBUTING.md) for details. Thanks to all the people who already contributed! See [Contributing](CONTRIBUTING.md) for details. Thanks to all the people who already contributed!
<a href="https://github.com/nushell/nushell/graphs/contributors"> <a href="https://github.com/nushell/nushell/graphs/contributors">
<img src="https://contributors-img.web.app/image?repo=nushell/nushell&max=750" /> <img src="https://contributors-img.web.app/image?repo=nushell/nushell&max=500" />
</a> </a>
## License ## License

3
README.release.txt Normal file
View File

@ -0,0 +1,3 @@
To use Nu plugins, use the register command to tell Nu where to find the plugin. For example:
> register ./nu_plugin_query

View File

@ -1,29 +0,0 @@
# Security Policy
As a shell and programming language Nushell provides you with great powers and the potential to do dangerous things to your computer and data. Whenever there is a risk that a malicious actor can abuse a bug or a violation of documented behavior/assumptions in Nushell to harm you this is a *security* risk.
We want to fix those issues without exposing our users to unnecessary risk. Thus we want to explain our security policy.
Additional issues may be part of *safety* where the behavior of Nushell as designed and implemented can cause unintended harm or a bug causes damage without the involvement of a third party.
## Supported Versions
As Nushell is still under very active pre-stable development, the only version the core team prioritizes for security and safety fixes is the [most recent version as published on GitHub](https://github.com/nushell/nushell/releases/latest).
Only if you provide a strong reasoning and the necessary resources, will we consider blessing a backported fix with an official patch release for a previous version.
## Reporting a Vulnerability
If you suspect that a bug or behavior of Nushell can affect security or may be potentially exploitable, please report the issue to us in private.
Either reach out to the core team on [our Discord server](https://discord.gg/NtAbbGn) to arrange a private channel or use the [GitHub vulnerability reporting form](https://github.com/nushell/nushell/security/advisories/new).
Please try to answer the following questions:
- How can we reach you for further questions?
- What is the bug? Which system of Nushell may be affected?
- Do you have proof-of-concept for a potential exploit or have you observed an exploit in the wild?
- What is your assessment of the severity based on what could be impacted should the bug be exploited?
- Are additional people aware of the issue or deserve credit for identifying the issue?
We will try to get back to you within a week with:
- acknowledging the receipt of the report
- an initial plan of how we want to address this including the primary points of contact for further communication
- our preliminary assessment of how severe we judge the issue
- a proposal for how we can coordinate responsible disclosure (e.g. how we ship the bugfix, if we need to coordinate with distribution maintainers, when you can release a blog post if you want to etc.)
For purely *safety* related issues where the impact is severe by direct user action instead of malicious input or third parties, feel free to open a regular issue. If we deem that there may be an additional *security* risk on a *safety* issue we may continue discussions in a restricted forum.

View File

@ -1,7 +0,0 @@
# Divan benchmarks
These are benchmarks using [Divan](https://github.com/nvzqz/divan), a microbenchmarking tool for Rust.
Run all benchmarks with `cargo bench`
Or run individual benchmarks like `cargo bench -- <regex>` e.g. `cargo bench -- parse`

View File

@ -1,492 +0,0 @@
use nu_cli::{eval_source, evaluate_commands};
use nu_plugin_core::{Encoder, EncodingType};
use nu_plugin_protocol::{PluginCallResponse, PluginOutput};
use nu_protocol::{
engine::{EngineState, Stack},
PipelineData, Signals, Span, Spanned, Value,
};
use nu_std::load_standard_library;
use nu_utils::{get_default_config, get_default_env};
use std::{
rc::Rc,
sync::{atomic::AtomicBool, Arc},
};
use std::hint::black_box;
use tango_bench::{benchmark_fn, tango_benchmarks, tango_main, IntoBenchmarks};
fn load_bench_commands() -> EngineState {
nu_command::add_shell_command_context(nu_cmd_lang::create_default_context())
}
fn setup_engine() -> EngineState {
let mut engine_state = load_bench_commands();
let cwd = std::env::current_dir()
.unwrap()
.into_os_string()
.into_string()
.unwrap();
// parsing config.nu breaks without PWD set, so set a valid path
engine_state.add_env_var("PWD".into(), Value::string(cwd, Span::test_data()));
engine_state.generate_nu_constant();
engine_state
}
fn setup_stack_and_engine_from_command(command: &str) -> (Stack, EngineState) {
let mut engine = setup_engine();
let commands = Spanned {
span: Span::unknown(),
item: command.to_string(),
};
let mut stack = Stack::new();
// Support running benchmarks without IR mode
stack.use_ir = std::env::var_os("NU_DISABLE_IR").is_none();
evaluate_commands(
&commands,
&mut engine,
&mut stack,
PipelineData::empty(),
Default::default(),
)
.unwrap();
(stack, engine)
}
// generate a new table data with `row_cnt` rows, `col_cnt` columns.
fn encoding_test_data(row_cnt: usize, col_cnt: usize) -> Value {
let record = Value::test_record(
(0..col_cnt)
.map(|x| (format!("col_{x}"), Value::test_int(x as i64)))
.collect(),
);
Value::list(vec![record; row_cnt], Span::test_data())
}
fn bench_command(
name: &str,
command: &str,
stack: Stack,
engine: EngineState,
) -> impl IntoBenchmarks {
let commands = Spanned {
span: Span::unknown(),
item: command.to_string(),
};
[benchmark_fn(name, move |b| {
let commands = commands.clone();
let stack = stack.clone();
let engine = engine.clone();
b.iter(move || {
let mut stack = stack.clone();
let mut engine = engine.clone();
#[allow(clippy::unit_arg)]
black_box(
evaluate_commands(
&commands,
&mut engine,
&mut stack,
PipelineData::empty(),
Default::default(),
)
.unwrap(),
);
})
})]
}
fn bench_eval_source(
name: &str,
fname: String,
source: Vec<u8>,
stack: Stack,
engine: EngineState,
) -> impl IntoBenchmarks {
[benchmark_fn(name, move |b| {
let stack = stack.clone();
let engine = engine.clone();
let fname = fname.clone();
let source = source.clone();
b.iter(move || {
let mut stack = stack.clone();
let mut engine = engine.clone();
let fname: &str = &fname.clone();
let source: &[u8] = &source.clone();
black_box(eval_source(
&mut engine,
&mut stack,
source,
fname,
PipelineData::empty(),
false,
));
})
})]
}
/// Load the standard library into the engine.
fn bench_load_standard_lib() -> impl IntoBenchmarks {
[benchmark_fn("load_standard_lib", move |b| {
let engine = setup_engine();
b.iter(move || {
let mut engine = engine.clone();
load_standard_library(&mut engine)
})
})]
}
fn create_flat_record_string(n: i32) -> String {
let mut s = String::from("let record = {");
for i in 0..n {
s.push_str(&format!("col_{}: {}", i, i));
if i < n - 1 {
s.push_str(", ");
}
}
s.push('}');
s
}
fn create_nested_record_string(depth: i32) -> String {
let mut s = String::from("let record = {");
for _ in 0..depth {
s.push_str("col: {");
}
s.push_str("col_final: 0");
for _ in 0..depth {
s.push('}');
}
s.push('}');
s
}
fn create_example_table_nrows(n: i32) -> String {
let mut s = String::from("let table = [[foo bar baz]; ");
for i in 0..n {
s.push_str(&format!("[0, 1, {i}]"));
if i < n - 1 {
s.push_str(", ");
}
}
s.push(']');
s
}
fn bench_record_create(n: i32) -> impl IntoBenchmarks {
bench_command(
&format!("record_create_{n}"),
&create_flat_record_string(n),
Stack::new(),
setup_engine(),
)
}
fn bench_record_flat_access(n: i32) -> impl IntoBenchmarks {
let setup_command = create_flat_record_string(n);
let (stack, engine) = setup_stack_and_engine_from_command(&setup_command);
bench_command(
&format!("record_flat_access_{n}"),
"$record.col_0 | ignore",
stack,
engine,
)
}
fn bench_record_nested_access(n: i32) -> impl IntoBenchmarks {
let setup_command = create_nested_record_string(n);
let (stack, engine) = setup_stack_and_engine_from_command(&setup_command);
let nested_access = ".col".repeat(n as usize);
bench_command(
&format!("record_nested_access_{n}"),
&format!("$record{} | ignore", nested_access),
stack,
engine,
)
}
fn bench_table_create(n: i32) -> impl IntoBenchmarks {
bench_command(
&format!("table_create_{n}"),
&create_example_table_nrows(n),
Stack::new(),
setup_engine(),
)
}
fn bench_table_get(n: i32) -> impl IntoBenchmarks {
let setup_command = create_example_table_nrows(n);
let (stack, engine) = setup_stack_and_engine_from_command(&setup_command);
bench_command(
&format!("table_get_{n}"),
"$table | get bar | math sum | ignore",
stack,
engine,
)
}
fn bench_table_select(n: i32) -> impl IntoBenchmarks {
let setup_command = create_example_table_nrows(n);
let (stack, engine) = setup_stack_and_engine_from_command(&setup_command);
bench_command(
&format!("table_select_{n}"),
"$table | select foo baz | ignore",
stack,
engine,
)
}
fn bench_eval_interleave(n: i32) -> impl IntoBenchmarks {
let engine = setup_engine();
let stack = Stack::new();
bench_command(
&format!("eval_interleave_{n}"),
&format!("seq 1 {n} | wrap a | interleave {{ seq 1 {n} | wrap b }} | ignore"),
stack,
engine,
)
}
fn bench_eval_interleave_with_interrupt(n: i32) -> impl IntoBenchmarks {
let mut engine = setup_engine();
engine.set_signals(Signals::new(Arc::new(AtomicBool::new(false))));
let stack = Stack::new();
bench_command(
&format!("eval_interleave_with_interrupt_{n}"),
&format!("seq 1 {n} | wrap a | interleave {{ seq 1 {n} | wrap b }} | ignore"),
stack,
engine,
)
}
fn bench_eval_for(n: i32) -> impl IntoBenchmarks {
let engine = setup_engine();
let stack = Stack::new();
bench_command(
&format!("eval_for_{n}"),
&format!("(for $x in (1..{n}) {{ 1 }}) | ignore"),
stack,
engine,
)
}
fn bench_eval_each(n: i32) -> impl IntoBenchmarks {
let engine = setup_engine();
let stack = Stack::new();
bench_command(
&format!("eval_each_{n}"),
&format!("(1..{n}) | each {{|_| 1 }} | ignore"),
stack,
engine,
)
}
fn bench_eval_par_each(n: i32) -> impl IntoBenchmarks {
let engine = setup_engine();
let stack = Stack::new();
bench_command(
&format!("eval_par_each_{n}"),
&format!("(1..{}) | par-each -t 2 {{|_| 1 }} | ignore", n),
stack,
engine,
)
}
fn bench_eval_default_config() -> impl IntoBenchmarks {
let default_env = get_default_config().as_bytes().to_vec();
let fname = "default_config.nu".to_string();
bench_eval_source(
"eval_default_config",
fname,
default_env,
Stack::new(),
setup_engine(),
)
}
fn bench_eval_default_env() -> impl IntoBenchmarks {
let default_env = get_default_env().as_bytes().to_vec();
let fname = "default_env.nu".to_string();
bench_eval_source(
"eval_default_env",
fname,
default_env,
Stack::new(),
setup_engine(),
)
}
fn encode_json(row_cnt: usize, col_cnt: usize) -> impl IntoBenchmarks {
let test_data = Rc::new(PluginOutput::CallResponse(
0,
PluginCallResponse::value(encoding_test_data(row_cnt, col_cnt)),
));
let encoder = Rc::new(EncodingType::try_from_bytes(b"json").unwrap());
[benchmark_fn(
format!("encode_json_{}_{}", row_cnt, col_cnt),
move |b| {
let encoder = encoder.clone();
let test_data = test_data.clone();
b.iter(move || {
let mut res = Vec::new();
encoder.encode(&*test_data, &mut res).unwrap();
})
},
)]
}
fn encode_msgpack(row_cnt: usize, col_cnt: usize) -> impl IntoBenchmarks {
let test_data = Rc::new(PluginOutput::CallResponse(
0,
PluginCallResponse::value(encoding_test_data(row_cnt, col_cnt)),
));
let encoder = Rc::new(EncodingType::try_from_bytes(b"msgpack").unwrap());
[benchmark_fn(
format!("encode_msgpack_{}_{}", row_cnt, col_cnt),
move |b| {
let encoder = encoder.clone();
let test_data = test_data.clone();
b.iter(move || {
let mut res = Vec::new();
encoder.encode(&*test_data, &mut res).unwrap();
})
},
)]
}
fn decode_json(row_cnt: usize, col_cnt: usize) -> impl IntoBenchmarks {
let test_data = PluginOutput::CallResponse(
0,
PluginCallResponse::value(encoding_test_data(row_cnt, col_cnt)),
);
let encoder = EncodingType::try_from_bytes(b"json").unwrap();
let mut res = vec![];
encoder.encode(&test_data, &mut res).unwrap();
[benchmark_fn(
format!("decode_json_{}_{}", row_cnt, col_cnt),
move |b| {
let res = res.clone();
b.iter(move || {
let mut binary_data = std::io::Cursor::new(res.clone());
binary_data.set_position(0);
let _: Result<Option<PluginOutput>, _> =
black_box(encoder.decode(&mut binary_data));
})
},
)]
}
fn decode_msgpack(row_cnt: usize, col_cnt: usize) -> impl IntoBenchmarks {
let test_data = PluginOutput::CallResponse(
0,
PluginCallResponse::value(encoding_test_data(row_cnt, col_cnt)),
);
let encoder = EncodingType::try_from_bytes(b"msgpack").unwrap();
let mut res = vec![];
encoder.encode(&test_data, &mut res).unwrap();
[benchmark_fn(
format!("decode_msgpack_{}_{}", row_cnt, col_cnt),
move |b| {
let res = res.clone();
b.iter(move || {
let mut binary_data = std::io::Cursor::new(res.clone());
binary_data.set_position(0);
let _: Result<Option<PluginOutput>, _> =
black_box(encoder.decode(&mut binary_data));
})
},
)]
}
tango_benchmarks!(
bench_load_standard_lib(),
// Data types
// Record
bench_record_create(1),
bench_record_create(10),
bench_record_create(100),
bench_record_create(1_000),
bench_record_flat_access(1),
bench_record_flat_access(10),
bench_record_flat_access(100),
bench_record_flat_access(1_000),
bench_record_nested_access(1),
bench_record_nested_access(2),
bench_record_nested_access(4),
bench_record_nested_access(8),
bench_record_nested_access(16),
bench_record_nested_access(32),
bench_record_nested_access(64),
bench_record_nested_access(128),
// Table
bench_table_create(1),
bench_table_create(10),
bench_table_create(100),
bench_table_create(1_000),
bench_table_get(1),
bench_table_get(10),
bench_table_get(100),
bench_table_get(1_000),
bench_table_select(1),
bench_table_select(10),
bench_table_select(100),
bench_table_select(1_000),
// Eval
// Interleave
bench_eval_interleave(100),
bench_eval_interleave(1_000),
bench_eval_interleave(10_000),
bench_eval_interleave_with_interrupt(100),
bench_eval_interleave_with_interrupt(1_000),
bench_eval_interleave_with_interrupt(10_000),
// For
bench_eval_for(1),
bench_eval_for(10),
bench_eval_for(100),
bench_eval_for(1_000),
bench_eval_for(10_000),
// Each
bench_eval_each(1),
bench_eval_each(10),
bench_eval_each(100),
bench_eval_each(1_000),
bench_eval_each(10_000),
// Par-Each
bench_eval_par_each(1),
bench_eval_par_each(10),
bench_eval_par_each(100),
bench_eval_par_each(1_000),
bench_eval_par_each(10_000),
// Config
bench_eval_default_config(),
// Env
bench_eval_default_env(),
// Encode
// Json
encode_json(100, 5),
encode_json(10000, 15),
// MsgPack
encode_msgpack(100, 5),
encode_msgpack(10000, 15),
// Decode
// Json
decode_json(100, 5),
decode_json(10000, 15),
// MsgPack
decode_msgpack(100, 5),
decode_msgpack(10000, 15)
);
tango_main!();

View File

@ -1,12 +1,8 @@
#!/usr/bin/env bash #!/usr/bin/env bash
set -euo pipefail set -euo pipefail
DIR=$(readlink -f $(dirname "${BASH_SOURCE[0]}"))
REPO_ROOT=$(dirname $DIR)
echo "---------------------------------------------------------------" echo "---------------------------------------------------------------"
echo "Building nushell (nu) and all the plugins" echo "Building nushell (nu) with dataframes and all the plugins"
echo "---------------------------------------------------------------" echo "---------------------------------------------------------------"
echo "" echo ""
@ -16,21 +12,14 @@ NU_PLUGINS=(
'nu_plugin_inc' 'nu_plugin_inc'
'nu_plugin_query' 'nu_plugin_query'
'nu_plugin_custom_values' 'nu_plugin_custom_values'
'nu_plugin_polars'
) )
echo "Building nushell" echo "Building nushell"
( cargo build --features=dataframe
cd $REPO_ROOT
cargo build --locked
)
for plugin in "${NU_PLUGINS[@]}" for plugin in "${NU_PLUGINS[@]}"
do do
echo '' && cd crates/"$plugin"
echo "Building $plugin..." echo "Building $plugin..."
echo "-----------------------------" echo "-----------------------------"
( cargo build && cd ../..
cd "$REPO_ROOT/crates/$plugin"
cargo build
)
done done

36
build-all-windows.cmd Normal file
View File

@ -0,0 +1,36 @@
@echo off
@echo -------------------------------------------------------------------
@echo Building nushell (nu.exe) with dataframes and all the plugins
@echo -------------------------------------------------------------------
@echo.
echo Building nushell.exe
cargo build cargo build --features=dataframe
@echo.
@cd crates\nu_plugin_example
echo Building nu_plugin_example.exe
cargo build
@echo.
@cd ..\..\crates\nu_plugin_gstat
echo Building nu_plugin_gstat.exe
cargo build
@echo.
@cd ..\..\crates\nu_plugin_inc
echo Building nu_plugin_inc.exe
cargo build
@echo.
@cd ..\..\crates\nu_plugin_query
echo Building nu_plugin_query.exe
cargo build
@echo.
@cd ..\..\crates\nu_plugin_custom_values
echo Building nu_plugin_custom_values.exe
cargo build
@echo.
@cd ..\..

23
build-all.nu Normal file
View File

@ -0,0 +1,23 @@
echo '-------------------------------------------------------------------'
echo 'Building nushell (nu) with dataframes and all the plugins'
echo '-------------------------------------------------------------------'
echo $'(char nl)Building nushell'
echo '----------------------------'
cargo build --features=dataframe
let plugins = [
nu_plugin_inc,
nu_plugin_gstat,
nu_plugin_query,
nu_plugin_example,
nu_plugin_custom_values,
]
for plugin in $plugins {
$'(char nl)Building ($plugin)'
'----------------------------'
cd $'crates/($plugin)'
cargo build
ignore
}

13
build.rs Normal file
View File

@ -0,0 +1,13 @@
#[cfg(windows)]
fn main() {
let mut res = winres::WindowsResource::new();
res.set("ProductName", "Nushell");
res.set("FileDescription", "Nushell");
res.set("LegalCopyright", "Copyright (C) 2022");
res.set_icon("assets/nu_logo.ico");
res.compile()
.expect("Failed to run the Windows resource compiler (rc.exe)");
}
#[cfg(not(windows))]
fn main() {}

View File

@ -5,48 +5,35 @@ repository = "https://github.com/nushell/nushell/tree/main/crates/nu-cli"
edition = "2021" edition = "2021"
license = "MIT" license = "MIT"
name = "nu-cli" name = "nu-cli"
version = "0.99.1" version = "0.72.1"
[lib]
bench = false
[dev-dependencies] [dev-dependencies]
nu-cmd-lang = { path = "../nu-cmd-lang", version = "0.99.1" } nu-test-support = { path="../nu-test-support", version = "0.72.1" }
nu-command = { path = "../nu-command", version = "0.99.1" } nu-command = { path = "../nu-command", version = "0.72.1" }
nu-test-support = { path = "../nu-test-support", version = "0.99.1" } rstest = {version = "0.15.0", default-features = false}
rstest = { workspace = true, default-features = false }
tempfile = { workspace = true }
[dependencies] [dependencies]
nu-cmd-base = { path = "../nu-cmd-base", version = "0.99.1" } nu-engine = { path = "../nu-engine", version = "0.72.1" }
nu-engine = { path = "../nu-engine", version = "0.99.1" } nu-path = { path = "../nu-path", version = "0.72.1" }
nu-path = { path = "../nu-path", version = "0.99.1" } nu-parser = { path = "../nu-parser", version = "0.72.1" }
nu-parser = { path = "../nu-parser", version = "0.99.1" } nu-protocol = { path = "../nu-protocol", version = "0.72.1" }
nu-plugin-engine = { path = "../nu-plugin-engine", version = "0.99.1", optional = true } nu-utils = { path = "../nu-utils", version = "0.72.1" }
nu-protocol = { path = "../nu-protocol", version = "0.99.1" } nu-ansi-term = "0.46.0"
nu-utils = { path = "../nu-utils", version = "0.99.1" } nu-color-config = { path = "../nu-color-config", version = "0.72.1" }
nu-color-config = { path = "../nu-color-config", version = "0.99.1" } reedline = { version = "0.14.0", features = ["bashisms", "sqlite"]}
nu-ansi-term = { workspace = true }
reedline = { workspace = true, features = ["bashisms", "sqlite"] }
chrono = { default-features = false, features = ["std"], workspace = true } atty = "0.2.14"
crossterm = { workspace = true } chrono = { default-features = false, features = ["std"], version = "0.4.23" }
fancy-regex = { workspace = true } crossterm = "0.24.0"
fuzzy-matcher = { workspace = true } fancy-regex = "0.10.0"
is_executable = { workspace = true } fuzzy-matcher = "0.3.7"
log = { workspace = true } is_executable = "1.0.1"
miette = { workspace = true, features = ["fancy-no-backtrace"] } lazy_static = "1.4.0"
lscolors = { workspace = true, default-features = false, features = ["nu-ansi-term"] } log = "0.4"
once_cell = { workspace = true } miette = { version = "5.1.0", features = ["fancy-no-backtrace"] }
percent-encoding = { workspace = true } percent-encoding = "2"
sysinfo = { workspace = true } sysinfo = "0.26.2"
unicode-segmentation = { workspace = true } thiserror = "1.0.31"
uuid = { workspace = true, features = ["v4"] }
which = { workspace = true }
[features] [features]
plugin = ["nu-plugin-engine"] plugin = []
system-clipboard = ["reedline/system_clipboard"]
[lints]
workspace = true

View File

@ -1,6 +1,6 @@
MIT License MIT License
Copyright (c) 2019 - 2023 The Nushell Project Developers Copyright (c) 2019 - 2022 The Nushell Project Developers
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

View File

@ -1,7 +0,0 @@
This crate implements the core functionality of the interactive Nushell REPL and interfaces with `reedline`.
Currently implements the syntax highlighting and completions logic.
Furthermore includes a few commands that are specific to `reedline`
## Internal Nushell crate
This crate implements components of Nushell and is not designed to support plugin authors or other users directly.

View File

@ -0,0 +1,73 @@
use crate::util::report_error;
use log::info;
use miette::Result;
use nu_engine::{convert_env_values, eval_block};
use nu_parser::parse;
use nu_protocol::engine::Stack;
use nu_protocol::{
engine::{EngineState, StateWorkingSet},
PipelineData, Spanned, Value,
};
/// Run a command (or commands) given to us by the user
pub fn evaluate_commands(
commands: &Spanned<String>,
engine_state: &mut EngineState,
stack: &mut Stack,
input: PipelineData,
table_mode: Option<Value>,
) -> Result<Option<i64>> {
// Translate environment variables from Strings to Values
if let Some(e) = convert_env_values(engine_state, stack) {
let working_set = StateWorkingSet::new(engine_state);
report_error(&working_set, &e);
std::process::exit(1);
}
// Parse the source code
let (block, delta) = {
if let Some(ref t_mode) = table_mode {
let mut config = engine_state.get_config().clone();
config.table_mode = t_mode.as_string()?;
engine_state.set_config(&config);
}
let mut working_set = StateWorkingSet::new(engine_state);
let (output, err) = parse(&mut working_set, None, commands.item.as_bytes(), false, &[]);
if let Some(err) = err {
report_error(&working_set, &err);
std::process::exit(1);
}
(output, working_set.render())
};
// Update permanent state
if let Err(err) = engine_state.merge_delta(delta) {
let working_set = StateWorkingSet::new(engine_state);
report_error(&working_set, &err);
}
// Run the block
let exit_code = match eval_block(engine_state, stack, &block, input, false, false) {
Ok(pipeline_data) => {
let mut config = engine_state.get_config().clone();
if let Some(t_mode) = table_mode {
config.table_mode = t_mode.as_string()?;
}
crate::eval_file::print_table_or_error(engine_state, stack, pipeline_data, &mut config)
}
Err(err) => {
let working_set = StateWorkingSet::new(engine_state);
report_error(&working_set, &err);
std::process::exit(1);
}
};
info!("evaluate {}:{}:{}", file!(), line!(), column!());
Ok(exit_code)
}

View File

@ -1,35 +0,0 @@
use nu_engine::command_prelude::*;
#[derive(Clone)]
pub struct Commandline;
impl Command for Commandline {
fn name(&self) -> &str {
"commandline"
}
fn signature(&self) -> Signature {
Signature::build("commandline")
.input_output_types(vec![(Type::Nothing, Type::String)])
.category(Category::Core)
}
fn description(&self) -> &str {
"View the current command line input buffer."
}
fn search_terms(&self) -> Vec<&str> {
vec!["repl", "interactive"]
}
fn run(
&self,
engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let repl = engine_state.repl_state.lock().expect("repl state mutex");
Ok(Value::string(repl.buffer.clone(), call.head).into_pipeline_data())
}
}

View File

@ -1,66 +0,0 @@
use nu_engine::command_prelude::*;
#[derive(Clone)]
pub struct SubCommand;
impl Command for SubCommand {
fn name(&self) -> &str {
"commandline edit"
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.input_output_types(vec![(Type::Nothing, Type::Nothing)])
.switch(
"append",
"appends the string to the end of the buffer",
Some('a'),
)
.switch(
"insert",
"inserts the string into the buffer at the cursor position",
Some('i'),
)
.switch(
"replace",
"replaces the current contents of the buffer (default)",
Some('r'),
)
.required(
"str",
SyntaxShape::String,
"the string to perform the operation with",
)
.category(Category::Core)
}
fn description(&self) -> &str {
"Modify the current command line input buffer."
}
fn search_terms(&self) -> Vec<&str> {
vec!["repl", "interactive"]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let str: String = call.req(engine_state, stack, 0)?;
let mut repl = engine_state.repl_state.lock().expect("repl state mutex");
if call.has_flag(engine_state, stack, "append")? {
repl.buffer.push_str(&str);
} else if call.has_flag(engine_state, stack, "insert")? {
let cursor_pos = repl.cursor_pos;
repl.buffer.insert_str(cursor_pos, &str);
repl.cursor_pos += str.len();
} else {
repl.buffer = str;
repl.cursor_pos = repl.buffer.len();
}
Ok(Value::nothing(call.head).into_pipeline_data())
}
}

View File

@ -1,52 +0,0 @@
use nu_engine::command_prelude::*;
use unicode_segmentation::UnicodeSegmentation;
#[derive(Clone)]
pub struct SubCommand;
impl Command for SubCommand {
fn name(&self) -> &str {
"commandline get-cursor"
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.input_output_types(vec![(Type::Nothing, Type::Int)])
.allow_variants_without_examples(true)
.category(Category::Core)
}
fn description(&self) -> &str {
"Get the current cursor position."
}
fn search_terms(&self) -> Vec<&str> {
vec!["repl", "interactive"]
}
fn run(
&self,
engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let repl = engine_state.repl_state.lock().expect("repl state mutex");
let char_pos = repl
.buffer
.grapheme_indices(true)
.chain(std::iter::once((repl.buffer.len(), "")))
.position(|(i, _c)| i == repl.cursor_pos)
.expect("Cursor position isn't on a grapheme boundary");
match i64::try_from(char_pos) {
Ok(pos) => Ok(Value::int(pos, call.head).into_pipeline_data()),
Err(e) => Err(ShellError::GenericError {
error: "Failed to convert cursor position to int".to_string(),
msg: e.to_string(),
span: None,
help: None,
inner: vec![],
}),
}
}
}

View File

@ -1,9 +0,0 @@
mod commandline_;
mod edit;
mod get_cursor;
mod set_cursor;
pub use commandline_::Commandline;
pub use edit::SubCommand as CommandlineEdit;
pub use get_cursor::SubCommand as CommandlineGetCursor;
pub use set_cursor::SubCommand as CommandlineSetCursor;

View File

@ -1,65 +0,0 @@
use nu_engine::command_prelude::*;
use unicode_segmentation::UnicodeSegmentation;
#[derive(Clone)]
pub struct SubCommand;
impl Command for SubCommand {
fn name(&self) -> &str {
"commandline set-cursor"
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.input_output_types(vec![(Type::Nothing, Type::Nothing)])
.switch(
"end",
"set the current cursor position to the end of the buffer",
Some('e'),
)
.optional("pos", SyntaxShape::Int, "Cursor position to be set")
.category(Category::Core)
}
fn description(&self) -> &str {
"Set the current cursor position."
}
fn search_terms(&self) -> Vec<&str> {
vec!["repl", "interactive"]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let mut repl = engine_state.repl_state.lock().expect("repl state mutex");
if let Some(pos) = call.opt::<i64>(engine_state, stack, 0)? {
repl.cursor_pos = if pos <= 0 {
0usize
} else {
repl.buffer
.grapheme_indices(true)
.map(|(i, _c)| i)
.nth(pos as usize)
.unwrap_or(repl.buffer.len())
};
Ok(Value::nothing(call.head).into_pipeline_data())
} else if call.has_flag(engine_state, stack, "end")? {
repl.cursor_pos = repl.buffer.len();
Ok(Value::nothing(call.head).into_pipeline_data())
} else {
Err(ShellError::GenericError {
error: "Required a positional argument or a flag".to_string(),
msg: "".to_string(),
span: None,
help: None,
inner: vec![],
})
}
}
}

View File

@ -1,35 +0,0 @@
use crate::commands::*;
use nu_protocol::engine::{EngineState, StateWorkingSet};
pub fn add_cli_context(mut engine_state: EngineState) -> EngineState {
let delta = {
let mut working_set = StateWorkingSet::new(&engine_state);
macro_rules! bind_command {
( $( $command:expr ),* $(,)? ) => {
$( working_set.add_decl(Box::new($command)); )*
};
}
bind_command! {
Commandline,
CommandlineEdit,
CommandlineGetCursor,
CommandlineSetCursor,
History,
HistorySession,
Keybindings,
KeybindingsDefault,
KeybindingsList,
KeybindingsListen,
};
working_set.render()
};
if let Err(err) = engine_state.merge_delta(delta) {
eprintln!("Error creating CLI command context: {err:?}");
}
engine_state
}

View File

@ -1,202 +0,0 @@
use nu_engine::command_prelude::*;
use nu_protocol::HistoryFileFormat;
use reedline::{
FileBackedHistory, History as ReedlineHistory, HistoryItem, SearchDirection, SearchQuery,
SqliteBackedHistory,
};
#[derive(Clone)]
pub struct History;
impl Command for History {
fn name(&self) -> &str {
"history"
}
fn description(&self) -> &str {
"Get the command history."
}
fn signature(&self) -> nu_protocol::Signature {
Signature::build("history")
.input_output_types(vec![(Type::Nothing, Type::Any)])
.allow_variants_without_examples(true)
.switch("clear", "Clears out the history entries", Some('c'))
.switch(
"long",
"Show long listing of entries for sqlite history",
Some('l'),
)
.category(Category::History)
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let Some(history) = engine_state.history_config() else {
return Ok(PipelineData::empty());
};
// todo for sqlite history this command should be an alias to `open ~/.config/nushell/history.sqlite3 | get history`
let Some(history_path) = history.file_path() else {
return Err(ShellError::ConfigDirNotFound { span: Some(head) });
};
if call.has_flag(engine_state, stack, "clear")? {
let _ = std::fs::remove_file(history_path);
// TODO: FIXME also clear the auxiliary files when using sqlite
return Ok(PipelineData::empty());
}
let long = call.has_flag(engine_state, stack, "long")?;
let signals = engine_state.signals().clone();
let history_reader: Option<Box<dyn ReedlineHistory>> = match history.file_format {
HistoryFileFormat::Sqlite => {
SqliteBackedHistory::with_file(history_path.clone(), None, None)
.map(|inner| {
let boxed: Box<dyn ReedlineHistory> = Box::new(inner);
boxed
})
.ok()
}
HistoryFileFormat::Plaintext => {
FileBackedHistory::with_file(history.max_size as usize, history_path.clone())
.map(|inner| {
let boxed: Box<dyn ReedlineHistory> = Box::new(inner);
boxed
})
.ok()
}
};
match history.file_format {
HistoryFileFormat::Plaintext => Ok(history_reader
.and_then(|h| {
h.search(SearchQuery::everything(SearchDirection::Forward, None))
.ok()
})
.map(move |entries| {
entries.into_iter().enumerate().map(move |(idx, entry)| {
Value::record(
record! {
"command" => Value::string(entry.command_line, head),
"index" => Value::int(idx as i64, head),
},
head,
)
})
})
.ok_or(ShellError::FileNotFound {
file: history_path.display().to_string(),
span: head,
})?
.into_pipeline_data(head, signals)),
HistoryFileFormat::Sqlite => Ok(history_reader
.and_then(|h| {
h.search(SearchQuery::everything(SearchDirection::Forward, None))
.ok()
})
.map(move |entries| {
entries
.into_iter()
.enumerate()
.map(move |(idx, entry)| create_history_record(idx, entry, long, head))
})
.ok_or(ShellError::FileNotFound {
file: history_path.display().to_string(),
span: head,
})?
.into_pipeline_data(head, signals)),
}
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
example: "history | length",
description: "Get current history length",
result: None,
},
Example {
example: "history | last 5",
description: "Show last 5 commands you have ran",
result: None,
},
Example {
example: "history | where command =~ cargo | get command",
description: "Search all the commands from history that contains 'cargo'",
result: None,
},
]
}
}
fn create_history_record(idx: usize, entry: HistoryItem, long: bool, head: Span) -> Value {
//1. Format all the values
//2. Create a record of either short or long columns and values
let item_id_value = Value::int(
entry
.id
.and_then(|id| id.to_string().parse::<i64>().ok())
.unwrap_or_default(),
head,
);
let start_timestamp_value = Value::string(
entry
.start_timestamp
.map(|time| time.to_string())
.unwrap_or_default(),
head,
);
let command_value = Value::string(entry.command_line, head);
let session_id_value = Value::int(
entry
.session_id
.and_then(|id| id.to_string().parse::<i64>().ok())
.unwrap_or_default(),
head,
);
let hostname_value = Value::string(entry.hostname.unwrap_or_default(), head);
let cwd_value = Value::string(entry.cwd.unwrap_or_default(), head);
let duration_value = Value::duration(
entry
.duration
.and_then(|d| d.as_nanos().try_into().ok())
.unwrap_or(0),
head,
);
let exit_status_value = Value::int(entry.exit_status.unwrap_or(0), head);
let index_value = Value::int(idx as i64, head);
if long {
Value::record(
record! {
"item_id" => item_id_value,
"start_timestamp" => start_timestamp_value,
"command" => command_value,
"session_id" => session_id_value,
"hostname" => hostname_value,
"cwd" => cwd_value,
"duration" => duration_value,
"exit_status" => exit_status_value,
"idx" => index_value,
},
head,
)
} else {
Value::record(
record! {
"start_timestamp" => start_timestamp_value,
"command" => command_value,
"cwd" => cwd_value,
"duration" => duration_value,
"exit_status" => exit_status_value,
},
head,
)
}
}

View File

@ -1,5 +0,0 @@
mod history_;
mod history_session;
pub use history_::History;
pub use history_session::HistorySession;

View File

@ -1,41 +0,0 @@
use nu_engine::{command_prelude::*, get_full_help};
#[derive(Clone)]
pub struct Keybindings;
impl Command for Keybindings {
fn name(&self) -> &str {
"keybindings"
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.category(Category::Platform)
.input_output_types(vec![(Type::Nothing, Type::String)])
}
fn description(&self) -> &str {
"Keybindings related commands."
}
fn extra_description(&self) -> &str {
r#"You must use one of the following subcommands. Using this command as-is will only produce this help message.
For more information on input and keybindings, check:
https://www.nushell.sh/book/line_editor.html"#
}
fn search_terms(&self) -> Vec<&str> {
vec!["shortcut", "hotkey"]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
Ok(Value::string(get_full_help(self, engine_state, stack), call.head).into_pipeline_data())
}
}

View File

@ -1,54 +0,0 @@
use nu_engine::command_prelude::*;
use reedline::get_reedline_default_keybindings;
#[derive(Clone)]
pub struct KeybindingsDefault;
impl Command for KeybindingsDefault {
fn name(&self) -> &str {
"keybindings default"
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.category(Category::Platform)
.input_output_types(vec![(Type::Nothing, Type::table())])
}
fn description(&self) -> &str {
"List default keybindings."
}
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Get list with default keybindings",
example: "keybindings default",
result: None,
}]
}
fn run(
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let records = get_reedline_default_keybindings()
.into_iter()
.map(|(mode, modifier, code, event)| {
Value::record(
record! {
"mode" => Value::string(mode, call.head),
"modifier" => Value::string(modifier, call.head),
"code" => Value::string(code, call.head),
"event" => Value::string(event, call.head),
},
call.head,
)
})
.collect();
Ok(Value::list(records, call.head).into_pipeline_data())
}
}

View File

@ -1,173 +0,0 @@
use crossterm::{
event::Event, event::KeyCode, event::KeyEvent, execute, terminal, QueueableCommand,
};
use nu_engine::command_prelude::*;
use std::io::{stdout, Write};
#[derive(Clone)]
pub struct KeybindingsListen;
impl Command for KeybindingsListen {
fn name(&self) -> &str {
"keybindings listen"
}
fn description(&self) -> &str {
"Get input from the user."
}
fn extra_description(&self) -> &str {
"This is an internal debugging tool. For better output, try `input listen --types [key]`"
}
fn signature(&self) -> Signature {
Signature::build(self.name())
.category(Category::Platform)
.input_output_types(vec![(Type::Nothing, Type::Nothing)])
.allow_variants_without_examples(true)
}
fn run(
&self,
engine_state: &EngineState,
_stack: &mut Stack,
_call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
println!("Type any key combination to see key details. Press ESC to abort.");
match print_events(engine_state) {
Ok(v) => Ok(v.into_pipeline_data()),
Err(e) => {
terminal::disable_raw_mode()?;
Err(ShellError::GenericError {
error: "Error with input".into(),
msg: "".into(),
span: None,
help: Some(e.to_string()),
inner: vec![],
})
}
}
}
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Type and see key event codes",
example: "keybindings listen",
result: None,
}]
}
}
pub fn print_events(engine_state: &EngineState) -> Result<Value, ShellError> {
let config = engine_state.get_config();
stdout().flush()?;
terminal::enable_raw_mode()?;
if config.use_kitty_protocol {
if let Ok(false) = crossterm::terminal::supports_keyboard_enhancement() {
println!("WARN: The terminal doesn't support use_kitty_protocol config.\r");
}
// enable kitty protocol
//
// Note that, currently, only the following support this protocol:
// * [kitty terminal](https://sw.kovidgoyal.net/kitty/)
// * [foot terminal](https://codeberg.org/dnkl/foot/issues/319)
// * [WezTerm terminal](https://wezfurlong.org/wezterm/config/lua/config/enable_kitty_keyboard.html)
// * [notcurses library](https://github.com/dankamongmen/notcurses/issues/2131)
// * [neovim text editor](https://github.com/neovim/neovim/pull/18181)
// * [kakoune text editor](https://github.com/mawww/kakoune/issues/4103)
// * [dte text editor](https://gitlab.com/craigbarnes/dte/-/issues/138)
//
// Refer to https://sw.kovidgoyal.net/kitty/keyboard-protocol/ if you're curious.
let _ = execute!(
stdout(),
crossterm::event::PushKeyboardEnhancementFlags(
crossterm::event::KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES
)
);
}
let mut stdout = std::io::BufWriter::new(std::io::stderr());
loop {
let event = crossterm::event::read()?;
if event == Event::Key(KeyCode::Esc.into()) {
break;
}
// stdout.queue(crossterm::style::Print(format!("event: {:?}", &event)))?;
// stdout.queue(crossterm::style::Print("\r\n"))?;
// Get a record
let v = print_events_helper(event)?;
// Print out the record
let o = match v {
Value::Record { val, .. } => val
.iter()
.map(|(x, y)| format!("{}: {}", x, y.to_expanded_string("", config)))
.collect::<Vec<String>>()
.join(", "),
_ => "".to_string(),
};
stdout.queue(crossterm::style::Print(o))?;
stdout.queue(crossterm::style::Print("\r\n"))?;
stdout.flush()?;
}
if config.use_kitty_protocol {
let _ = execute!(
std::io::stdout(),
crossterm::event::PopKeyboardEnhancementFlags
);
}
terminal::disable_raw_mode()?;
Ok(Value::nothing(Span::unknown()))
}
// this fn is totally ripped off from crossterm's examples
// it's really a diagnostic routine to see if crossterm is
// even seeing the events. if you press a key and no events
// are printed, it's a good chance your terminal is eating
// those events.
fn print_events_helper(event: Event) -> Result<Value, ShellError> {
if let Event::Key(KeyEvent {
code,
modifiers,
kind,
state,
}) = event
{
match code {
KeyCode::Char(c) => {
let record = record! {
"char" => Value::string(format!("{c}"), Span::unknown()),
"code" => Value::string(format!("{:#08x}", u32::from(c)), Span::unknown()),
"modifier" => Value::string(format!("{modifiers:?}"), Span::unknown()),
"flags" => Value::string(format!("{modifiers:#08b}"), Span::unknown()),
"kind" => Value::string(format!("{kind:?}"), Span::unknown()),
"state" => Value::string(format!("{state:?}"), Span::unknown()),
};
Ok(Value::record(record, Span::unknown()))
}
_ => {
let record = record! {
"code" => Value::string(format!("{code:?}"), Span::unknown()),
"modifier" => Value::string(format!("{modifiers:?}"), Span::unknown()),
"flags" => Value::string(format!("{modifiers:#08b}"), Span::unknown()),
"kind" => Value::string(format!("{kind:?}"), Span::unknown()),
"state" => Value::string(format!("{state:?}"), Span::unknown()),
};
Ok(Value::record(record, Span::unknown()))
}
}
} else {
let record = record! { "event" => Value::string(format!("{event:?}"), Span::unknown()) };
Ok(Value::record(record, Span::unknown()))
}
}

View File

@ -1,43 +1,43 @@
use crate::completions::CompletionOptions; use crate::completions::{CompletionOptions, SortBy};
use nu_protocol::{ use nu_protocol::{engine::StateWorkingSet, levenshtein_distance, Span};
engine::{Stack, StateWorkingSet},
Span,
};
use reedline::Suggestion; use reedline::Suggestion;
// Completer trait represents the three stages of the completion
// fetch, filter and sort
pub trait Completer { pub trait Completer {
/// Fetch, filter, and sort completions
#[allow(clippy::too_many_arguments)]
fn fetch( fn fetch(
&mut self, &mut self,
working_set: &StateWorkingSet, working_set: &StateWorkingSet,
stack: &Stack, prefix: Vec<u8>,
prefix: &[u8],
span: Span, span: Span,
offset: usize, offset: usize,
pos: usize, pos: usize,
options: &CompletionOptions, options: &CompletionOptions,
) -> Vec<SemanticSuggestion>; ) -> Vec<Suggestion>;
}
#[derive(Debug, Default, PartialEq)] fn get_sort_by(&self) -> SortBy {
pub struct SemanticSuggestion { SortBy::Ascending
pub suggestion: Suggestion, }
pub kind: Option<SuggestionKind>,
}
// TODO: think about name: maybe suggestion context? fn sort(&self, items: Vec<Suggestion>, prefix: Vec<u8>) -> Vec<Suggestion> {
#[derive(Clone, Debug, PartialEq)] let prefix_str = String::from_utf8_lossy(&prefix).to_string();
pub enum SuggestionKind { let mut filtered_items = items;
Command(nu_protocol::engine::CommandType),
Type(nu_protocol::Type),
}
impl From<Suggestion> for SemanticSuggestion { // Sort items
fn from(suggestion: Suggestion) -> Self { match self.get_sort_by() {
Self { SortBy::LevenshteinDistance => {
suggestion, filtered_items.sort_by(|a, b| {
..Default::default() let a_distance = levenshtein_distance(&prefix_str, &a.value);
} let b_distance = levenshtein_distance(&prefix_str, &b.value);
a_distance.cmp(&b_distance)
});
}
SortBy::Ascending => {
filtered_items.sort_by(|a, b| a.value.cmp(&b.value));
}
SortBy::None => {}
};
filtered_items
} }
} }

View File

@ -1,17 +1,14 @@
use crate::{ use crate::completions::{Completer, CompletionOptions, MatchAlgorithm, SortBy};
completions::{Completer, CompletionOptions, MatchAlgorithm},
SuggestionKind,
};
use nu_parser::FlatShape; use nu_parser::FlatShape;
use nu_protocol::{ use nu_protocol::{
engine::{CachedFile, Stack, StateWorkingSet}, engine::{EngineState, StateWorkingSet},
Span, Span,
}; };
use reedline::Suggestion; use reedline::Suggestion;
use std::sync::Arc;
use super::{completion_common::sort_suggestions, SemanticSuggestion};
pub struct CommandCompletion { pub struct CommandCompletion {
engine_state: Arc<EngineState>,
flattened: Vec<(Span, FlatShape)>, flattened: Vec<(Span, FlatShape)>,
flat_shape: FlatShape, flat_shape: FlatShape,
force_completion_after_space: bool, force_completion_after_space: bool,
@ -19,11 +16,14 @@ pub struct CommandCompletion {
impl CommandCompletion { impl CommandCompletion {
pub fn new( pub fn new(
engine_state: Arc<EngineState>,
_: &StateWorkingSet,
flattened: Vec<(Span, FlatShape)>, flattened: Vec<(Span, FlatShape)>,
flat_shape: FlatShape, flat_shape: FlatShape,
force_completion_after_space: bool, force_completion_after_space: bool,
) -> Self { ) -> Self {
Self { Self {
engine_state,
flattened, flattened,
flat_shape, flat_shape,
force_completion_after_space, force_completion_after_space,
@ -32,28 +32,21 @@ impl CommandCompletion {
fn external_command_completion( fn external_command_completion(
&self, &self,
working_set: &StateWorkingSet,
prefix: &str, prefix: &str,
match_algorithm: MatchAlgorithm, match_algorithm: MatchAlgorithm,
) -> Vec<String> { ) -> Vec<String> {
let mut executables = vec![]; let mut executables = vec![];
// os agnostic way to get the PATH env var let paths = self.engine_state.get_env_var("PATH");
let paths = working_set.permanent_state.get_path_env_var();
if let Some(paths) = paths { if let Some(paths) = paths {
if let Ok(paths) = paths.as_list() { if let Ok(paths) = paths.as_list() {
for path in paths { for path in paths {
let path = path.coerce_str().unwrap_or_default(); let path = path.as_string().unwrap_or_default();
if let Ok(mut contents) = std::fs::read_dir(path.as_ref()) { if let Ok(mut contents) = std::fs::read_dir(path) {
while let Some(Ok(item)) = contents.next() { while let Some(Ok(item)) = contents.next() {
if working_set if self.engine_state.config.max_external_completion_results
.permanent_state
.config
.completions
.external
.max_results
> executables.len() as i64 > executables.len() as i64
&& !executables.contains( && !executables.contains(
&item &item
@ -89,57 +82,67 @@ impl CommandCompletion {
offset: usize, offset: usize,
find_externals: bool, find_externals: bool,
match_algorithm: MatchAlgorithm, match_algorithm: MatchAlgorithm,
) -> Vec<SemanticSuggestion> { ) -> Vec<Suggestion> {
let partial = working_set.get_span_contents(span); let partial = working_set.get_span_contents(span);
let filter_predicate = |command: &[u8]| match_algorithm.matches_u8(command, partial); let filter_predicate = |command: &[u8]| match_algorithm.matches_u8(command, partial);
let mut results = working_set let results = working_set
.find_commands_by_predicate(filter_predicate, true) .find_commands_by_predicate(filter_predicate)
.into_iter() .into_iter()
.map(move |x| SemanticSuggestion { .map(move |x| Suggestion {
suggestion: Suggestion { value: String::from_utf8_lossy(&x.0).to_string(),
value: String::from_utf8_lossy(&x.0).to_string(), description: x.1,
description: x.1, extra: None,
span: reedline::Span::new(span.start - offset, span.end - offset), span: reedline::Span {
append_whitespace: true, start: span.start - offset,
..Suggestion::default() end: span.end - offset,
}, },
kind: Some(SuggestionKind::Command(x.2)), append_whitespace: true,
}) });
.collect::<Vec<_>>();
let results_aliases = working_set
.find_aliases_by_predicate(filter_predicate)
.into_iter()
.map(move |x| Suggestion {
value: String::from_utf8_lossy(&x).to_string(),
description: None,
extra: None,
span: reedline::Span {
start: span.start - offset,
end: span.end - offset,
},
append_whitespace: true,
});
let mut results = results.chain(results_aliases).collect::<Vec<_>>();
let partial = working_set.get_span_contents(span); let partial = working_set.get_span_contents(span);
let partial = String::from_utf8_lossy(partial).to_string(); let partial = String::from_utf8_lossy(partial).to_string();
if find_externals { if find_externals {
let results_external = self let results_external = self
.external_command_completion(working_set, &partial, match_algorithm) .external_command_completion(&partial, match_algorithm)
.into_iter() .into_iter()
.map(move |x| SemanticSuggestion { .map(move |x| Suggestion {
suggestion: Suggestion { value: x,
value: x, description: None,
span: reedline::Span::new(span.start - offset, span.end - offset), extra: None,
append_whitespace: true, span: reedline::Span {
..Suggestion::default() start: span.start - offset,
end: span.end - offset,
}, },
// TODO: is there a way to create a test? append_whitespace: true,
kind: None,
}); });
let results_strings: Vec<String> =
results.iter().map(|x| x.suggestion.value.clone()).collect();
for external in results_external { for external in results_external {
if results_strings.contains(&external.suggestion.value) { if results.contains(&external) {
results.push(SemanticSuggestion { results.push(Suggestion {
suggestion: Suggestion { value: format!("^{}", external.value),
value: format!("^{}", external.suggestion.value), description: None,
span: external.suggestion.span, extra: None,
append_whitespace: true, span: external.span,
..Suggestion::default() append_whitespace: true,
},
kind: external.kind,
}) })
} else { } else {
results.push(external) results.push(external)
@ -157,13 +160,12 @@ impl Completer for CommandCompletion {
fn fetch( fn fetch(
&mut self, &mut self,
working_set: &StateWorkingSet, working_set: &StateWorkingSet,
_stack: &Stack, _prefix: Vec<u8>,
prefix: &[u8],
span: Span, span: Span,
offset: usize, offset: usize,
pos: usize, pos: usize,
options: &CompletionOptions, options: &CompletionOptions,
) -> Vec<SemanticSuggestion> { ) -> Vec<Suggestion> {
let last = self let last = self
.flattened .flattened
.iter() .iter()
@ -172,7 +174,7 @@ impl Completer for CommandCompletion {
.take_while(|x| { .take_while(|x| {
matches!( matches!(
x.1, x.1,
FlatShape::InternalCall(_) FlatShape::InternalCall
| FlatShape::External | FlatShape::External
| FlatShape::ExternalArg | FlatShape::ExternalArg
| FlatShape::Literal | FlatShape::Literal
@ -185,7 +187,10 @@ impl Completer for CommandCompletion {
let subcommands = if let Some(last) = last { let subcommands = if let Some(last) = last {
self.complete_commands( self.complete_commands(
working_set, working_set,
Span::new(last.0.start, pos), Span {
start: last.0.start,
end: pos,
},
offset, offset,
false, false,
options.match_algorithm, options.match_algorithm,
@ -195,14 +200,13 @@ impl Completer for CommandCompletion {
}; };
if !subcommands.is_empty() { if !subcommands.is_empty() {
return sort_suggestions(&String::from_utf8_lossy(prefix), subcommands, options); return subcommands;
} }
let config = working_set.get_config(); let config = working_set.get_config();
let commands = if matches!(self.flat_shape, nu_parser::FlatShape::External) let commands = if matches!(self.flat_shape, nu_parser::FlatShape::External)
|| matches!(self.flat_shape, nu_parser::FlatShape::InternalCall(_)) || matches!(self.flat_shape, nu_parser::FlatShape::InternalCall)
|| ((span.end - span.start) == 0) || ((span.end - span.start) == 0)
|| is_passthrough_command(working_set.delta.get_file_contents())
{ {
// we're in a gap or at a command // we're in a gap or at a command
if working_set.get_span_contents(span).is_empty() && !self.force_completion_after_space if working_set.get_span_contents(span).is_empty() && !self.force_completion_after_space
@ -213,120 +217,20 @@ impl Completer for CommandCompletion {
working_set, working_set,
span, span,
offset, offset,
config.completions.external.enable, config.enable_external_completion,
options.match_algorithm, options.match_algorithm,
) )
} else { } else {
vec![] vec![]
}; };
sort_suggestions(&String::from_utf8_lossy(prefix), commands, options) subcommands
} .into_iter()
} .chain(commands.into_iter())
.collect::<Vec<_>>()
pub fn find_non_whitespace_index(contents: &[u8], start: usize) -> usize { }
match contents.get(start..) {
Some(contents) => { fn get_sort_by(&self) -> SortBy {
contents SortBy::LevenshteinDistance
.iter()
.take_while(|x| x.is_ascii_whitespace())
.count()
+ start
}
None => start,
}
}
pub fn is_passthrough_command(working_set_file_contents: &[CachedFile]) -> bool {
for cached_file in working_set_file_contents {
let contents = &cached_file.content;
let last_pipe_pos_rev = contents.iter().rev().position(|x| x == &b'|');
let last_pipe_pos = last_pipe_pos_rev.map(|x| contents.len() - x).unwrap_or(0);
let cur_pos = find_non_whitespace_index(contents, last_pipe_pos);
let result = match contents.get(cur_pos..) {
Some(contents) => contents.starts_with(b"sudo ") || contents.starts_with(b"doas "),
None => false,
};
if result {
return true;
}
}
false
}
#[cfg(test)]
mod command_completions_tests {
use super::*;
use nu_protocol::engine::EngineState;
use std::sync::Arc;
#[test]
fn test_find_non_whitespace_index() {
let commands = [
(" hello", 4),
("sudo ", 0),
(" sudo ", 2),
(" sudo ", 2),
(" hello ", 1),
(" hello ", 3),
(" hello | sudo ", 4),
(" sudo|sudo", 5),
("sudo | sudo ", 0),
(" hello sud", 1),
];
for (idx, ele) in commands.iter().enumerate() {
let index = find_non_whitespace_index(ele.0.as_bytes(), 0);
assert_eq!(index, ele.1, "Failed on index {}", idx);
}
}
#[test]
fn test_is_last_command_passthrough() {
let commands = [
(" hello", false),
(" sudo ", true),
("sudo ", true),
(" hello", false),
(" sudo", false),
(" sudo ", true),
(" sudo ", true),
(" sudo ", true),
(" hello ", false),
(" hello | sudo ", true),
(" sudo|sudo", false),
("sudo | sudo ", true),
(" hello sud", false),
(" sudo | sud ", false),
(" sudo|sudo ", true),
(" sudo | sudo ls | sudo ", true),
];
for (idx, ele) in commands.iter().enumerate() {
let input = ele.0.as_bytes();
let mut engine_state = EngineState::new();
engine_state.add_file("test.nu".into(), Arc::new([]));
let delta = {
let mut working_set = StateWorkingSet::new(&engine_state);
let _ = working_set.add_file("child.nu".into(), input);
working_set.render()
};
let result = engine_state.merge_delta(delta);
assert!(
result.is_ok(),
"Merge delta has failed: {}",
result.err().unwrap()
);
let is_passthrough_command = is_passthrough_command(engine_state.get_file_contents());
assert_eq!(
is_passthrough_command, ele.1,
"index for '{}': {}",
ele.0, idx
);
}
} }
} }

View File

@ -1,19 +1,17 @@
use crate::completions::{ use crate::completions::{
CommandCompletion, Completer, CompletionOptions, CustomCompletion, DirectoryCompletion, CommandCompletion, Completer, CompletionOptions, CustomCompletion, DirectoryCompletion,
DotNuCompletion, FileCompletion, FlagCompletion, OperatorCompletion, VariableCompletion, DotNuCompletion, FileCompletion, FlagCompletion, MatchAlgorithm, VariableCompletion,
}; };
use nu_color_config::{color_record_to_nustyle, lookup_ansi_color_style};
use nu_engine::eval_block; use nu_engine::eval_block;
use nu_parser::{flatten_pipeline_element, parse, FlatShape}; use nu_parser::{flatten_expression, parse, FlatShape};
use nu_protocol::{ use nu_protocol::{
debugger::WithoutDebug, ast::PipelineElement,
engine::{Closure, EngineState, Stack, StateWorkingSet}, engine::{EngineState, Stack, StateWorkingSet},
PipelineData, Span, Value, BlockId, PipelineData, Span, Value,
}; };
use reedline::{Completer as ReedlineCompleter, Suggestion}; use reedline::{Completer as ReedlineCompleter, Suggestion};
use std::{str, sync::Arc}; use std::str;
use std::sync::Arc;
use super::base::{SemanticSuggestion, SuggestionKind};
#[derive(Clone)] #[derive(Clone)]
pub struct NuCompleter { pub struct NuCompleter {
@ -22,386 +20,368 @@ pub struct NuCompleter {
} }
impl NuCompleter { impl NuCompleter {
pub fn new(engine_state: Arc<EngineState>, stack: Arc<Stack>) -> Self { pub fn new(engine_state: Arc<EngineState>, stack: Stack) -> Self {
Self { Self {
engine_state, engine_state,
stack: Stack::with_parent(stack).reset_out_dest().collect_value(), stack,
} }
} }
pub fn fetch_completions_at(&mut self, line: &str, pos: usize) -> Vec<SemanticSuggestion> {
self.completion_helper(line, pos)
}
// Process the completion for a given completer // Process the completion for a given completer
fn process_completion<T: Completer>( fn process_completion<T: Completer>(
&self, &self,
completer: &mut T, completer: &mut T,
working_set: &StateWorkingSet, working_set: &StateWorkingSet,
prefix: &[u8], prefix: Vec<u8>,
new_span: Span, new_span: Span,
offset: usize, offset: usize,
pos: usize, pos: usize,
) -> Vec<SemanticSuggestion> { ) -> Vec<Suggestion> {
let config = self.engine_state.get_config(); let config = self.engine_state.get_config();
let options = CompletionOptions { let mut options = CompletionOptions {
case_sensitive: config.completions.case_sensitive, case_sensitive: config.case_sensitive_completions,
match_algorithm: config.completions.algorithm.into(),
sort: config.completions.sort,
..Default::default() ..Default::default()
}; };
completer.fetch( if config.completion_algorithm == "fuzzy" {
working_set, options.match_algorithm = MatchAlgorithm::Fuzzy;
&self.stack, }
prefix,
new_span, // Fetch
offset, let mut suggestions =
pos, completer.fetch(working_set, prefix.clone(), new_span, offset, pos, &options);
&options,
) // Sort
suggestions = completer.sort(suggestions, prefix);
suggestions
} }
fn external_completion( fn external_completion(
&self, &self,
closure: &Closure, block_id: BlockId,
spans: &[String], spans: &[String],
offset: usize, offset: usize,
span: Span, span: Span,
) -> Option<Vec<SemanticSuggestion>> { ) -> Option<Vec<Suggestion>> {
let block = self.engine_state.get_block(closure.block_id); let stack = self.stack.clone();
let mut callee_stack = self let block = self.engine_state.get_block(block_id);
.stack let mut callee_stack = stack.gather_captures(&block.captures);
.captures_to_stack_preserve_out_dest(closure.captures.clone());
// Line // Line
if let Some(pos_arg) = block.signature.required_positional.first() { if let Some(pos_arg) = block.signature.required_positional.get(0) {
if let Some(var_id) = pos_arg.var_id { if let Some(var_id) = pos_arg.var_id {
callee_stack.add_var( callee_stack.add_var(
var_id, var_id,
Value::list( Value::List {
spans vals: spans
.iter() .iter()
.map(|it| Value::string(it, Span::unknown())) .map(|it| Value::String {
val: it.to_string(),
span: Span::unknown(),
})
.collect(), .collect(),
Span::unknown(), span: Span::unknown(),
), },
); );
} }
} }
let result = eval_block::<WithoutDebug>( let result = eval_block(
&self.engine_state, &self.engine_state,
&mut callee_stack, &mut callee_stack,
block, block,
PipelineData::empty(), PipelineData::new(span),
true,
true,
); );
match result.and_then(|data| data.into_value(span)) { match result {
Ok(value) => { Ok(pd) => {
if let Value::List { vals, .. } = value { let value = pd.into_value(span);
let result = if let Value::List { vals, span: _ } = value {
map_value_completions(vals.iter(), Span::new(span.start, span.end), offset); let result = map_value_completions(
vals.iter(),
Span {
start: span.start,
end: span.end,
},
offset,
);
return Some(result); return Some(result);
} }
} }
Err(err) => println!("failed to eval completer block: {err}"), Err(err) => println!("failed to eval completer block: {}", err),
} }
None None
} }
fn completion_helper(&mut self, line: &str, pos: usize) -> Vec<SemanticSuggestion> { fn completion_helper(&mut self, line: &str, pos: usize) -> Vec<Suggestion> {
let mut working_set = StateWorkingSet::new(&self.engine_state); let mut working_set = StateWorkingSet::new(&self.engine_state);
let offset = working_set.next_span_start(); let offset = working_set.next_span_start();
// TODO: Callers should be trimming the line themselves let (mut new_line, alias_offset) = try_find_alias(line.as_bytes(), &working_set);
let line = if line.len() > pos { &line[..pos] } else { line };
// Adjust offset so that the spans of the suggestions will start at the right
// place even with `only_buffer_difference: true`
let fake_offset = offset + line.len() - pos;
let pos = offset + line.len();
let initial_line = line.to_string(); let initial_line = line.to_string();
let mut line = line.to_string(); let alias_total_offset: usize = alias_offset.iter().sum();
line.push('a'); new_line.insert(alias_total_offset + pos, b'a');
let pos = offset + pos;
let config = self.engine_state.get_config(); let config = self.engine_state.get_config();
let output = parse(&mut working_set, Some("completer"), line.as_bytes(), false); let (output, _err) = parse(&mut working_set, Some("completer"), &new_line, false, &[]);
for pipeline in &output.pipelines { for pipeline in output.pipelines.into_iter() {
for pipeline_element in &pipeline.elements { for pipeline_element in pipeline.elements {
let flattened = flatten_pipeline_element(&working_set, pipeline_element); match pipeline_element {
let mut spans: Vec<String> = vec![]; PipelineElement::Expression(_, expr)
| PipelineElement::Redirection(_, _, expr)
| PipelineElement::And(_, expr)
| PipelineElement::Or(_, expr) => {
let flattened: Vec<_> = flatten_expression(&working_set, &expr);
let span_offset: usize = alias_offset.iter().sum();
let mut spans: Vec<String> = vec![];
for (flat_idx, flat) in flattened.iter().enumerate() { for (flat_idx, flat) in flattened.iter().enumerate() {
let is_passthrough_command = spans // Read the current spam to string
.first() let current_span = working_set.get_span_contents(flat.0).to_vec();
.filter(|content| content.as_str() == "sudo" || content.as_str() == "doas") let current_span_str = String::from_utf8_lossy(&current_span);
.is_some();
// Read the current spam to string
let current_span = working_set.get_span_contents(flat.0).to_vec();
let current_span_str = String::from_utf8_lossy(&current_span);
let is_last_span = pos >= flat.0.start && pos < flat.0.end; // Skip the last 'a' as span item
if flat_idx == flattened.len() - 1 {
// Skip the last 'a' as span item let mut chars = current_span_str.chars();
if is_last_span { chars.next_back();
let offset = pos - flat.0.start; let current_span_str = chars.as_str().to_owned();
if offset == 0 { spans.push(current_span_str.to_string());
spans.push(String::new()) } else {
} else { spans.push(current_span_str.to_string());
let mut current_span_str = current_span_str.to_string();
current_span_str.remove(offset);
spans.push(current_span_str);
}
} else {
spans.push(current_span_str.to_string());
}
// Complete based on the last span
if is_last_span {
// Context variables
let most_left_var =
most_left_variable(flat_idx, &working_set, flattened.clone());
// Create a new span
let new_span = Span::new(flat.0.start, flat.0.end - 1);
// Parses the prefix. Completion should look up to the cursor position, not after.
let mut prefix = working_set.get_span_contents(flat.0);
let index = pos - flat.0.start;
prefix = &prefix[..index];
// Variables completion
if prefix.starts_with(b"$") || most_left_var.is_some() {
let mut variable_names_completer =
VariableCompletion::new(most_left_var.unwrap_or((vec![], vec![])));
let mut variable_completions = self.process_completion(
&mut variable_names_completer,
&working_set,
prefix,
new_span,
fake_offset,
pos,
);
let mut variable_operations_completer =
OperatorCompletion::new(pipeline_element.expr.clone());
let mut variable_operations_completions = self.process_completion(
&mut variable_operations_completer,
&working_set,
prefix,
new_span,
fake_offset,
pos,
);
variable_completions.append(&mut variable_operations_completions);
return variable_completions;
}
// Flags completion
if prefix.starts_with(b"-") {
// Try to complete flag internally
let mut completer = FlagCompletion::new(pipeline_element.expr.clone());
let result = self.process_completion(
&mut completer,
&working_set,
prefix,
new_span,
fake_offset,
pos,
);
if !result.is_empty() {
return result;
} }
// We got no results for internal completion // Complete based on the last span
// now we can check if external completer is set and use it if pos + span_offset >= flat.0.start && pos + span_offset < flat.0.end {
if let Some(closure) = config.completions.external.completer.as_ref() { // Context variables
if let Some(external_result) = let most_left_var =
self.external_completion(closure, &spans, fake_offset, new_span) most_left_variable(flat_idx, &working_set, flattened.clone());
{
return external_result;
}
}
}
// specially check if it is currently empty - always complete commands // Create a new span
if (is_passthrough_command && flat_idx == 1) let new_span = if flat_idx == 0 {
|| (flat_idx == 0 && working_set.get_span_contents(new_span).is_empty()) Span {
{ start: flat.0.start,
let mut completer = CommandCompletion::new( end: flat.0.end - 1 - span_offset,
flattened.clone(), }
// flat_idx, } else {
FlatShape::String, Span {
true, start: flat.0.start - span_offset,
); end: flat.0.end - 1 - span_offset,
return self.process_completion( }
&mut completer, };
&working_set,
prefix,
new_span,
fake_offset,
pos,
);
}
// Completions that depends on the previous expression (e.g: use, source-env) // Parses the prefix. Completion should look up to the cursor position, not after.
if (is_passthrough_command && flat_idx > 1) || flat_idx > 0 { let mut prefix = working_set.get_span_contents(flat.0).to_vec();
if let Some(previous_expr) = flattened.get(flat_idx - 1) { let index = pos - (flat.0.start - span_offset);
// Read the content for the previous expression prefix.drain(index..);
let prev_expr_str =
working_set.get_span_contents(previous_expr.0).to_vec();
// Completion for .nu files // Variables completion
if prev_expr_str == b"use" if prefix.starts_with(b"$") || most_left_var.is_some() {
|| prev_expr_str == b"overlay use" let mut completer = VariableCompletion::new(
|| prev_expr_str == b"source-env" self.engine_state.clone(),
{ self.stack.clone(),
let mut completer = DotNuCompletion::new(); most_left_var.unwrap_or((vec![], vec![])),
);
return self.process_completion( return self.process_completion(
&mut completer, &mut completer,
&working_set, &working_set,
prefix, prefix,
new_span, new_span,
fake_offset, offset,
pos,
);
} else if prev_expr_str == b"ls" {
let mut completer = FileCompletion::new();
return self.process_completion(
&mut completer,
&working_set,
prefix,
new_span,
fake_offset,
pos,
);
} else if matches!(
previous_expr.1,
FlatShape::Float
| FlatShape::Int
| FlatShape::String
| FlatShape::List
| FlatShape::Bool
| FlatShape::Variable(_)
) {
let mut completer =
OperatorCompletion::new(pipeline_element.expr.clone());
return self.process_completion(
&mut completer,
&working_set,
prefix,
new_span,
fake_offset,
pos, pos,
); );
} }
}
}
// Match other types // Flags completion
match &flat.1 { if prefix.starts_with(b"-") {
FlatShape::Custom(decl_id) => { // Try to complete flag internally
let mut completer = CustomCompletion::new( let mut completer = FlagCompletion::new(expr.clone());
self.stack.clone(), let result = self.process_completion(
*decl_id, &mut completer,
initial_line, &working_set,
); prefix.clone(),
return self.process_completion(
&mut completer,
&working_set,
prefix,
new_span,
fake_offset,
pos,
);
}
FlatShape::Directory => {
let mut completer = DirectoryCompletion::new();
return self.process_completion(
&mut completer,
&working_set,
prefix,
new_span,
fake_offset,
pos,
);
}
FlatShape::Filepath | FlatShape::GlobPattern => {
let mut completer = FileCompletion::new();
return self.process_completion(
&mut completer,
&working_set,
prefix,
new_span,
fake_offset,
pos,
);
}
flat_shape => {
let mut completer = CommandCompletion::new(
flattened.clone(),
// flat_idx,
flat_shape.clone(),
false,
);
let mut out: Vec<_> = self.process_completion(
&mut completer,
&working_set,
prefix,
new_span,
fake_offset,
pos,
);
if !out.is_empty() {
return out;
}
// Try to complete using an external completer (if set)
if let Some(closure) =
config.completions.external.completer.as_ref()
{
if let Some(external_result) = self.external_completion(
closure,
&spans,
fake_offset,
new_span, new_span,
) { offset,
return external_result; pos,
);
if !result.is_empty() {
return result;
}
// We got no results for internal completion
// now we can check if external completer is set and use it
if let Some(block_id) = config.external_completer {
if let Some(external_result) = self
.external_completion(block_id, &spans, offset, new_span)
{
return external_result;
}
} }
} }
// Check for file completion // specially check if it is currently empty - always complete commands
let mut completer = FileCompletion::new(); if flat_idx == 0
out = self.process_completion( && working_set.get_span_contents(new_span).is_empty()
&mut completer, {
&working_set, let mut completer = CommandCompletion::new(
prefix, self.engine_state.clone(),
new_span, &working_set,
fake_offset, flattened.clone(),
pos, // flat_idx,
); FlatShape::String,
true,
if !out.is_empty() { );
return out; return self.process_completion(
&mut completer,
&working_set,
prefix,
new_span,
offset,
pos,
);
} }
// Completions that depends on the previous expression (e.g: use, source-env)
if flat_idx > 0 {
if let Some(previous_expr) = flattened.get(flat_idx - 1) {
// Read the content for the previous expression
let prev_expr_str =
working_set.get_span_contents(previous_expr.0).to_vec();
// Completion for .nu files
if prev_expr_str == b"use" || prev_expr_str == b"source-env"
{
let mut completer =
DotNuCompletion::new(self.engine_state.clone());
return self.process_completion(
&mut completer,
&working_set,
prefix,
new_span,
offset,
pos,
);
} else if prev_expr_str == b"ls" {
let mut completer =
FileCompletion::new(self.engine_state.clone());
return self.process_completion(
&mut completer,
&working_set,
prefix,
new_span,
offset,
pos,
);
}
}
}
// Match other types
match &flat.1 {
FlatShape::Custom(decl_id) => {
let mut completer = CustomCompletion::new(
self.engine_state.clone(),
self.stack.clone(),
*decl_id,
initial_line,
);
return self.process_completion(
&mut completer,
&working_set,
prefix,
new_span,
offset,
pos,
);
}
FlatShape::Directory => {
let mut completer =
DirectoryCompletion::new(self.engine_state.clone());
return self.process_completion(
&mut completer,
&working_set,
prefix,
new_span,
offset,
pos,
);
}
FlatShape::Filepath | FlatShape::GlobPattern => {
let mut completer =
FileCompletion::new(self.engine_state.clone());
return self.process_completion(
&mut completer,
&working_set,
prefix,
new_span,
offset,
pos,
);
}
flat_shape => {
let mut completer = CommandCompletion::new(
self.engine_state.clone(),
&working_set,
flattened.clone(),
// flat_idx,
flat_shape.clone(),
false,
);
let mut out: Vec<_> = self.process_completion(
&mut completer,
&working_set,
prefix.clone(),
new_span,
offset,
pos,
);
if !out.is_empty() {
return out;
}
// Try to complete using an external completer (if set)
if let Some(block_id) = config.external_completer {
if let Some(external_result) = self.external_completion(
block_id, &spans, offset, new_span,
) {
return external_result;
}
}
// Check for file completion
let mut completer =
FileCompletion::new(self.engine_state.clone());
out = self.process_completion(
&mut completer,
&working_set,
prefix,
new_span,
offset,
pos,
);
if !out.is_empty() {
return out;
}
}
};
} }
}; }
} }
} }
} }
@ -414,9 +394,85 @@ impl NuCompleter {
impl ReedlineCompleter for NuCompleter { impl ReedlineCompleter for NuCompleter {
fn complete(&mut self, line: &str, pos: usize) -> Vec<Suggestion> { fn complete(&mut self, line: &str, pos: usize) -> Vec<Suggestion> {
self.completion_helper(line, pos) self.completion_helper(line, pos)
.into_iter() }
.map(|s| s.suggestion) }
.collect()
type MatchedAlias = Vec<(Vec<u8>, Vec<u8>)>;
// Handler the completion when giving lines contains at least one alias. (e.g: `g checkout`)
// that `g` is an alias of `git`
fn try_find_alias(line: &[u8], working_set: &StateWorkingSet) -> (Vec<u8>, Vec<usize>) {
// An vector represents the offsets of alias
// e.g: the offset is 2 for the alias `g` of `git`
let mut alias_offset = vec![];
let mut output = vec![];
if let Some(matched_alias) = search_alias(line, working_set) {
let mut lens = matched_alias.len();
for (input_vec, line_vec) in matched_alias {
alias_offset.push(line_vec.len() - input_vec.len());
output.extend(line_vec);
if lens > 1 {
output.push(b' ');
lens -= 1;
}
}
if !line.is_empty() {
let last = line.last().expect("input is empty");
if last == &b' ' {
output.push(b' ');
}
}
} else {
output = line.to_vec();
}
(output, alias_offset)
}
fn search_alias(input: &[u8], working_set: &StateWorkingSet) -> Option<MatchedAlias> {
let mut vec_names = vec![];
let mut vec_alias = vec![];
let mut pos = 0;
let mut is_alias = false;
for (index, character) in input.iter().enumerate() {
if *character == b' ' {
let range = &input[pos..index];
vec_names.push(range.to_owned());
pos = index + 1;
}
}
// Push the rest to names vector.
if pos < input.len() {
vec_names.push(input[pos..].to_owned());
}
for name in &vec_names {
if let Some(alias_id) = working_set.find_alias(&name[..]) {
let alias_span = working_set.get_alias(alias_id);
let mut span_vec = vec![];
is_alias = true;
for alias in alias_span {
let name = working_set.get_span_contents(*alias);
if !name.is_empty() {
span_vec.push(name);
}
}
// Join span of vector together for complex alias, e.g: `f` is an alias for `git remote -v`
let full_aliases = span_vec.join(&[b' '][..]);
vec_alias.push(full_aliases);
} else {
vec_alias.push(name.to_owned());
}
}
if is_alias {
// Zip names and alias vectors, the original inputs and its aliases mapping.
// e.g:(['g'], ['g','i','t'])
let output = vec_names.into_iter().zip(vec_alias).collect();
Some(output)
} else {
None
} }
} }
@ -440,7 +496,7 @@ fn most_left_variable(
let result = working_set.get_span_contents(item.0).to_vec(); let result = working_set.get_span_contents(item.0).to_vec();
match item.1 { match item.1 {
FlatShape::Variable(_) => { FlatShape::Variable => {
variables_found.push(result); variables_found.push(result);
found_var = true; found_var = true;
@ -474,40 +530,41 @@ pub fn map_value_completions<'a>(
list: impl Iterator<Item = &'a Value>, list: impl Iterator<Item = &'a Value>,
span: Span, span: Span,
offset: usize, offset: usize,
) -> Vec<SemanticSuggestion> { ) -> Vec<Suggestion> {
list.filter_map(move |x| { list.filter_map(move |x| {
// Match for string values // Match for string values
if let Ok(s) = x.coerce_string() { if let Ok(s) = x.as_string() {
return Some(SemanticSuggestion { return Some(Suggestion {
suggestion: Suggestion { value: s,
value: s, description: None,
span: reedline::Span { extra: None,
start: span.start - offset,
end: span.end - offset,
},
..Suggestion::default()
},
kind: Some(SuggestionKind::Type(x.get_type())),
});
}
// Match for record values
if let Ok(record) = x.as_record() {
let mut suggestion = Suggestion {
value: String::from(""), // Initialize with empty string
span: reedline::Span { span: reedline::Span {
start: span.start - offset, start: span.start - offset,
end: span.end - offset, end: span.end - offset,
}, },
..Suggestion::default() append_whitespace: false,
});
}
// Match for record values
if let Ok((cols, vals)) = x.as_record() {
let mut suggestion = Suggestion {
value: String::from(""), // Initialize with empty string
description: None,
extra: None,
span: reedline::Span {
start: span.start - offset,
end: span.end - offset,
},
append_whitespace: false,
}; };
// Iterate the cols looking for `value` and `description` // Iterate the cols looking for `value` and `description`
record.iter().for_each(|it| { cols.iter().zip(vals).for_each(|it| {
// Match `value` column // Match `value` column
if it.0 == "value" { if it.0 == "value" {
// Convert the value to string // Convert the value to string
if let Ok(val_str) = it.1.coerce_string() { if let Ok(val_str) = it.1.as_string() {
// Update the suggestion value // Update the suggestion value
suggestion.value = val_str; suggestion.value = val_str;
} }
@ -516,96 +573,17 @@ pub fn map_value_completions<'a>(
// Match `description` column // Match `description` column
if it.0 == "description" { if it.0 == "description" {
// Convert the value to string // Convert the value to string
if let Ok(desc_str) = it.1.coerce_string() { if let Ok(desc_str) = it.1.as_string() {
// Update the suggestion value // Update the suggestion value
suggestion.description = Some(desc_str); suggestion.description = Some(desc_str);
} }
} }
// Match `style` column
if it.0 == "style" {
// Convert the value to string
suggestion.style = match it.1 {
Value::String { val, .. } => Some(lookup_ansi_color_style(val)),
Value::Record { .. } => Some(color_record_to_nustyle(it.1)),
_ => None,
};
}
}); });
return Some(SemanticSuggestion { return Some(suggestion);
suggestion,
kind: Some(SuggestionKind::Type(x.get_type())),
});
} }
None None
}) })
.collect() .collect()
} }
#[cfg(test)]
mod completer_tests {
use super::*;
#[test]
fn test_completion_helper() {
let mut engine_state =
nu_command::add_shell_command_context(nu_cmd_lang::create_default_context());
// Custom additions
let delta = {
let working_set = nu_protocol::engine::StateWorkingSet::new(&engine_state);
working_set.render()
};
let result = engine_state.merge_delta(delta);
assert!(
result.is_ok(),
"Error merging delta: {:?}",
result.err().unwrap()
);
let mut completer = NuCompleter::new(engine_state.into(), Arc::new(Stack::new()));
let dataset = [
("1 bit-sh", true, "b", vec!["bit-shl", "bit-shr"]),
("1.0 bit-sh", false, "b", vec![]),
("1 m", true, "m", vec!["mod"]),
("1.0 m", true, "m", vec!["mod"]),
("\"a\" s", true, "s", vec!["starts-with"]),
("sudo", false, "", Vec::new()),
("sudo l", true, "l", vec!["ls", "let", "lines", "loop"]),
(" sudo", false, "", Vec::new()),
(" sudo le", true, "le", vec!["let", "length"]),
(
"ls | c",
true,
"c",
vec!["cd", "config", "const", "cp", "cal"],
),
("ls | sudo m", true, "m", vec!["mv", "mut", "move"]),
];
for (line, has_result, begins_with, expected_values) in dataset {
let result = completer.completion_helper(line, line.len());
// Test whether the result is empty or not
assert_eq!(!result.is_empty(), has_result, "line: {}", line);
// Test whether the result begins with the expected value
result
.iter()
.for_each(|x| assert!(x.suggestion.value.starts_with(begins_with)));
// Test whether the result contains all the expected values
assert_eq!(
result
.iter()
.map(|x| expected_values.contains(&x.suggestion.value.as_str()))
.filter(|x| *x)
.count(),
expected_values.len(),
"line: {}",
line
);
}
}
}

View File

@ -1,384 +0,0 @@
use super::MatchAlgorithm;
use crate::{
completions::{matches, CompletionOptions},
SemanticSuggestion,
};
use fuzzy_matcher::{skim::SkimMatcherV2, FuzzyMatcher};
use nu_ansi_term::Style;
use nu_engine::env_to_string;
use nu_path::dots::expand_ndots;
use nu_path::{expand_to_real_path, home_dir};
use nu_protocol::{
engine::{EngineState, Stack, StateWorkingSet},
CompletionSort, Span,
};
use nu_utils::get_ls_colors;
use std::path::{is_separator, Component, Path, PathBuf, MAIN_SEPARATOR as SEP};
#[derive(Clone, Default)]
pub struct PathBuiltFromString {
parts: Vec<String>,
isdir: bool,
}
/// Recursively goes through paths that match a given `partial`.
/// built: State struct for a valid matching path built so far.
///
/// `isdir`: whether the current partial path has a trailing slash.
/// Parsing a path string into a pathbuf loses that bit of information.
///
/// want_directory: Whether we want only directories as completion matches.
/// Some commands like `cd` can only be run on directories whereas others
/// like `ls` can be run on regular files as well.
pub fn complete_rec(
partial: &[&str],
built: &PathBuiltFromString,
cwd: &Path,
options: &CompletionOptions,
want_directory: bool,
isdir: bool,
) -> Vec<PathBuiltFromString> {
let mut completions = vec![];
if let Some((&base, rest)) = partial.split_first() {
if base.chars().all(|c| c == '.') && (isdir || !rest.is_empty()) {
let mut built = built.clone();
built.parts.push(base.to_string());
built.isdir = true;
return complete_rec(rest, &built, cwd, options, want_directory, isdir);
}
}
let mut built_path = cwd.to_path_buf();
for part in &built.parts {
built_path.push(part);
}
let Ok(result) = built_path.read_dir() else {
return completions;
};
let mut entries = Vec::new();
for entry in result.filter_map(|e| e.ok()) {
let entry_name = entry.file_name().to_string_lossy().into_owned();
let entry_isdir = entry.path().is_dir();
let mut built = built.clone();
built.parts.push(entry_name.clone());
built.isdir = entry_isdir;
if !want_directory || entry_isdir {
entries.push((entry_name, built));
}
}
let prefix = partial.first().unwrap_or(&"");
let sorted_entries = sort_completions(prefix, entries, options, |(entry, _)| entry);
for (entry_name, built) in sorted_entries {
match partial.split_first() {
Some((base, rest)) => {
if matches(base, &entry_name, options) {
// We use `isdir` to confirm that the current component has
// at least one next component or a slash.
// Serves as confirmation to ignore longer completions for
// components in between.
if !rest.is_empty() || isdir {
completions.extend(complete_rec(
rest,
&built,
cwd,
options,
want_directory,
isdir,
));
} else {
completions.push(built);
}
}
if entry_name.eq(base)
&& matches!(options.match_algorithm, MatchAlgorithm::Prefix)
&& isdir
{
break;
}
}
None => {
completions.push(built);
}
}
}
completions
}
#[derive(Debug)]
enum OriginalCwd {
None,
Home,
Prefix(String),
}
impl OriginalCwd {
fn apply(&self, mut p: PathBuiltFromString, path_separator: char) -> String {
match self {
Self::None => {}
Self::Home => p.parts.insert(0, "~".to_string()),
Self::Prefix(s) => p.parts.insert(0, s.clone()),
};
let mut ret = p.parts.join(&path_separator.to_string());
if p.isdir {
ret.push(path_separator);
}
ret
}
}
fn surround_remove(partial: &str) -> String {
for c in ['`', '"', '\''] {
if partial.starts_with(c) {
let ret = partial.strip_prefix(c).unwrap_or(partial);
return match ret.split(c).collect::<Vec<_>>()[..] {
[inside] => inside.to_string(),
[inside, outside] if inside.ends_with(is_separator) => format!("{inside}{outside}"),
_ => ret.to_string(),
};
}
}
partial.to_string()
}
pub fn complete_item(
want_directory: bool,
span: nu_protocol::Span,
partial: &str,
cwd: &str,
options: &CompletionOptions,
engine_state: &EngineState,
stack: &Stack,
) -> Vec<(nu_protocol::Span, String, Option<Style>)> {
let cleaned_partial = surround_remove(partial);
let isdir = cleaned_partial.ends_with(is_separator);
let expanded_partial = expand_ndots(Path::new(&cleaned_partial));
let should_collapse_dots = expanded_partial != Path::new(&cleaned_partial);
let mut partial = expanded_partial.to_string_lossy().to_string();
#[cfg(unix)]
let path_separator = SEP;
#[cfg(windows)]
let path_separator = cleaned_partial
.chars()
.rfind(|c: &char| is_separator(*c))
.unwrap_or(SEP);
// Handle the trailing dot case
if cleaned_partial.ends_with(&format!("{path_separator}.")) {
partial.push_str(&format!("{path_separator}."));
}
let cwd_pathbuf = Path::new(cwd).to_path_buf();
let ls_colors = (engine_state.config.completions.use_ls_colors
&& engine_state.config.use_ansi_coloring)
.then(|| {
let ls_colors_env_str = match stack.get_env_var(engine_state, "LS_COLORS") {
Some(v) => env_to_string("LS_COLORS", v, engine_state, stack).ok(),
None => None,
};
get_ls_colors(ls_colors_env_str)
});
let mut cwd = cwd_pathbuf.clone();
let mut prefix_len = 0;
let mut original_cwd = OriginalCwd::None;
let mut components = Path::new(&partial).components().peekable();
match components.peek().cloned() {
Some(c @ Component::Prefix(..)) => {
// windows only by definition
cwd = [c, Component::RootDir].iter().collect();
prefix_len = c.as_os_str().len();
original_cwd = OriginalCwd::Prefix(c.as_os_str().to_string_lossy().into_owned());
}
Some(c @ Component::RootDir) => {
// This is kind of a hack. When joining an empty string with the rest,
// we add the slash automagically
cwd = PathBuf::from(c.as_os_str());
prefix_len = 1;
original_cwd = OriginalCwd::Prefix(String::new());
}
Some(Component::Normal(home)) if home.to_string_lossy() == "~" => {
cwd = home_dir().map(Into::into).unwrap_or(cwd_pathbuf);
prefix_len = 1;
original_cwd = OriginalCwd::Home;
}
_ => {}
};
let after_prefix = &partial[prefix_len..];
let partial: Vec<_> = after_prefix
.strip_prefix(is_separator)
.unwrap_or(after_prefix)
.split(is_separator)
.filter(|s| !s.is_empty())
.collect();
complete_rec(
partial.as_slice(),
&PathBuiltFromString::default(),
&cwd,
options,
want_directory,
isdir,
)
.into_iter()
.map(|mut p| {
if should_collapse_dots {
p = collapse_ndots(p);
}
let path = original_cwd.apply(p, path_separator);
let style = ls_colors.as_ref().map(|lsc| {
lsc.style_for_path_with_metadata(
&path,
std::fs::symlink_metadata(expand_to_real_path(&path))
.ok()
.as_ref(),
)
.map(lscolors::Style::to_nu_ansi_term_style)
.unwrap_or_default()
});
(span, escape_path(path, want_directory), style)
})
.collect()
}
// Fix files or folders with quotes or hashes
pub fn escape_path(path: String, dir: bool) -> String {
// make glob pattern have the highest priority.
let glob_contaminated = path.contains(['[', '*', ']', '?']);
if glob_contaminated {
return if path.contains('\'') {
// decide to use double quote, also need to escape `"` in path
// or else users can't do anything with completed path either.
format!("\"{}\"", path.replace('"', r#"\""#))
} else {
format!("'{path}'")
};
}
let filename_contaminated = !dir && path.contains(['\'', '"', ' ', '#', '(', ')']);
let dirname_contaminated = dir && path.contains(['\'', '"', ' ', '#']);
let maybe_flag = path.starts_with('-');
let maybe_variable = path.starts_with('$');
let maybe_number = path.parse::<f64>().is_ok();
if filename_contaminated || dirname_contaminated || maybe_flag || maybe_variable || maybe_number
{
format!("`{path}`")
} else {
path
}
}
pub struct AdjustView {
pub prefix: String,
pub span: Span,
pub readjusted: bool,
}
pub fn adjust_if_intermediate(
prefix: &[u8],
working_set: &StateWorkingSet,
mut span: nu_protocol::Span,
) -> AdjustView {
let span_contents = String::from_utf8_lossy(working_set.get_span_contents(span)).to_string();
let mut prefix = String::from_utf8_lossy(prefix).to_string();
// A difference of 1 because of the cursor's unicode code point in between.
// Using .chars().count() because unicode and Windows.
let readjusted = span_contents.chars().count() - prefix.chars().count() > 1;
if readjusted {
let remnant: String = span_contents
.chars()
.skip(prefix.chars().count() + 1)
.take_while(|&c| !is_separator(c))
.collect();
prefix.push_str(&remnant);
span = Span::new(span.start, span.start + prefix.chars().count() + 1);
}
AdjustView {
prefix,
span,
readjusted,
}
}
/// Convenience function to sort suggestions using [`sort_completions`]
pub fn sort_suggestions(
prefix: &str,
items: Vec<SemanticSuggestion>,
options: &CompletionOptions,
) -> Vec<SemanticSuggestion> {
sort_completions(prefix, items, options, |it| &it.suggestion.value)
}
/// # Arguments
/// * `prefix` - What the user's typed, for sorting by fuzzy matcher score
pub fn sort_completions<T>(
prefix: &str,
mut items: Vec<T>,
options: &CompletionOptions,
get_value: fn(&T) -> &str,
) -> Vec<T> {
// Sort items
if options.sort == CompletionSort::Smart && options.match_algorithm == MatchAlgorithm::Fuzzy {
let mut matcher = SkimMatcherV2::default();
if options.case_sensitive {
matcher = matcher.respect_case();
} else {
matcher = matcher.ignore_case();
};
items.sort_unstable_by(|a, b| {
let a_str = get_value(a);
let b_str = get_value(b);
let a_score = matcher.fuzzy_match(a_str, prefix).unwrap_or_default();
let b_score = matcher.fuzzy_match(b_str, prefix).unwrap_or_default();
b_score.cmp(&a_score).then(a_str.cmp(b_str))
});
} else {
items.sort_unstable_by(|a, b| get_value(a).cmp(get_value(b)));
}
items
}
/// Collapse multiple ".." components into n-dots.
///
/// It performs the reverse operation of `expand_ndots`, collapsing sequences of ".." into n-dots,
/// such as "..." and "....".
///
/// The resulting path will use platform-specific path separators, regardless of what path separators were used in the input.
fn collapse_ndots(path: PathBuiltFromString) -> PathBuiltFromString {
let mut result = PathBuiltFromString {
parts: Vec::with_capacity(path.parts.len()),
isdir: path.isdir,
};
let mut dot_count = 0;
for part in path.parts {
if part == ".." {
dot_count += 1;
} else {
if dot_count > 0 {
result.parts.push(".".repeat(dot_count + 1));
dot_count = 0;
}
result.parts.push(part);
}
}
// Add any remaining dots
if dot_count > 0 {
result.parts.push(".".repeat(dot_count + 1));
}
result
}

View File

@ -1,10 +1,17 @@
use fuzzy_matcher::{skim::SkimMatcherV2, FuzzyMatcher};
use nu_parser::trim_quotes_str;
use nu_protocol::{CompletionAlgorithm, CompletionSort};
use std::fmt::Display; use std::fmt::Display;
use fuzzy_matcher::{skim::SkimMatcherV2, FuzzyMatcher};
use nu_parser::trim_quotes_str;
#[derive(Copy, Clone)]
pub enum SortBy {
LevenshteinDistance,
Ascending,
None,
}
/// Describes how suggestions should be matched. /// Describes how suggestions should be matched.
#[derive(Copy, Clone, Debug, PartialEq)] #[derive(Copy, Clone, Debug)]
pub enum MatchAlgorithm { pub enum MatchAlgorithm {
/// Only show suggestions which begin with the given input /// Only show suggestions which begin with the given input
/// ///
@ -48,15 +55,6 @@ impl MatchAlgorithm {
} }
} }
impl From<CompletionAlgorithm> for MatchAlgorithm {
fn from(value: CompletionAlgorithm) -> Self {
match value {
CompletionAlgorithm::Prefix => MatchAlgorithm::Prefix,
CompletionAlgorithm::Fuzzy => MatchAlgorithm::Fuzzy,
}
}
}
impl TryFrom<String> for MatchAlgorithm { impl TryFrom<String> for MatchAlgorithm {
type Error = InvalidMatchAlgorithm; type Error = InvalidMatchAlgorithm;
@ -88,8 +86,8 @@ impl std::error::Error for InvalidMatchAlgorithm {}
pub struct CompletionOptions { pub struct CompletionOptions {
pub case_sensitive: bool, pub case_sensitive: bool,
pub positional: bool, pub positional: bool,
pub sort_by: SortBy,
pub match_algorithm: MatchAlgorithm, pub match_algorithm: MatchAlgorithm,
pub sort: CompletionSort,
} }
impl Default for CompletionOptions { impl Default for CompletionOptions {
@ -97,8 +95,8 @@ impl Default for CompletionOptions {
Self { Self {
case_sensitive: true, case_sensitive: true,
positional: true, positional: true,
sort_by: SortBy::Ascending,
match_algorithm: MatchAlgorithm::Prefix, match_algorithm: MatchAlgorithm::Prefix,
sort: Default::default(),
} }
} }
} }

View File

@ -1,31 +1,31 @@
use crate::completions::{ use crate::completions::{Completer, CompletionOptions, MatchAlgorithm, SortBy};
completer::map_value_completions, Completer, CompletionOptions, MatchAlgorithm,
SemanticSuggestion,
};
use nu_engine::eval_call; use nu_engine::eval_call;
use nu_protocol::{ use nu_protocol::{
ast::{Argument, Call, Expr, Expression}, ast::{Argument, Call, Expr, Expression},
debugger::WithoutDebug, engine::{EngineState, Stack, StateWorkingSet},
engine::{Stack, StateWorkingSet}, PipelineData, Span, Type, Value,
CompletionSort, DeclId, PipelineData, Span, Type, Value,
}; };
use nu_utils::IgnoreCaseExt; use reedline::Suggestion;
use std::collections::HashMap; use std::sync::Arc;
use super::completion_common::sort_suggestions; use super::completer::map_value_completions;
pub struct CustomCompletion { pub struct CustomCompletion {
engine_state: Arc<EngineState>,
stack: Stack, stack: Stack,
decl_id: DeclId, decl_id: usize,
line: String, line: String,
sort_by: SortBy,
} }
impl CustomCompletion { impl CustomCompletion {
pub fn new(stack: Stack, decl_id: DeclId, line: String) -> Self { pub fn new(engine_state: Arc<EngineState>, stack: Stack, decl_id: usize, line: String) -> Self {
Self { Self {
engine_state,
stack, stack,
decl_id, decl_id,
line, line,
sort_by: SortBy::None,
} }
} }
} }
@ -33,121 +33,130 @@ impl CustomCompletion {
impl Completer for CustomCompletion { impl Completer for CustomCompletion {
fn fetch( fn fetch(
&mut self, &mut self,
working_set: &StateWorkingSet, _: &StateWorkingSet,
_stack: &Stack, prefix: Vec<u8>,
prefix: &[u8],
span: Span, span: Span,
offset: usize, offset: usize,
pos: usize, pos: usize,
completion_options: &CompletionOptions, completion_options: &CompletionOptions,
) -> Vec<SemanticSuggestion> { ) -> Vec<Suggestion> {
// Line position // Line position
let line_pos = pos - offset; let line_pos = pos - offset;
// Call custom declaration // Call custom declaration
let result = eval_call::<WithoutDebug>( let result = eval_call(
working_set.permanent_state, &self.engine_state,
&mut self.stack, &mut self.stack,
&Call { &Call {
decl_id: self.decl_id, decl_id: self.decl_id,
head: span, head: span,
arguments: vec![ arguments: vec![
Argument::Positional(Expression::new_unknown( Argument::Positional(Expression {
Expr::String(self.line.clone()), span: Span { start: 0, end: 0 },
Span::unknown(), ty: Type::String,
Type::String, expr: Expr::String(self.line.clone()),
)), custom_completion: None,
Argument::Positional(Expression::new_unknown( }),
Expr::Int(line_pos as i64), Argument::Positional(Expression {
Span::unknown(), span: Span { start: 0, end: 0 },
Type::Int, ty: Type::Int,
)), expr: Expr::Int(line_pos as i64),
custom_completion: None,
}),
], ],
parser_info: HashMap::new(), redirect_stdout: true,
redirect_stderr: true,
}, },
PipelineData::empty(), PipelineData::new(span),
); );
let mut custom_completion_options = None; let mut custom_completion_options = None;
// Parse result // Parse result
let suggestions = result let suggestions = match result {
.and_then(|data| data.into_value(span)) Ok(pd) => {
.map(|value| match &value { let value = pd.into_value(span);
Value::Record { val, .. } => { match &value {
let completions = val Value::Record { .. } => {
.get("completions") let completions = value
.and_then(|val| { .get_data_by_key("completions")
val.as_list() .and_then(|val| {
.ok() val.as_list()
.map(|it| map_value_completions(it.iter(), span, offset))
})
.unwrap_or_default();
let options = val.get("options");
if let Some(Value::Record { val: options, .. }) = &options {
let should_sort = options
.get("sort")
.and_then(|val| val.as_bool().ok())
.unwrap_or(false);
custom_completion_options = Some(CompletionOptions {
case_sensitive: options
.get("case_sensitive")
.and_then(|val| val.as_bool().ok())
.unwrap_or(true),
positional: options
.get("positional")
.and_then(|val| val.as_bool().ok())
.unwrap_or(true),
match_algorithm: match options.get("completion_algorithm") {
Some(option) => option
.coerce_string()
.ok() .ok()
.and_then(|option| option.try_into().ok()) .map(|it| map_value_completions(it.iter(), span, offset))
.unwrap_or(MatchAlgorithm::Prefix), })
None => completion_options.match_algorithm, .unwrap_or_default();
}, let options = value.get_data_by_key("options");
sort: if should_sort {
CompletionSort::Alphabetical if let Some(Value::Record { .. }) = &options {
} else { let options = options.unwrap_or_default();
CompletionSort::Smart let should_sort = options
}, .get_data_by_key("sort")
}); .and_then(|val| val.as_bool().ok())
.unwrap_or(false);
if should_sort {
self.sort_by = SortBy::Ascending;
}
custom_completion_options = Some(CompletionOptions {
case_sensitive: options
.get_data_by_key("case_sensitive")
.and_then(|val| val.as_bool().ok())
.unwrap_or(true),
positional: options
.get_data_by_key("positional")
.and_then(|val| val.as_bool().ok())
.unwrap_or(true),
sort_by: if should_sort {
SortBy::Ascending
} else {
SortBy::None
},
match_algorithm: match options
.get_data_by_key("completion_algorithm")
{
Some(option) => option
.as_string()
.ok()
.and_then(|option| option.try_into().ok())
.unwrap_or(MatchAlgorithm::Prefix),
None => completion_options.match_algorithm,
},
});
}
completions
} }
Value::List { vals, .. } => map_value_completions(vals.iter(), span, offset),
completions _ => vec![],
} }
Value::List { vals, .. } => map_value_completions(vals.iter(), span, offset), }
_ => vec![], _ => vec![],
}) };
.unwrap_or_default();
let options = custom_completion_options if let Some(custom_completion_options) = custom_completion_options {
.as_ref() filter(&prefix, suggestions, &custom_completion_options)
.unwrap_or(completion_options); } else {
let suggestions = filter(prefix, suggestions, options); filter(&prefix, suggestions, completion_options)
sort_suggestions(&String::from_utf8_lossy(prefix), suggestions, options) }
}
fn get_sort_by(&self) -> SortBy {
self.sort_by
} }
} }
fn filter( fn filter(prefix: &[u8], items: Vec<Suggestion>, options: &CompletionOptions) -> Vec<Suggestion> {
prefix: &[u8],
items: Vec<SemanticSuggestion>,
options: &CompletionOptions,
) -> Vec<SemanticSuggestion> {
items items
.into_iter() .into_iter()
.filter(|it| match options.match_algorithm { .filter(|it| match options.match_algorithm {
MatchAlgorithm::Prefix => match (options.case_sensitive, options.positional) { MatchAlgorithm::Prefix => match (options.case_sensitive, options.positional) {
(true, true) => it.suggestion.value.as_bytes().starts_with(prefix), (true, true) => it.value.as_bytes().starts_with(prefix),
(true, false) => it (true, false) => it.value.contains(std::str::from_utf8(prefix).unwrap_or("")),
.suggestion
.value
.contains(std::str::from_utf8(prefix).unwrap_or("")),
(false, positional) => { (false, positional) => {
let value = it.suggestion.value.to_folded_case(); let value = it.value.to_lowercase();
let prefix = std::str::from_utf8(prefix).unwrap_or("").to_folded_case(); let prefix = std::str::from_utf8(prefix).unwrap_or("").to_lowercase();
if positional { if positional {
value.starts_with(&prefix) value.starts_with(&prefix)
} else { } else {
@ -157,7 +166,7 @@ fn filter(
}, },
MatchAlgorithm::Fuzzy => options MatchAlgorithm::Fuzzy => options
.match_algorithm .match_algorithm
.matches_u8(it.suggestion.value.as_bytes(), prefix), .matches_u8(it.value.as_bytes(), prefix),
}) })
.collect() .collect()
} }

View File

@ -1,71 +1,85 @@
use crate::completions::{ use crate::completions::{matches, Completer, CompletionOptions};
completion_common::{adjust_if_intermediate, complete_item, AdjustView},
Completer, CompletionOptions,
};
use nu_ansi_term::Style;
use nu_protocol::{ use nu_protocol::{
engine::{EngineState, Stack, StateWorkingSet}, engine::{EngineState, StateWorkingSet},
Span, levenshtein_distance, Span,
}; };
use reedline::Suggestion; use reedline::Suggestion;
use std::fs;
use std::path::Path; use std::path::Path;
use std::sync::Arc;
use super::SemanticSuggestion; use super::{partial_from, prepend_base_dir};
#[derive(Clone, Default)] const SEP: char = std::path::MAIN_SEPARATOR;
pub struct DirectoryCompletion {}
#[derive(Clone)]
pub struct DirectoryCompletion {
engine_state: Arc<EngineState>,
}
impl DirectoryCompletion { impl DirectoryCompletion {
pub fn new() -> Self { pub fn new(engine_state: Arc<EngineState>) -> Self {
Self::default() Self { engine_state }
} }
} }
impl Completer for DirectoryCompletion { impl Completer for DirectoryCompletion {
fn fetch( fn fetch(
&mut self, &mut self,
working_set: &StateWorkingSet, _: &StateWorkingSet,
stack: &Stack, prefix: Vec<u8>,
prefix: &[u8],
span: Span, span: Span,
offset: usize, offset: usize,
_pos: usize, _: usize,
options: &CompletionOptions, options: &CompletionOptions,
) -> Vec<SemanticSuggestion> { ) -> Vec<Suggestion> {
let AdjustView { prefix, span, .. } = adjust_if_intermediate(prefix, working_set, span); let cwd = if let Some(d) = self.engine_state.get_env_var("PWD") {
match d.as_string() {
Ok(s) => s,
Err(_) => "".to_string(),
}
} else {
"".to_string()
};
let partial = String::from_utf8_lossy(&prefix).to_string();
// Filter only the folders // Filter only the folders
#[allow(deprecated)] let output: Vec<_> = directory_completion(span, &partial, &cwd, options)
let items: Vec<_> = directory_completion( .into_iter()
span, .map(move |x| Suggestion {
&prefix,
&working_set.permanent_state.current_work_dir(),
options,
working_set.permanent_state,
stack,
)
.into_iter()
.map(move |x| SemanticSuggestion {
suggestion: Suggestion {
value: x.1, value: x.1,
style: x.2, description: None,
extra: None,
span: reedline::Span { span: reedline::Span {
start: x.0.start - offset, start: x.0.start - offset,
end: x.0.end - offset, end: x.0.end - offset,
}, },
..Suggestion::default() append_whitespace: false,
}, })
// TODO???? .collect();
kind: None,
}) output
.collect(); }
// Sort results prioritizing the non hidden folders
fn sort(&self, items: Vec<Suggestion>, prefix: Vec<u8>) -> Vec<Suggestion> {
let prefix_str = String::from_utf8_lossy(&prefix).to_string();
// Sort items
let mut sorted_items = items;
sorted_items.sort_by(|a, b| a.value.cmp(&b.value));
sorted_items.sort_by(|a, b| {
let a_distance = levenshtein_distance(&prefix_str, &a.value);
let b_distance = levenshtein_distance(&prefix_str, &b.value);
a_distance.cmp(&b_distance)
});
// Separate the results between hidden and non hidden // Separate the results between hidden and non hidden
let mut hidden: Vec<SemanticSuggestion> = vec![]; let mut hidden: Vec<Suggestion> = vec![];
let mut non_hidden: Vec<SemanticSuggestion> = vec![]; let mut non_hidden: Vec<Suggestion> = vec![];
for item in items.into_iter() { for item in sorted_items.into_iter() {
let item_path = Path::new(&item.suggestion.value); let item_path = Path::new(&item.value);
if let Some(value) = item_path.file_name() { if let Some(value) = item_path.file_name() {
if let Some(value) = value.to_str() { if let Some(value) = value.to_str() {
@ -90,8 +104,57 @@ pub fn directory_completion(
partial: &str, partial: &str,
cwd: &str, cwd: &str,
options: &CompletionOptions, options: &CompletionOptions,
engine_state: &EngineState, ) -> Vec<(nu_protocol::Span, String)> {
stack: &Stack, let original_input = partial;
) -> Vec<(nu_protocol::Span, String, Option<Style>)> {
complete_item(true, span, partial, cwd, options, engine_state, stack) let (base_dir_name, partial) = partial_from(partial);
let base_dir = nu_path::expand_path_with(&base_dir_name, cwd);
// This check is here as base_dir.read_dir() with base_dir == "" will open the current dir
// which we don't want in this case (if we did, base_dir would already be ".")
if base_dir == Path::new("") {
return Vec::new();
}
if let Ok(result) = base_dir.read_dir() {
return result
.filter_map(|entry| {
entry.ok().and_then(|entry| {
if let Ok(metadata) = fs::metadata(entry.path()) {
if metadata.is_dir() {
let mut file_name = entry.file_name().to_string_lossy().into_owned();
if matches(&partial, &file_name, options) {
let mut path = if prepend_base_dir(original_input, &base_dir_name) {
format!("{}{}", base_dir_name, file_name)
} else {
file_name.to_string()
};
if entry.path().is_dir() {
path.push(SEP);
file_name.push(SEP);
}
// Fix files or folders with quotes
if path.contains('\'') || path.contains('"') || path.contains(' ') {
path = format!("`{}`", path);
}
Some((span, path))
} else {
None
}
} else {
None
}
} else {
None
}
})
})
.collect();
}
Vec::new()
} }

View File

@ -1,69 +1,64 @@
use crate::completions::{file_path_completion, Completer, CompletionOptions}; use crate::completions::{
file_path_completion, partial_from, Completer, CompletionOptions, SortBy,
};
use nu_protocol::{ use nu_protocol::{
engine::{Stack, StateWorkingSet}, engine::{EngineState, StateWorkingSet},
Span, Span,
}; };
use reedline::Suggestion; use reedline::Suggestion;
use std::path::{is_separator, Path, MAIN_SEPARATOR as SEP, MAIN_SEPARATOR_STR}; use std::sync::Arc;
const SEP: char = std::path::MAIN_SEPARATOR;
use super::{completion_common::sort_suggestions, SemanticSuggestion}; #[derive(Clone)]
pub struct DotNuCompletion {
#[derive(Clone, Default)] engine_state: Arc<EngineState>,
pub struct DotNuCompletion {} }
impl DotNuCompletion { impl DotNuCompletion {
pub fn new() -> Self { pub fn new(engine_state: Arc<EngineState>) -> Self {
Self::default() Self { engine_state }
} }
} }
impl Completer for DotNuCompletion { impl Completer for DotNuCompletion {
fn fetch( fn fetch(
&mut self, &mut self,
working_set: &StateWorkingSet, _: &StateWorkingSet,
stack: &Stack, prefix: Vec<u8>,
prefix: &[u8],
span: Span, span: Span,
offset: usize, offset: usize,
_pos: usize, _: usize,
options: &CompletionOptions, options: &CompletionOptions,
) -> Vec<SemanticSuggestion> { ) -> Vec<Suggestion> {
let prefix_str = String::from_utf8_lossy(prefix).replace('`', ""); let prefix_str = String::from_utf8_lossy(&prefix).to_string();
let mut search_dirs: Vec<String> = vec![]; let mut search_dirs: Vec<String> = vec![];
let (base_dir, mut partial) = partial_from(&prefix_str);
// If prefix_str is only a word we want to search in the current dir
let (base, partial) = prefix_str
.rsplit_once(is_separator)
.unwrap_or((".", &prefix_str));
let base_dir = base.replace(is_separator, MAIN_SEPARATOR_STR);
let mut partial = partial.to_string();
// On windows, this standardizes paths to use \
let mut is_current_folder = false; let mut is_current_folder = false;
// Fetch the lib dirs // Fetch the lib dirs
let lib_dirs: Vec<String> = if let Some(lib_dirs) = working_set.get_env_var("NU_LIB_DIRS") { let lib_dirs: Vec<String> =
lib_dirs if let Some(lib_dirs) = self.engine_state.get_env_var("NU_LIB_DIRS") {
.as_list() lib_dirs
.into_iter() .as_list()
.flat_map(|it| { .into_iter()
it.iter().map(|x| { .flat_map(|it| {
x.to_path() it.iter().map(|x| {
.expect("internal error: failed to convert lib path") x.as_path()
.expect("internal error: failed to convert lib path")
})
}) })
}) .map(|it| {
.map(|it| { it.into_os_string()
it.into_os_string() .into_string()
.into_string() .expect("internal error: failed to convert OS path")
.expect("internal error: failed to convert OS path") })
}) .collect()
.collect() } else {
} else { vec![]
vec![] };
};
// Check if the base_dir is a folder // Check if the base_dir is a folder
// rsplit_once removes the separator if base_dir != format!(".{}", SEP) {
if base_dir != "." {
// Add the base dir into the directories to be searched // Add the base dir into the directories to be searched
search_dirs.push(base_dir.clone()); search_dirs.push(base_dir.clone());
@ -75,8 +70,14 @@ impl Completer for DotNuCompletion {
partial = base_dir_partial; partial = base_dir_partial;
} else { } else {
// Fetch the current folder // Fetch the current folder
#[allow(deprecated)] let current_folder = if let Some(d) = self.engine_state.get_env_var("PWD") {
let current_folder = working_set.permanent_state.current_work_dir(); match d.as_string() {
Ok(s) => s,
Err(_) => "".to_string(),
}
} else {
"".to_string()
};
is_current_folder = true; is_current_folder = true;
// Add the current folder and the lib dirs into the // Add the current folder and the lib dirs into the
@ -87,49 +88,37 @@ impl Completer for DotNuCompletion {
// Fetch the files filtering the ones that ends with .nu // Fetch the files filtering the ones that ends with .nu
// and transform them into suggestions // and transform them into suggestions
let output: Vec<SemanticSuggestion> = search_dirs let output: Vec<Suggestion> = search_dirs
.into_iter() .into_iter()
.flat_map(|search_dir| { .flat_map(|it| {
let completions = file_path_completion( file_path_completion(span, &partial, &it, options)
span,
&partial,
&search_dir,
options,
working_set.permanent_state,
stack,
);
completions
.into_iter() .into_iter()
.filter(move |it| { .filter(|it| {
// Different base dir, so we list the .nu files or folders // Different base dir, so we list the .nu files or folders
if !is_current_folder { if !is_current_folder {
it.1.ends_with(".nu") || it.1.ends_with(SEP) it.1.ends_with(".nu") || it.1.ends_with(SEP)
} else { } else {
// Lib dirs, so we filter only the .nu files or directory modules // Lib dirs, so we filter only the .nu files
if it.1.ends_with(SEP) { it.1.ends_with(".nu")
Path::new(&search_dir).join(&it.1).join("mod.nu").exists()
} else {
it.1.ends_with(".nu")
}
} }
}) })
.map(move |x| SemanticSuggestion { .map(move |x| Suggestion {
suggestion: Suggestion { value: x.1,
value: x.1, description: None,
style: x.2, extra: None,
span: reedline::Span { span: reedline::Span {
start: x.0.start - offset, start: x.0.start - offset,
end: x.0.end - offset, end: x.0.end - offset,
},
append_whitespace: true,
..Suggestion::default()
}, },
// TODO???? append_whitespace: true,
kind: None,
}) })
}) })
.collect(); .collect();
sort_suggestions(&prefix_str, output, options) output
}
fn get_sort_by(&self) -> SortBy {
SortBy::LevenshteinDistance
} }
} }

View File

@ -1,78 +1,80 @@
use crate::completions::{ use crate::completions::{Completer, CompletionOptions};
completion_common::{adjust_if_intermediate, complete_item, AdjustView},
Completer, CompletionOptions,
};
use nu_ansi_term::Style;
use nu_protocol::{ use nu_protocol::{
engine::{EngineState, Stack, StateWorkingSet}, engine::{EngineState, StateWorkingSet},
Span, levenshtein_distance, Span,
}; };
use nu_utils::IgnoreCaseExt;
use reedline::Suggestion; use reedline::Suggestion;
use std::path::Path; use std::path::{is_separator, Path};
use std::sync::Arc;
use super::SemanticSuggestion; const SEP: char = std::path::MAIN_SEPARATOR;
#[derive(Clone, Default)] #[derive(Clone)]
pub struct FileCompletion {} pub struct FileCompletion {
engine_state: Arc<EngineState>,
}
impl FileCompletion { impl FileCompletion {
pub fn new() -> Self { pub fn new(engine_state: Arc<EngineState>) -> Self {
Self::default() Self { engine_state }
} }
} }
impl Completer for FileCompletion { impl Completer for FileCompletion {
fn fetch( fn fetch(
&mut self, &mut self,
working_set: &StateWorkingSet, _: &StateWorkingSet,
stack: &Stack, prefix: Vec<u8>,
prefix: &[u8],
span: Span, span: Span,
offset: usize, offset: usize,
_pos: usize, _: usize,
options: &CompletionOptions, options: &CompletionOptions,
) -> Vec<SemanticSuggestion> { ) -> Vec<Suggestion> {
let AdjustView { let cwd = if let Some(d) = self.engine_state.get_env_var("PWD") {
prefix, match d.as_string() {
span, Ok(s) => s,
readjusted, Err(_) => "".to_string(),
} = adjust_if_intermediate(prefix, working_set, span); }
} else {
#[allow(deprecated)] "".to_string()
let items: Vec<_> = complete_item( };
readjusted, let prefix = String::from_utf8_lossy(&prefix).to_string();
span, let output: Vec<_> = file_path_completion(span, &prefix, &cwd, options)
&prefix, .into_iter()
&working_set.permanent_state.current_work_dir(), .map(move |x| Suggestion {
options,
working_set.permanent_state,
stack,
)
.into_iter()
.map(move |x| SemanticSuggestion {
suggestion: Suggestion {
value: x.1, value: x.1,
style: x.2, description: None,
extra: None,
span: reedline::Span { span: reedline::Span {
start: x.0.start - offset, start: x.0.start - offset,
end: x.0.end - offset, end: x.0.end - offset,
}, },
..Suggestion::default() append_whitespace: false,
}, })
// TODO???? .collect();
kind: None,
})
.collect();
// Sort results prioritizing the non hidden folders output
}
// Sort results prioritizing the non hidden folders
fn sort(&self, items: Vec<Suggestion>, prefix: Vec<u8>) -> Vec<Suggestion> {
let prefix_str = String::from_utf8_lossy(&prefix).to_string();
// Sort items
let mut sorted_items = items;
sorted_items.sort_by(|a, b| a.value.cmp(&b.value));
sorted_items.sort_by(|a, b| {
let a_distance = levenshtein_distance(&prefix_str, &a.value);
let b_distance = levenshtein_distance(&prefix_str, &b.value);
a_distance.cmp(&b_distance)
});
// Separate the results between hidden and non hidden // Separate the results between hidden and non hidden
let mut hidden: Vec<SemanticSuggestion> = vec![]; let mut hidden: Vec<Suggestion> = vec![];
let mut non_hidden: Vec<SemanticSuggestion> = vec![]; let mut non_hidden: Vec<Suggestion> = vec![];
for item in items.into_iter() { for item in sorted_items.into_iter() {
let item_path = Path::new(&item.suggestion.value); let item_path = Path::new(&item.value);
if let Some(value) = item_path.file_name() { if let Some(value) = item_path.file_name() {
if let Some(value) = value.to_str() { if let Some(value) = value.to_str() {
@ -92,15 +94,68 @@ impl Completer for FileCompletion {
} }
} }
pub fn partial_from(input: &str) -> (String, String) {
let partial = input.replace('`', "");
// If partial is only a word we want to search in the current dir
let (base, rest) = partial.rsplit_once(is_separator).unwrap_or((".", &partial));
// On windows, this standardizes paths to use \
let mut base = base.replace(is_separator, &SEP.to_string());
// rsplit_once removes the separator
base.push(SEP);
(base.to_string(), rest.to_string())
}
pub fn file_path_completion( pub fn file_path_completion(
span: nu_protocol::Span, span: nu_protocol::Span,
partial: &str, partial: &str,
cwd: &str, cwd: &str,
options: &CompletionOptions, options: &CompletionOptions,
engine_state: &EngineState, ) -> Vec<(nu_protocol::Span, String)> {
stack: &Stack, let original_input = partial;
) -> Vec<(nu_protocol::Span, String, Option<Style>)> { let (base_dir_name, partial) = partial_from(partial);
complete_item(false, span, partial, cwd, options, engine_state, stack)
let base_dir = nu_path::expand_path_with(&base_dir_name, cwd);
// This check is here as base_dir.read_dir() with base_dir == "" will open the current dir
// which we don't want in this case (if we did, base_dir would already be ".")
if base_dir == Path::new("") {
return Vec::new();
}
if let Ok(result) = base_dir.read_dir() {
return result
.filter_map(|entry| {
entry.ok().and_then(|entry| {
let mut file_name = entry.file_name().to_string_lossy().into_owned();
if matches(&partial, &file_name, options) {
let mut path = if prepend_base_dir(original_input, &base_dir_name) {
format!("{}{}", base_dir_name, file_name)
} else {
file_name.to_string()
};
if entry.path().is_dir() {
path.push(SEP);
file_name.push(SEP);
}
// Fix files or folders with quotes
if path.contains('\'') || path.contains('"') || path.contains(' ') {
path = format!("`{}`", path);
}
Some((span, path))
} else {
None
}
})
})
.collect();
}
Vec::new()
} }
pub fn matches(partial: &str, from: &str, options: &CompletionOptions) -> bool { pub fn matches(partial: &str, from: &str, options: &CompletionOptions) -> bool {
@ -108,8 +163,28 @@ pub fn matches(partial: &str, from: &str, options: &CompletionOptions) -> bool {
if !options.case_sensitive { if !options.case_sensitive {
return options return options
.match_algorithm .match_algorithm
.matches_str(&from.to_folded_case(), &partial.to_folded_case()); .matches_str(&from.to_ascii_lowercase(), &partial.to_ascii_lowercase());
} }
options.match_algorithm.matches_str(from, partial) options.match_algorithm.matches_str(from, partial)
} }
/// Returns whether the base_dir should be prepended to the file path
pub fn prepend_base_dir(input: &str, base_dir: &str) -> bool {
if base_dir == format!(".{}", SEP) {
// if the current base_dir path is the local folder we only add a "./" prefix if the user
// input already includes a local folder prefix.
let manually_entered = {
let mut chars = input.chars();
let first_char = chars.next();
let second_char = chars.next();
first_char == Some('.') && second_char.map(is_separator).unwrap_or(false)
};
manually_entered
} else {
// always prepend the base dir if it is a subfolder
true
}
}

View File

@ -1,12 +1,11 @@
use crate::completions::{completion_common::sort_suggestions, Completer, CompletionOptions}; use crate::completions::{Completer, CompletionOptions};
use nu_protocol::{ use nu_protocol::{
ast::{Expr, Expression}, ast::{Expr, Expression},
engine::{Stack, StateWorkingSet}, engine::StateWorkingSet,
Span, Span,
}; };
use reedline::Suggestion;
use super::SemanticSuggestion; use reedline::Suggestion;
#[derive(Clone)] #[derive(Clone)]
pub struct FlagCompletion { pub struct FlagCompletion {
@ -23,13 +22,12 @@ impl Completer for FlagCompletion {
fn fetch( fn fetch(
&mut self, &mut self,
working_set: &StateWorkingSet, working_set: &StateWorkingSet,
_stack: &Stack, prefix: Vec<u8>,
prefix: &[u8],
span: Span, span: Span,
offset: usize, offset: usize,
_pos: usize, _: usize,
options: &CompletionOptions, options: &CompletionOptions,
) -> Vec<SemanticSuggestion> { ) -> Vec<Suggestion> {
// Check if it's a flag // Check if it's a flag
if let Expr::Call(call) = &self.expression.expr { if let Expr::Call(call) = &self.expression.expr {
let decl = working_set.get_decl(call.decl_id); let decl = working_set.get_decl(call.decl_id);
@ -44,20 +42,16 @@ impl Completer for FlagCompletion {
short.encode_utf8(&mut named); short.encode_utf8(&mut named);
named.insert(0, b'-'); named.insert(0, b'-');
if options.match_algorithm.matches_u8(&named, prefix) { if options.match_algorithm.matches_u8(&named, &prefix) {
output.push(SemanticSuggestion { output.push(Suggestion {
suggestion: Suggestion { value: String::from_utf8_lossy(&named).to_string(),
value: String::from_utf8_lossy(&named).to_string(), description: Some(flag_desc.to_string()),
description: Some(flag_desc.to_string()), extra: None,
span: reedline::Span { span: reedline::Span {
start: span.start - offset, start: span.start - offset,
end: span.end - offset, end: span.end - offset,
},
append_whitespace: true,
..Suggestion::default()
}, },
// TODO???? append_whitespace: true,
kind: None,
}); });
} }
} }
@ -70,25 +64,21 @@ impl Completer for FlagCompletion {
named.insert(0, b'-'); named.insert(0, b'-');
named.insert(0, b'-'); named.insert(0, b'-');
if options.match_algorithm.matches_u8(&named, prefix) { if options.match_algorithm.matches_u8(&named, &prefix) {
output.push(SemanticSuggestion { output.push(Suggestion {
suggestion: Suggestion { value: String::from_utf8_lossy(&named).to_string(),
value: String::from_utf8_lossy(&named).to_string(), description: Some(flag_desc.to_string()),
description: Some(flag_desc.to_string()), extra: None,
span: reedline::Span { span: reedline::Span {
start: span.start - offset, start: span.start - offset,
end: span.end - offset, end: span.end - offset,
},
append_whitespace: true,
..Suggestion::default()
}, },
// TODO???? append_whitespace: true,
kind: None,
}); });
} }
} }
return sort_suggestions(&String::from_utf8_lossy(prefix), output, options); return output;
} }
vec![] vec![]

View File

@ -1,24 +1,23 @@
mod base; mod base;
mod command_completions; mod command_completions;
mod completer; mod completer;
mod completion_common;
mod completion_options; mod completion_options;
mod custom_completions; mod custom_completions;
mod directory_completions; mod directory_completions;
mod dotnu_completions; mod dotnu_completions;
mod file_completions; mod file_completions;
mod flag_completions; mod flag_completions;
mod operator_completions;
mod variable_completions; mod variable_completions;
pub use base::{Completer, SemanticSuggestion, SuggestionKind}; pub use base::Completer;
pub use command_completions::CommandCompletion; pub use command_completions::CommandCompletion;
pub use completer::NuCompleter; pub use completer::NuCompleter;
pub use completion_options::{CompletionOptions, MatchAlgorithm}; pub use completion_options::{CompletionOptions, MatchAlgorithm, SortBy};
pub use custom_completions::CustomCompletion; pub use custom_completions::CustomCompletion;
pub use directory_completions::DirectoryCompletion; pub use directory_completions::DirectoryCompletion;
pub use dotnu_completions::DotNuCompletion; pub use dotnu_completions::DotNuCompletion;
pub use file_completions::{file_path_completion, matches, FileCompletion}; pub use file_completions::{
file_path_completion, matches, partial_from, prepend_base_dir, FileCompletion,
};
pub use flag_completions::FlagCompletion; pub use flag_completions::FlagCompletion;
pub use operator_completions::OperatorCompletion;
pub use variable_completions::VariableCompletion; pub use variable_completions::VariableCompletion;

View File

@ -1,180 +0,0 @@
use crate::completions::{
Completer, CompletionOptions, MatchAlgorithm, SemanticSuggestion, SuggestionKind,
};
use nu_protocol::{
ast::{Expr, Expression},
engine::{Stack, StateWorkingSet},
Span, Type,
};
use reedline::Suggestion;
#[derive(Clone)]
pub struct OperatorCompletion {
previous_expr: Expression,
}
impl OperatorCompletion {
pub fn new(previous_expr: Expression) -> Self {
OperatorCompletion { previous_expr }
}
}
impl Completer for OperatorCompletion {
fn fetch(
&mut self,
working_set: &StateWorkingSet,
_stack: &Stack,
_prefix: &[u8],
span: Span,
offset: usize,
_pos: usize,
_options: &CompletionOptions,
) -> Vec<SemanticSuggestion> {
//Check if int, float, or string
let partial = std::str::from_utf8(working_set.get_span_contents(span)).unwrap_or("");
let op = match &self.previous_expr.expr {
Expr::BinaryOp(x, _, _) => &x.expr,
_ => {
return vec![];
}
};
let possible_operations = match op {
Expr::Int(_) => vec![
("+", "Add (Plus)"),
("-", "Subtract (Minus)"),
("*", "Multiply"),
("/", "Divide"),
("==", "Equal to"),
("!=", "Not equal to"),
("//", "Floor division"),
("<", "Less than"),
(">", "Greater than"),
("<=", "Less than or equal to"),
(">=", "Greater than or equal to"),
("mod", "Floor division remainder (Modulo)"),
("**", "Power of"),
("bit-or", "Bitwise OR"),
("bit-xor", "Bitwise exclusive OR"),
("bit-and", "Bitwise AND"),
("bit-shl", "Bitwise shift left"),
("bit-shr", "Bitwise shift right"),
("in", "Is a member of (doesn't use regex)"),
("not-in", "Is not a member of (doesn't use regex)"),
(
"++",
"Appends two lists, a list and a value, two strings, or two binary values",
),
],
Expr::String(_) => vec![
("=~", "Contains regex match"),
("!~", "Does not contain regex match"),
(
"++",
"Appends two lists, a list and a value, two strings, or two binary values",
),
("in", "Is a member of (doesn't use regex)"),
("not-in", "Is not a member of (doesn't use regex)"),
("starts-with", "Starts with"),
("ends-with", "Ends with"),
],
Expr::Float(_) => vec![
("+", "Add (Plus)"),
("-", "Subtract (Minus)"),
("*", "Multiply"),
("/", "Divide"),
("==", "Equal to"),
("!=", "Not equal to"),
("//", "Floor division"),
("<", "Less than"),
(">", "Greater than"),
("<=", "Less than or equal to"),
(">=", "Greater than or equal to"),
("mod", "Floor division remainder (Modulo)"),
("**", "Power of"),
("in", "Is a member of (doesn't use regex)"),
("not-in", "Is not a member of (doesn't use regex)"),
(
"++",
"Appends two lists, a list and a value, two strings, or two binary values",
),
],
Expr::Bool(_) => vec![
(
"and",
"Both values are true (short-circuits when first value is false)",
),
(
"or",
"Either value is true (short-circuits when first value is true)",
),
("xor", "One value is true and the other is false"),
("not", "Negates a value or expression"),
("in", "Is a member of (doesn't use regex)"),
("not-in", "Is not a member of (doesn't use regex)"),
(
"++",
"Appends two lists, a list and a value, two strings, or two binary values",
),
],
Expr::FullCellPath(path) => match path.head.expr {
Expr::List(_) => vec![(
"++",
"Appends two lists, a list and a value, two strings, or two binary values",
)],
Expr::Var(id) => get_variable_completions(id, working_set),
_ => vec![],
},
_ => vec![],
};
let match_algorithm = MatchAlgorithm::Prefix;
let input_fuzzy_search =
|(operator, _): &(&str, &str)| match_algorithm.matches_str(operator, partial);
possible_operations
.into_iter()
.filter(input_fuzzy_search)
.map(move |x| SemanticSuggestion {
suggestion: Suggestion {
value: x.0.to_string(),
description: Some(x.1.to_string()),
span: reedline::Span::new(span.start - offset, span.end - offset),
append_whitespace: true,
..Suggestion::default()
},
kind: Some(SuggestionKind::Command(
nu_protocol::engine::CommandType::Builtin,
)),
})
.collect()
}
}
pub fn get_variable_completions<'a>(
id: nu_protocol::Id<nu_protocol::marker::Var>,
working_set: &StateWorkingSet,
) -> Vec<(&'a str, &'a str)> {
let var = working_set.get_variable(id);
if !var.mutable {
return vec![];
}
match var.ty {
Type::List(_) | Type::String | Type::Binary => vec![
(
"++=",
"Appends a list, a value, a string, or a binary value to a variable.",
),
("=", "Assigns a value to a variable."),
],
Type::Int | Type::Float => vec![
("=", "Assigns a value to a variable."),
("+=", "Adds a value to a variable."),
("-=", "Subtracts a value from a variable."),
("*=", "Multiplies a variable by a value"),
("/=", "Divides a variable by a value."),
],
_ => vec![],
}
}

View File

@ -1,24 +1,32 @@
use crate::completions::{ use crate::completions::{Completer, CompletionOptions};
Completer, CompletionOptions, MatchAlgorithm, SemanticSuggestion, SuggestionKind, use nu_engine::eval_variable;
};
use nu_engine::{column::get_columns, eval_variable};
use nu_protocol::{ use nu_protocol::{
engine::{Stack, StateWorkingSet}, engine::{EngineState, Stack, StateWorkingSet},
Span, Value, Span, Value,
}; };
use reedline::Suggestion; use reedline::Suggestion;
use std::str; use std::str;
use std::sync::Arc;
use super::completion_common::sort_suggestions;
#[derive(Clone)] #[derive(Clone)]
pub struct VariableCompletion { pub struct VariableCompletion {
engine_state: Arc<EngineState>, // TODO: Is engine state necessary? It's already a part of working set in fetch()
stack: Stack,
var_context: (Vec<u8>, Vec<Vec<u8>>), // tuple with $var and the sublevels (.b.c.d) var_context: (Vec<u8>, Vec<Vec<u8>>), // tuple with $var and the sublevels (.b.c.d)
} }
impl VariableCompletion { impl VariableCompletion {
pub fn new(var_context: (Vec<u8>, Vec<Vec<u8>>)) -> Self { pub fn new(
Self { var_context } engine_state: Arc<EngineState>,
stack: Stack,
var_context: (Vec<u8>, Vec<Vec<u8>>),
) -> Self {
Self {
engine_state,
stack,
var_context,
}
} }
} }
@ -26,29 +34,29 @@ impl Completer for VariableCompletion {
fn fetch( fn fetch(
&mut self, &mut self,
working_set: &StateWorkingSet, working_set: &StateWorkingSet,
stack: &Stack, prefix: Vec<u8>,
prefix: &[u8],
span: Span, span: Span,
offset: usize, offset: usize,
_pos: usize, _: usize,
options: &CompletionOptions, options: &CompletionOptions,
) -> Vec<SemanticSuggestion> { ) -> Vec<Suggestion> {
let mut output = vec![]; let mut output = vec![];
let builtins = ["$nu", "$in", "$env"]; let builtins = ["$nu", "$in", "$env", "$nothing"];
let var_str = std::str::from_utf8(&self.var_context.0).unwrap_or(""); let var_str = std::str::from_utf8(&self.var_context.0)
.unwrap_or("")
.to_lowercase();
let var_id = working_set.find_variable(&self.var_context.0); let var_id = working_set.find_variable(&self.var_context.0);
let current_span = reedline::Span { let current_span = reedline::Span {
start: span.start - offset, start: span.start - offset,
end: span.end - offset, end: span.end - offset,
}; };
let sublevels_count = self.var_context.1.len(); let sublevels_count = self.var_context.1.len();
let prefix_str = String::from_utf8_lossy(prefix);
// Completions for the given variable // Completions for the given variable
if !var_str.is_empty() { if !var_str.is_empty() {
// Completion for $env.<tab> // Completion for $env.<tab>
if var_str == "$env" { if var_str.as_str() == "$env" {
let env_vars = stack.get_env_vars(working_set.permanent_state); let env_vars = self.stack.get_env_vars(&self.engine_state);
// Return nested values // Return nested values
if sublevels_count > 0 { if sublevels_count > 0 {
@ -62,103 +70,108 @@ impl Completer for VariableCompletion {
self.var_context.1.clone().into_iter().skip(1).collect(); self.var_context.1.clone().into_iter().skip(1).collect();
if let Some(val) = env_vars.get(&target_var_str) { if let Some(val) = env_vars.get(&target_var_str) {
for suggestion in nested_suggestions(val, &nested_levels, current_span) { for suggestion in
if options.match_algorithm.matches_u8_insensitive( nested_suggestions(val.clone(), nested_levels, current_span)
options.case_sensitive, {
suggestion.suggestion.value.as_bytes(), if options
prefix, .match_algorithm
) { .matches_u8(suggestion.value.as_bytes(), &prefix)
{
output.push(suggestion); output.push(suggestion);
} }
} }
return sort_suggestions(&prefix_str, output, options); return output;
} }
} else { } else {
// No nesting provided, return all env vars // No nesting provided, return all env vars
for env_var in env_vars { for env_var in env_vars {
if options.match_algorithm.matches_u8_insensitive( if options
options.case_sensitive, .match_algorithm
env_var.0.as_bytes(), .matches_u8(env_var.0.as_bytes(), &prefix)
prefix, {
) { output.push(Suggestion {
output.push(SemanticSuggestion { value: env_var.0,
suggestion: Suggestion { description: None,
value: env_var.0, extra: None,
span: current_span, span: current_span,
..Suggestion::default() append_whitespace: false,
},
kind: Some(SuggestionKind::Type(env_var.1.get_type())),
}); });
} }
} }
return sort_suggestions(&prefix_str, output, options); return output;
} }
} }
// Completions for $nu.<tab> // Completions for $nu.<tab>
if var_str == "$nu" { if var_str.as_str() == "$nu" {
// Eval nu var // Eval nu var
if let Ok(nuval) = eval_variable( if let Ok(nuval) = eval_variable(
working_set.permanent_state, &self.engine_state,
stack, &self.stack,
nu_protocol::NU_VARIABLE_ID, nu_protocol::NU_VARIABLE_ID,
nu_protocol::Span::new(current_span.start, current_span.end), nu_protocol::Span {
start: current_span.start,
end: current_span.end,
},
) { ) {
for suggestion in nested_suggestions(&nuval, &self.var_context.1, current_span) for suggestion in
nested_suggestions(nuval, self.var_context.1.clone(), current_span)
{ {
if options.match_algorithm.matches_u8_insensitive( if options
options.case_sensitive, .match_algorithm
suggestion.suggestion.value.as_bytes(), .matches_u8(suggestion.value.as_bytes(), &prefix)
prefix, {
) {
output.push(suggestion); output.push(suggestion);
} }
} }
return sort_suggestions(&prefix_str, output, options); return output;
} }
} }
// Completion other variable types // Completion other variable types
if let Some(var_id) = var_id { if let Some(var_id) = var_id {
// Extract the variable value from the stack // Extract the variable value from the stack
let var = stack.get_var(var_id, Span::new(span.start, span.end)); let var = self.stack.get_var(
var_id,
Span {
start: span.start,
end: span.end,
},
);
// If the value exists and it's of type Record // If the value exists and it's of type Record
if let Ok(value) = var { if let Ok(value) = var {
for suggestion in nested_suggestions(&value, &self.var_context.1, current_span) for suggestion in
nested_suggestions(value, self.var_context.1.clone(), current_span)
{ {
if options.match_algorithm.matches_u8_insensitive( if options
options.case_sensitive, .match_algorithm
suggestion.suggestion.value.as_bytes(), .matches_u8(suggestion.value.as_bytes(), &prefix)
prefix, {
) {
output.push(suggestion); output.push(suggestion);
} }
} }
return sort_suggestions(&prefix_str, output, options); return output;
} }
} }
} }
// Variable completion (e.g: $en<tab> to complete $env) // Variable completion (e.g: $en<tab> to complete $env)
for builtin in builtins { for builtin in builtins {
if options.match_algorithm.matches_u8_insensitive( if options
options.case_sensitive, .match_algorithm
builtin.as_bytes(), .matches_u8(builtin.as_bytes(), &prefix)
prefix, {
) { output.push(Suggestion {
output.push(SemanticSuggestion { value: builtin.to_string(),
suggestion: Suggestion { description: None,
value: builtin.to_string(), extra: None,
span: current_span, span: current_span,
..Suggestion::default() append_whitespace: false,
},
// TODO is there a way to get the VarId to get the type???
kind: None,
}); });
} }
} }
@ -168,22 +181,19 @@ impl Completer for VariableCompletion {
let mut removed_overlays = vec![]; let mut removed_overlays = vec![];
// Working set scope vars // Working set scope vars
for scope_frame in working_set.delta.scope.iter().rev() { for scope_frame in working_set.delta.scope.iter().rev() {
for overlay_frame in scope_frame.active_overlays(&mut removed_overlays).rev() { for overlay_frame in scope_frame
.active_overlays(&mut removed_overlays)
.iter()
.rev()
{
for v in &overlay_frame.vars { for v in &overlay_frame.vars {
if options.match_algorithm.matches_u8_insensitive( if options.match_algorithm.matches_u8(v.0, &prefix) {
options.case_sensitive, output.push(Suggestion {
v.0, value: String::from_utf8_lossy(v.0).to_string(),
prefix, description: None,
) { extra: None,
output.push(SemanticSuggestion { span: current_span,
suggestion: Suggestion { append_whitespace: false,
value: String::from_utf8_lossy(v.0).to_string(),
span: current_span,
..Suggestion::default()
},
kind: Some(SuggestionKind::Type(
working_set.get_variable(*v.1).ty.clone(),
)),
}); });
} }
} }
@ -192,33 +202,25 @@ impl Completer for VariableCompletion {
// Permanent state vars // Permanent state vars
// for scope in &self.engine_state.scope { // for scope in &self.engine_state.scope {
for overlay_frame in working_set for overlay_frame in self
.permanent_state .engine_state
.active_overlays(&removed_overlays) .active_overlays(&removed_overlays)
.iter()
.rev() .rev()
{ {
for v in &overlay_frame.vars { for v in &overlay_frame.vars {
if options.match_algorithm.matches_u8_insensitive( if options.match_algorithm.matches_u8(v.0, &prefix) {
options.case_sensitive, output.push(Suggestion {
v.0, value: String::from_utf8_lossy(v.0).to_string(),
prefix, description: None,
) { extra: None,
output.push(SemanticSuggestion { span: current_span,
suggestion: Suggestion { append_whitespace: false,
value: String::from_utf8_lossy(v.0).to_string(),
span: current_span,
..Suggestion::default()
},
kind: Some(SuggestionKind::Type(
working_set.get_variable(*v.1).ty.clone(),
)),
}); });
} }
} }
} }
output = sort_suggestions(&prefix_str, output, options);
output.dedup(); // TODO: Removes only consecutive duplicates, is it intended? output.dedup(); // TODO: Removes only consecutive duplicates, is it intended?
output output
@ -228,87 +230,63 @@ impl Completer for VariableCompletion {
// Find recursively the values for sublevels // Find recursively the values for sublevels
// if no sublevels are set it returns the current value // if no sublevels are set it returns the current value
fn nested_suggestions( fn nested_suggestions(
val: &Value, val: Value,
sublevels: &[Vec<u8>], sublevels: Vec<Vec<u8>>,
current_span: reedline::Span, current_span: reedline::Span,
) -> Vec<SemanticSuggestion> { ) -> Vec<Suggestion> {
let mut output: Vec<SemanticSuggestion> = vec![]; let mut output: Vec<Suggestion> = vec![];
let value = recursive_value(val, sublevels).unwrap_or_else(Value::nothing); let value = recursive_value(val, sublevels);
let kind = SuggestionKind::Type(value.get_type());
match value { match value {
Value::Record { val, .. } => { Value::Record {
cols,
vals: _,
span: _,
} => {
// Add all the columns as completion // Add all the columns as completion
for col in val.columns() { for item in cols {
output.push(SemanticSuggestion { output.push(Suggestion {
suggestion: Suggestion { value: item,
value: col.clone(), description: None,
span: current_span, extra: None,
..Suggestion::default() span: current_span,
}, append_whitespace: false,
kind: Some(kind.clone()),
}); });
} }
output output
} }
Value::List { vals, .. } => {
for column_name in get_columns(vals.as_slice()) {
output.push(SemanticSuggestion {
suggestion: Suggestion {
value: column_name,
span: current_span,
..Suggestion::default()
},
kind: Some(kind.clone()),
});
}
output
}
_ => output, _ => output,
} }
} }
// Extracts the recursive value (e.g: $var.a.b.c) // Extracts the recursive value (e.g: $var.a.b.c)
fn recursive_value(val: &Value, sublevels: &[Vec<u8>]) -> Result<Value, Span> { fn recursive_value(val: Value, sublevels: Vec<Vec<u8>>) -> Value {
// Go to next sublevel // Go to next sublevel
if let Some((sublevel, next_sublevels)) = sublevels.split_first() { if let Some(next_sublevel) = sublevels.clone().into_iter().next() {
let span = val.span();
match val { match val {
Value::Record { val, .. } => { Value::Record {
if let Some((_, value)) = val.iter().find(|(key, _)| key.as_bytes() == sublevel) { cols,
// If matches try to fetch recursively the next vals,
recursive_value(value, next_sublevels) span: _,
} else { } => {
// Current sublevel value not found for item in cols.into_iter().zip(vals.into_iter()) {
Err(span) // Check if index matches with sublevel
} if item.0.as_bytes().to_vec() == next_sublevel {
} // If matches try to fetch recursively the next
Value::List { vals, .. } => { return recursive_value(item.1, sublevels.into_iter().skip(1).collect());
for col in get_columns(vals.as_slice()) {
if col.as_bytes() == *sublevel {
let val = val.get_data_by_key(&col).ok_or(span)?;
return recursive_value(&val, next_sublevels);
} }
} }
// Current sublevel value not found // Current sublevel value not found
Err(span) return Value::Nothing {
span: Span { start: 0, end: 0 },
};
} }
_ => Ok(val.clone()), _ => return val,
} }
} else {
Ok(val.clone())
} }
}
impl MatchAlgorithm { val
pub fn matches_u8_insensitive(&self, sensitive: bool, haystack: &[u8], needle: &[u8]) -> bool {
if sensitive {
self.matches_u8(haystack, needle)
} else {
self.matches_u8(&haystack.to_ascii_lowercase(), &needle.to_ascii_lowercase())
}
}
} }

View File

@ -1,190 +1,73 @@
use crate::util::eval_source; use crate::util::{eval_source, report_error};
#[cfg(feature = "plugin")]
use log::info;
#[cfg(feature = "plugin")]
use nu_parser::ParseError;
#[cfg(feature = "plugin")] #[cfg(feature = "plugin")]
use nu_path::canonicalize_with; use nu_path::canonicalize_with;
use nu_protocol::engine::{EngineState, Stack, StateWorkingSet};
#[cfg(feature = "plugin")] #[cfg(feature = "plugin")]
use nu_protocol::{engine::StateWorkingSet, ParseError, PluginRegistryFile, Spanned}; use nu_protocol::Spanned;
use nu_protocol::{ use nu_protocol::{HistoryFileFormat, PipelineData, Span};
engine::{EngineState, Stack},
report_shell_error, PipelineData,
};
#[cfg(feature = "plugin")]
use nu_utils::perf;
use std::path::PathBuf; use std::path::PathBuf;
#[cfg(feature = "plugin")] #[cfg(feature = "plugin")]
const PLUGIN_FILE: &str = "plugin.msgpackz"; const PLUGIN_FILE: &str = "plugin.nu";
#[cfg(feature = "plugin")]
const OLD_PLUGIN_FILE: &str = "plugin.nu"; const HISTORY_FILE_TXT: &str = "history.txt";
const HISTORY_FILE_SQLITE: &str = "history.sqlite3";
#[cfg(feature = "plugin")] #[cfg(feature = "plugin")]
pub fn read_plugin_file(engine_state: &mut EngineState, plugin_file: Option<Spanned<String>>) { pub fn read_plugin_file(
use nu_protocol::ShellError; engine_state: &mut EngineState,
use std::path::Path; stack: &mut Stack,
plugin_file: Option<Spanned<String>>,
storage_path: &str,
) {
// Reading signatures from signature file
// The plugin.nu file stores the parsed signature collected from each registered plugin
add_plugin_file(engine_state, plugin_file, storage_path);
let span = plugin_file.as_ref().map(|s| s.span); let plugin_path = engine_state.plugin_signatures.clone();
// Check and warn + abort if this is a .nu plugin file
if plugin_file
.as_ref()
.and_then(|p| Path::new(&p.item).extension())
.is_some_and(|ext| ext == "nu")
{
report_shell_error(
engine_state,
&ShellError::GenericError {
error: "Wrong plugin file format".into(),
msg: ".nu plugin files are no longer supported".into(),
span,
help: Some("please recreate this file in the new .msgpackz format".into()),
inner: vec![],
},
);
return;
}
let mut start_time = std::time::Instant::now();
// Reading signatures from plugin registry file
// The plugin.msgpackz file stores the parsed signature collected from each registered plugin
add_plugin_file(engine_state, plugin_file.clone());
perf!(
"add plugin file to engine_state",
start_time,
engine_state.get_config().use_ansi_coloring
);
start_time = std::time::Instant::now();
let plugin_path = engine_state.plugin_path.clone();
if let Some(plugin_path) = plugin_path { if let Some(plugin_path) = plugin_path {
// Open the plugin file let plugin_filename = plugin_path.to_string_lossy();
let mut file = match std::fs::File::open(&plugin_path) {
Ok(file) => file,
Err(err) => {
if err.kind() == std::io::ErrorKind::NotFound {
log::warn!("Plugin file not found: {}", plugin_path.display());
// Try migration of an old plugin file if this wasn't a custom plugin file if let Ok(contents) = std::fs::read(&plugin_path) {
if plugin_file.is_none() && migrate_old_plugin_file(engine_state) { eval_source(
let Ok(file) = std::fs::File::open(&plugin_path) else { engine_state,
log::warn!("Failed to load newly migrated plugin file"); stack,
return; &contents,
}; &plugin_filename,
file PipelineData::new(Span::new(0, 0)),
} else {
return;
}
} else {
report_shell_error(
engine_state,
&ShellError::GenericError {
error: format!(
"Error while opening plugin registry file: {}",
plugin_path.display()
),
msg: "plugin path defined here".into(),
span,
help: None,
inner: vec![err.into()],
},
);
return;
}
}
};
// Abort if the file is empty.
if file.metadata().is_ok_and(|m| m.len() == 0) {
log::warn!(
"Not reading plugin file because it's empty: {}",
plugin_path.display()
); );
return;
} }
// Read the contents of the plugin file
let contents = match PluginRegistryFile::read_from(&mut file, span) {
Ok(contents) => contents,
Err(err) => {
log::warn!("Failed to read plugin registry file: {err:?}");
report_shell_error(
engine_state,
&ShellError::GenericError {
error: format!(
"Error while reading plugin registry file: {}",
plugin_path.display()
),
msg: "plugin path defined here".into(),
span,
help: Some(
"you might try deleting the file and registering all of your \
plugins again"
.into(),
),
inner: vec![],
},
);
return;
}
};
perf!(
&format!("read plugin file {}", plugin_path.display()),
start_time,
engine_state.get_config().use_ansi_coloring
);
start_time = std::time::Instant::now();
let mut working_set = StateWorkingSet::new(engine_state);
nu_plugin_engine::load_plugin_file(&mut working_set, &contents, span);
if let Err(err) = engine_state.merge_delta(working_set.render()) {
report_shell_error(engine_state, &err);
return;
}
perf!(
&format!("load plugin file {}", plugin_path.display()),
start_time,
engine_state.get_config().use_ansi_coloring
);
} }
info!("read_plugin_file {}:{}:{}", file!(), line!(), column!());
} }
#[cfg(feature = "plugin")] #[cfg(feature = "plugin")]
pub fn add_plugin_file(engine_state: &mut EngineState, plugin_file: Option<Spanned<String>>) { pub fn add_plugin_file(
use std::path::Path; engine_state: &mut EngineState,
plugin_file: Option<Spanned<String>>,
storage_path: &str,
) {
if let Some(plugin_file) = plugin_file {
let working_set = StateWorkingSet::new(engine_state);
let cwd = working_set.get_cwd();
use nu_protocol::report_parse_error; match canonicalize_with(&plugin_file.item, cwd) {
Ok(path) => engine_state.plugin_signatures = Some(path),
if let Ok(cwd) = engine_state.cwd_as_string(None) { Err(_) => {
if let Some(plugin_file) = plugin_file { let e = ParseError::FileNotFound(plugin_file.item, plugin_file.span);
let path = Path::new(&plugin_file.item); report_error(&working_set, &e);
let path_dir = path.parent().unwrap_or(path);
// Just try to canonicalize the directory of the plugin file first.
if let Ok(path_dir) = canonicalize_with(path_dir, &cwd) {
// Try to canonicalize the actual filename, but it's ok if that fails. The file doesn't
// have to exist.
let path = path_dir.join(path.file_name().unwrap_or(path.as_os_str()));
let path = canonicalize_with(&path, &cwd).unwrap_or(path);
engine_state.plugin_path = Some(path)
} else {
// It's an error if the directory for the plugin file doesn't exist.
report_parse_error(
&StateWorkingSet::new(engine_state),
&ParseError::FileNotFound(
path_dir.to_string_lossy().into_owned(),
plugin_file.span,
),
);
} }
} else if let Some(plugin_path) = nu_path::nu_config_dir() {
// Path to store plugins signatures
let mut plugin_path =
canonicalize_with(&plugin_path, &cwd).unwrap_or(plugin_path.into());
plugin_path.push(PLUGIN_FILE);
let plugin_path = canonicalize_with(&plugin_path, &cwd).unwrap_or(plugin_path);
engine_state.plugin_path = Some(plugin_path);
} }
} else if let Some(mut plugin_path) = nu_path::config_dir() {
// Path to store plugins signatures
plugin_path.push(storage_path);
plugin_path.push(PLUGIN_FILE);
engine_state.plugin_signatures = Some(plugin_path.clone());
} }
} }
@ -197,155 +80,38 @@ pub fn eval_config_contents(
let config_filename = config_path.to_string_lossy(); let config_filename = config_path.to_string_lossy();
if let Ok(contents) = std::fs::read(&config_path) { if let Ok(contents) = std::fs::read(&config_path) {
// Set the current active file to the config file. eval_source(
let prev_file = engine_state.file.take();
engine_state.file = Some(config_path.clone());
// TODO: ignore this error?
let _ = eval_source(
engine_state, engine_state,
stack, stack,
&contents, &contents,
&config_filename, &config_filename,
PipelineData::empty(), PipelineData::new(Span::new(0, 0)),
false,
); );
// Restore the current active file.
engine_state.file = prev_file;
// Merge the environment in case env vars changed in the config // Merge the environment in case env vars changed in the config
if let Err(e) = engine_state.merge_env(stack) { match nu_engine::env::current_dir(engine_state, stack) {
report_shell_error(engine_state, &e); Ok(cwd) => {
if let Err(e) = engine_state.merge_env(stack, cwd) {
let working_set = StateWorkingSet::new(engine_state);
report_error(&working_set, &e);
}
}
Err(e) => {
let working_set = StateWorkingSet::new(engine_state);
report_error(&working_set, &e);
}
} }
} }
} }
} }
#[cfg(feature = "plugin")] pub(crate) fn get_history_path(storage_path: &str, mode: HistoryFileFormat) -> Option<PathBuf> {
pub fn migrate_old_plugin_file(engine_state: &EngineState) -> bool { nu_path::config_dir().map(|mut history_path| {
use nu_protocol::{ history_path.push(storage_path);
PluginExample, PluginIdentity, PluginRegistryItem, PluginRegistryItemData, PluginSignature, history_path.push(match mode {
ShellError, HistoryFileFormat::PlainText => HISTORY_FILE_TXT,
}; HistoryFileFormat::Sqlite => HISTORY_FILE_SQLITE,
use std::collections::BTreeMap;
let start_time = std::time::Instant::now();
let Ok(cwd) = engine_state.cwd_as_string(None) else {
return false;
};
let Some(config_dir) =
nu_path::nu_config_dir().and_then(|dir| nu_path::canonicalize_with(dir, &cwd).ok())
else {
return false;
};
let Ok(old_plugin_file_path) = nu_path::canonicalize_with(OLD_PLUGIN_FILE, &config_dir) else {
return false;
};
let old_contents = match std::fs::read(&old_plugin_file_path) {
Ok(old_contents) => old_contents,
Err(err) => {
report_shell_error(
engine_state,
&ShellError::GenericError {
error: "Can't read old plugin file to migrate".into(),
msg: "".into(),
span: None,
help: Some(err.to_string()),
inner: vec![],
},
);
return false;
}
};
// Make a copy of the engine state, because we'll read the newly generated file
let mut engine_state = engine_state.clone();
let mut stack = Stack::new();
if eval_source(
&mut engine_state,
&mut stack,
&old_contents,
&old_plugin_file_path.to_string_lossy(),
PipelineData::Empty,
false,
) != 0
{
return false;
}
// Now that the plugin commands are loaded, we just have to generate the file
let mut contents = PluginRegistryFile::new();
let mut groups = BTreeMap::<PluginIdentity, Vec<PluginSignature>>::new();
for decl in engine_state.plugin_decls() {
if let Some(identity) = decl.plugin_identity() {
groups
.entry(identity.clone())
.or_default()
.push(PluginSignature {
sig: decl.signature(),
examples: decl
.examples()
.into_iter()
.map(PluginExample::from)
.collect(),
})
}
}
for (identity, commands) in groups {
contents.upsert_plugin(PluginRegistryItem {
name: identity.name().to_owned(),
filename: identity.filename().to_owned(),
shell: identity.shell().map(|p| p.to_owned()),
data: PluginRegistryItemData::Valid {
metadata: Default::default(),
commands,
},
}); });
} history_path
})
// Write the new file
let new_plugin_file_path = config_dir.join(PLUGIN_FILE);
if let Err(err) = std::fs::File::create(&new_plugin_file_path)
.map_err(|e| e.into())
.and_then(|file| contents.write_to(file, None))
{
report_shell_error(
&engine_state,
&ShellError::GenericError {
error: "Failed to save migrated plugin file".into(),
msg: "".into(),
span: None,
help: Some("ensure `$nu.plugin-path` is writable".into()),
inner: vec![err],
},
);
return false;
}
if engine_state.is_interactive {
eprintln!(
"Your old plugin.nu file has been migrated to the new format: {}",
new_plugin_file_path.display()
);
eprintln!(
"The plugin.nu file has not been removed. If `plugin list` looks okay, \
you may do so manually."
);
}
perf!(
"migrate old plugin file",
start_time,
engine_state.get_config().use_ansi_coloring
);
true
} }

View File

@ -1,101 +0,0 @@
use log::info;
use nu_engine::{convert_env_values, eval_block};
use nu_parser::parse;
use nu_protocol::{
cli_error::report_compile_error,
debugger::WithoutDebug,
engine::{EngineState, Stack, StateWorkingSet},
report_parse_error, report_parse_warning, PipelineData, ShellError, Spanned, Value,
};
use std::sync::Arc;
#[derive(Default)]
pub struct EvaluateCommandsOpts {
pub table_mode: Option<Value>,
pub error_style: Option<Value>,
pub no_newline: bool,
}
/// Run a command (or commands) given to us by the user
pub fn evaluate_commands(
commands: &Spanned<String>,
engine_state: &mut EngineState,
stack: &mut Stack,
input: PipelineData,
opts: EvaluateCommandsOpts,
) -> Result<(), ShellError> {
let EvaluateCommandsOpts {
table_mode,
error_style,
no_newline,
} = opts;
// Handle the configured error style early
if let Some(e_style) = error_style {
match e_style.coerce_str()?.parse() {
Ok(e_style) => {
Arc::make_mut(&mut engine_state.config).error_style = e_style;
}
Err(err) => {
return Err(ShellError::GenericError {
error: "Invalid value for `--error-style`".into(),
msg: err.into(),
span: Some(e_style.span()),
help: None,
inner: vec![],
});
}
}
}
// Translate environment variables from Strings to Values
convert_env_values(engine_state, stack)?;
// Parse the source code
let (block, delta) = {
if let Some(ref t_mode) = table_mode {
Arc::make_mut(&mut engine_state.config).table.mode =
t_mode.coerce_str()?.parse().unwrap_or_default();
}
let mut working_set = StateWorkingSet::new(engine_state);
let output = parse(&mut working_set, None, commands.item.as_bytes(), false);
if let Some(warning) = working_set.parse_warnings.first() {
report_parse_warning(&working_set, warning);
}
if let Some(err) = working_set.parse_errors.first() {
report_parse_error(&working_set, err);
std::process::exit(1);
}
if let Some(err) = working_set.compile_errors.first() {
report_compile_error(&working_set, err);
// Not a fatal error, for now
}
(output, working_set.render())
};
// Update permanent state
engine_state.merge_delta(delta)?;
// Run the block
let pipeline = eval_block::<WithoutDebug>(engine_state, stack, &block, input)?;
if let PipelineData::Value(Value::Error { error, .. }, ..) = pipeline {
return Err(*error);
}
if let Some(t_mode) = table_mode {
Arc::make_mut(&mut engine_state.config).table.mode =
t_mode.coerce_str()?.parse().unwrap_or_default();
}
pipeline.print(engine_state, stack, no_newline, false)?;
info!("evaluate {}:{}:{}", file!(), line!(), column!());
Ok(())
}

View File

@ -1,146 +1,146 @@
use crate::util::eval_source; use crate::util::{eval_source, report_error};
use log::{info, trace}; use log::info;
use nu_engine::{convert_env_values, eval_block}; use log::trace;
use miette::{IntoDiagnostic, Result};
use nu_engine::convert_env_values;
use nu_parser::parse; use nu_parser::parse;
use nu_path::canonicalize_with; use nu_protocol::Type;
use nu_protocol::{ use nu_protocol::{
cli_error::report_compile_error, ast::Call,
debugger::WithoutDebug,
engine::{EngineState, Stack, StateWorkingSet}, engine::{EngineState, Stack, StateWorkingSet},
report_parse_error, report_parse_warning, PipelineData, ShellError, Span, Value, Config, PipelineData, Span, Value,
}; };
use std::sync::Arc; use nu_utils::stdout_write_all_and_flush;
/// Entry point for evaluating a file. /// Main function used when a file path is found as argument for nu
///
/// If the file contains a main command, it is invoked with `args` and the pipeline data from `input`;
/// otherwise, the pipeline data is forwarded to the first command in the file, and `args` are ignored.
pub fn evaluate_file( pub fn evaluate_file(
path: String, path: String,
args: &[String], args: &[String],
engine_state: &mut EngineState, engine_state: &mut EngineState,
stack: &mut Stack, stack: &mut Stack,
input: PipelineData, input: PipelineData,
) -> Result<(), ShellError> { ) -> Result<()> {
// Convert environment variables from Strings to Values and store them in the engine state. // Translate environment variables from Strings to Values
convert_env_values(engine_state, stack)?; if let Some(e) = convert_env_values(engine_state, stack) {
let working_set = StateWorkingSet::new(engine_state);
let cwd = engine_state.cwd_as_string(Some(stack))?; report_error(&working_set, &e);
let file_path =
canonicalize_with(&path, cwd).map_err(|err| ShellError::FileNotFoundCustom {
msg: format!("Could not access file '{path}': {err}"),
span: Span::unknown(),
})?;
let file_path_str = file_path
.to_str()
.ok_or_else(|| ShellError::NonUtf8Custom {
msg: format!(
"Input file name '{}' is not valid UTF8",
file_path.to_string_lossy()
),
span: Span::unknown(),
})?;
let file = std::fs::read(&file_path).map_err(|err| ShellError::FileNotFoundCustom {
msg: format!("Could not read file '{file_path_str}': {err}"),
span: Span::unknown(),
})?;
engine_state.file = Some(file_path.clone());
let parent = file_path
.parent()
.ok_or_else(|| ShellError::FileNotFoundCustom {
msg: format!("The file path '{file_path_str}' does not have a parent"),
span: Span::unknown(),
})?;
stack.add_env_var(
"FILE_PWD".to_string(),
Value::string(parent.to_string_lossy(), Span::unknown()),
);
stack.add_env_var(
"CURRENT_FILE".to_string(),
Value::string(file_path.to_string_lossy(), Span::unknown()),
);
stack.add_env_var(
"PROCESS_PATH".to_string(),
Value::string(path, Span::unknown()),
);
let source_filename = file_path
.file_name()
.expect("internal error: missing filename");
let mut working_set = StateWorkingSet::new(engine_state);
trace!("parsing file: {}", file_path_str);
let block = parse(&mut working_set, Some(file_path_str), &file, false);
if let Some(warning) = working_set.parse_warnings.first() {
report_parse_warning(&working_set, warning);
}
// If any parse errors were found, report the first error and exit.
if let Some(err) = working_set.parse_errors.first() {
report_parse_error(&working_set, err);
std::process::exit(1); std::process::exit(1);
} }
if let Some(err) = working_set.compile_errors.first() { let file = std::fs::read(&path).into_diagnostic()?;
report_compile_error(&working_set, err);
// Not a fatal error, for now
}
// Look for blocks whose name starts with "main" and replace it with the filename. engine_state.start_in_file(Some(&path));
for block in working_set.delta.blocks.iter_mut().map(Arc::make_mut) {
if block.signature.name == "main" {
block.signature.name = source_filename.to_string_lossy().to_string();
} else if block.signature.name.starts_with("main ") {
block.signature.name =
source_filename.to_string_lossy().to_string() + " " + &block.signature.name[5..];
}
}
// Merge the changes into the engine state. let mut working_set = StateWorkingSet::new(engine_state);
engine_state.merge_delta(working_set.delta)?; trace!("parsing file: {}", path);
// Check if the file contains a main command. let _ = parse(&mut working_set, Some(&path), &file, false, &[]);
let exit_code = if engine_state.find_decl(b"main", &[]).is_some() {
// Evaluate the file, but don't run main yet.
let pipeline =
match eval_block::<WithoutDebug>(engine_state, stack, &block, PipelineData::empty()) {
Ok(data) => data,
Err(ShellError::Return { .. }) => {
// Allow early return before main is run.
return Ok(());
}
Err(err) => return Err(err),
};
// Print the pipeline output of the last command of the file. if working_set.find_decl(b"main", &Type::Any).is_some() {
pipeline.print(engine_state, stack, true, false)?;
// Invoke the main command with arguments.
// Arguments with whitespaces are quoted, thus can be safely concatenated by whitespace.
let args = format!("main {}", args.join(" ")); let args = format!("main {}", args.join(" "));
eval_source(
if !eval_source(
engine_state, engine_state,
stack, stack,
args.as_bytes(), &file,
"<commandline>", &path,
input, PipelineData::new(Span::new(0, 0)),
true, ) {
) std::process::exit(1);
} else { }
eval_source(engine_state, stack, &file, file_path_str, input, true) if !eval_source(engine_state, stack, args.as_bytes(), "<commandline>", input) {
}; std::process::exit(1);
}
if exit_code != 0 { } else if !eval_source(engine_state, stack, &file, &path, input) {
std::process::exit(exit_code); std::process::exit(1);
} }
info!("evaluate {}:{}:{}", file!(), line!(), column!()); info!("evaluate {}:{}:{}", file!(), line!(), column!());
Ok(()) Ok(())
} }
pub fn print_table_or_error(
engine_state: &mut EngineState,
stack: &mut Stack,
mut pipeline_data: PipelineData,
config: &mut Config,
) -> Option<i64> {
let exit_code = match &mut pipeline_data {
PipelineData::ExternalStream { exit_code, .. } => exit_code.take(),
_ => None,
};
// Change the engine_state config to use the passed in configuration
engine_state.set_config(config);
if let PipelineData::Value(Value::Error { error }, ..) = &pipeline_data {
let working_set = StateWorkingSet::new(engine_state);
report_error(&working_set, error);
std::process::exit(1);
}
match engine_state.find_decl("table".as_bytes(), &[]) {
Some(decl_id) => {
let command = engine_state.get_decl(decl_id);
if command.get_block_id().is_some() {
print_or_exit(pipeline_data, engine_state, config);
} else {
let table = command.run(
engine_state,
stack,
&Call::new(Span::new(0, 0)),
pipeline_data,
);
match table {
Ok(table) => {
print_or_exit(table, engine_state, config);
}
Err(error) => {
let working_set = StateWorkingSet::new(engine_state);
report_error(&working_set, &error);
std::process::exit(1);
}
}
}
}
None => {
print_or_exit(pipeline_data, engine_state, config);
}
};
// Make sure everything has finished
if let Some(exit_code) = exit_code {
let mut exit_code: Vec<_> = exit_code.into_iter().collect();
exit_code
.pop()
.and_then(|last_exit_code| match last_exit_code {
Value::Int { val: code, .. } => Some(code),
_ => None,
})
} else {
None
}
}
fn print_or_exit(pipeline_data: PipelineData, engine_state: &mut EngineState, config: &Config) {
for item in pipeline_data {
if let Value::Error { error } = item {
let working_set = StateWorkingSet::new(engine_state);
report_error(&working_set, &error);
std::process::exit(1);
}
let mut out = item.into_string("\n", config);
out.push('\n');
let _ = stdout_write_all_and_flush(out).map_err(|err| eprintln!("{}", err));
}
}

View File

@ -1,8 +1,6 @@
#![doc = include_str!("../README.md")]
mod commands; mod commands;
mod completions; mod completions;
mod config_files; mod config_files;
mod eval_cmds;
mod eval_file; mod eval_file;
mod menus; mod menus;
mod nu_highlight; mod nu_highlight;
@ -15,23 +13,21 @@ mod syntax_highlight;
mod util; mod util;
mod validation; mod validation;
pub use commands::add_cli_context; pub use commands::evaluate_commands;
pub use completions::{FileCompletion, NuCompleter, SemanticSuggestion, SuggestionKind}; pub use completions::{FileCompletion, NuCompleter};
pub use config_files::eval_config_contents; pub use config_files::eval_config_contents;
pub use eval_cmds::{evaluate_commands, EvaluateCommandsOpts};
pub use eval_file::evaluate_file; pub use eval_file::evaluate_file;
pub use menus::NuHelpCompleter; pub use menus::{DescriptionMenu, NuHelpCompleter};
pub use nu_highlight::NuHighlight; pub use nu_highlight::NuHighlight;
pub use print::Print; pub use print::Print;
pub use prompt::NushellPrompt; pub use prompt::NushellPrompt;
pub use repl::evaluate_repl; pub use repl::evaluate_repl;
pub use repl::{eval_env_change_hook, eval_hook};
pub use syntax_highlight::NuHighlighter; pub use syntax_highlight::NuHighlighter;
pub use util::{eval_source, gather_parent_env_vars}; pub use util::{eval_source, gather_parent_env_vars, get_init_cwd, report_error, report_error_new};
pub use validation::NuValidator; pub use validation::NuValidator;
#[cfg(feature = "plugin")] #[cfg(feature = "plugin")]
pub use config_files::add_plugin_file; pub use config_files::add_plugin_file;
#[cfg(feature = "plugin")] #[cfg(feature = "plugin")]
pub use config_files::migrate_old_plugin_file;
#[cfg(feature = "plugin")]
pub use config_files::read_plugin_file; pub use config_files::read_plugin_file;

View File

@ -0,0 +1,727 @@
use {
nu_ansi_term::{ansi::RESET, Style},
reedline::{
menu_functions::string_difference, Completer, Editor, Menu, MenuEvent, MenuTextStyle,
Painter, Suggestion, UndoBehavior,
},
};
/// Default values used as reference for the menu. These values are set during
/// the initial declaration of the menu and are always kept as reference for the
/// changeable [`WorkingDetails`]
struct DefaultMenuDetails {
/// Number of columns that the menu will have
pub columns: u16,
/// Column width
pub col_width: Option<usize>,
/// Column padding
pub col_padding: usize,
/// Number of rows for commands
pub selection_rows: u16,
/// Number of rows allowed to display the description
pub description_rows: usize,
}
impl Default for DefaultMenuDetails {
fn default() -> Self {
Self {
columns: 4,
col_width: None,
col_padding: 2,
selection_rows: 4,
description_rows: 10,
}
}
}
/// Represents the actual column conditions of the menu. These conditions change
/// since they need to accommodate possible different line sizes for the column values
#[derive(Default)]
struct WorkingDetails {
/// Number of columns that the menu will have
pub columns: u16,
/// Column width
pub col_width: usize,
/// Number of rows for description
pub description_rows: usize,
}
/// Completion menu definition
pub struct DescriptionMenu {
/// Menu name
name: String,
/// Menu status
active: bool,
/// Menu coloring
color: MenuTextStyle,
/// Default column details that are set when creating the menu
/// These values are the reference for the working details
default_details: DefaultMenuDetails,
/// Number of minimum rows that are displayed when
/// the required lines is larger than the available lines
min_rows: u16,
/// Working column details keep changing based on the collected values
working_details: WorkingDetails,
/// Menu cached values
values: Vec<Suggestion>,
/// column position of the cursor. Starts from 0
col_pos: u16,
/// row position in the menu. Starts from 0
row_pos: u16,
/// Menu marker when active
marker: String,
/// Event sent to the menu
event: Option<MenuEvent>,
/// String collected after the menu is activated
input: Option<String>,
/// Examples to select
examples: Vec<String>,
/// Example index
example_index: Option<usize>,
/// Examples may not be shown if there is not enough space in the screen
show_examples: bool,
/// Skipped description rows
skipped_rows: usize,
/// Calls the completer using only the line buffer difference difference
/// after the menu was activated
only_buffer_difference: bool,
}
impl Default for DescriptionMenu {
fn default() -> Self {
Self {
name: "description_menu".to_string(),
active: false,
color: MenuTextStyle::default(),
default_details: DefaultMenuDetails::default(),
min_rows: 3,
working_details: WorkingDetails::default(),
values: Vec::new(),
col_pos: 0,
row_pos: 0,
marker: "? ".to_string(),
event: None,
input: None,
examples: Vec::new(),
example_index: None,
show_examples: true,
skipped_rows: 0,
only_buffer_difference: true,
}
}
}
// Menu configuration
impl DescriptionMenu {
/// Menu builder with new name
pub fn with_name(mut self, name: &str) -> Self {
self.name = name.into();
self
}
/// Menu builder with new value for text style
pub fn with_text_style(mut self, text_style: Style) -> Self {
self.color.text_style = text_style;
self
}
/// Menu builder with new value for text style
pub fn with_selected_text_style(mut self, selected_text_style: Style) -> Self {
self.color.selected_text_style = selected_text_style;
self
}
/// Menu builder with new value for text style
pub fn with_description_text_style(mut self, description_text_style: Style) -> Self {
self.color.description_style = description_text_style;
self
}
/// Menu builder with new columns value
pub fn with_columns(mut self, columns: u16) -> Self {
self.default_details.columns = columns;
self
}
/// Menu builder with new column width value
pub fn with_column_width(mut self, col_width: Option<usize>) -> Self {
self.default_details.col_width = col_width;
self
}
/// Menu builder with new column width value
pub fn with_column_padding(mut self, col_padding: usize) -> Self {
self.default_details.col_padding = col_padding;
self
}
/// Menu builder with new selection rows value
pub fn with_selection_rows(mut self, selection_rows: u16) -> Self {
self.default_details.selection_rows = selection_rows;
self
}
/// Menu builder with new description rows value
pub fn with_description_rows(mut self, description_rows: usize) -> Self {
self.default_details.description_rows = description_rows;
self
}
/// Menu builder with marker
pub fn with_marker(mut self, marker: String) -> Self {
self.marker = marker;
self
}
/// Menu builder with new only buffer difference
pub fn with_only_buffer_difference(mut self, only_buffer_difference: bool) -> Self {
self.only_buffer_difference = only_buffer_difference;
self
}
}
// Menu functionality
impl DescriptionMenu {
/// Move menu cursor to the next element
fn move_next(&mut self) {
let mut new_col = self.col_pos + 1;
let mut new_row = self.row_pos;
if new_col >= self.get_cols() {
new_row += 1;
new_col = 0;
}
if new_row >= self.get_rows() {
new_row = 0;
new_col = 0;
}
let position = new_row * self.get_cols() + new_col;
if position >= self.get_values().len() as u16 {
self.reset_position();
} else {
self.col_pos = new_col;
self.row_pos = new_row;
}
}
/// Move menu cursor to the previous element
fn move_previous(&mut self) {
let new_col = self.col_pos.checked_sub(1);
let (new_col, new_row) = match new_col {
Some(col) => (col, self.row_pos),
None => match self.row_pos.checked_sub(1) {
Some(row) => (self.get_cols().saturating_sub(1), row),
None => (
self.get_cols().saturating_sub(1),
self.get_rows().saturating_sub(1),
),
},
};
let position = new_row * self.get_cols() + new_col;
if position >= self.get_values().len() as u16 {
self.col_pos = (self.get_values().len() as u16 % self.get_cols()).saturating_sub(1);
self.row_pos = self.get_rows().saturating_sub(1);
} else {
self.col_pos = new_col;
self.row_pos = new_row;
}
}
/// Menu index based on column and row position
fn index(&self) -> usize {
let index = self.row_pos * self.get_cols() + self.col_pos;
index as usize
}
/// Get selected value from the menu
fn get_value(&self) -> Option<Suggestion> {
self.get_values().get(self.index()).cloned()
}
/// Calculates how many rows the Menu will use
fn get_rows(&self) -> u16 {
let values = self.get_values().len() as u16;
if values == 0 {
// When the values are empty the no_records_msg is shown, taking 1 line
return 1;
}
let rows = values / self.get_cols();
if values % self.get_cols() != 0 {
rows + 1
} else {
rows
}
}
/// Returns working details col width
fn get_width(&self) -> usize {
self.working_details.col_width
}
/// Reset menu position
fn reset_position(&mut self) {
self.col_pos = 0;
self.row_pos = 0;
self.skipped_rows = 0;
}
fn no_records_msg(&self, use_ansi_coloring: bool) -> String {
let msg = "TYPE TO START SEARCH";
if use_ansi_coloring {
format!(
"{}{}{}",
self.color.selected_text_style.prefix(),
msg,
RESET
)
} else {
msg.to_string()
}
}
/// Returns working details columns
fn get_cols(&self) -> u16 {
self.working_details.columns.max(1)
}
/// End of line for menu
fn end_of_line(&self, column: u16, index: usize) -> &str {
let is_last = index == self.values.len().saturating_sub(1);
if column == self.get_cols().saturating_sub(1) || is_last {
"\r\n"
} else {
""
}
}
/// Update list of examples from the actual value
fn update_examples(&mut self) {
self.examples = self
.get_value()
.and_then(|suggestion| suggestion.extra)
.unwrap_or_default();
self.example_index = None;
}
/// Creates default string that represents one suggestion from the menu
fn create_entry_string(
&self,
suggestion: &Suggestion,
index: usize,
column: u16,
empty_space: usize,
use_ansi_coloring: bool,
) -> String {
if use_ansi_coloring {
if index == self.index() {
format!(
"{}{}{}{:>empty$}{}",
self.color.selected_text_style.prefix(),
&suggestion.value,
RESET,
"",
self.end_of_line(column, index),
empty = empty_space,
)
} else {
format!(
"{}{}{}{:>empty$}{}",
self.color.text_style.prefix(),
&suggestion.value,
RESET,
"",
self.end_of_line(column, index),
empty = empty_space,
)
}
} else {
// If no ansi coloring is found, then the selection word is
// the line in uppercase
let (marker, empty_space) = if index == self.index() {
(">", empty_space.saturating_sub(1))
} else {
("", empty_space)
};
let line = format!(
"{}{}{:>empty$}{}",
marker,
&suggestion.value,
"",
self.end_of_line(column, index),
empty = empty_space,
);
if index == self.index() {
line.to_uppercase()
} else {
line
}
}
}
/// Description string with color
fn create_description_string(&self, use_ansi_coloring: bool) -> String {
let description = self
.get_value()
.and_then(|suggestion| suggestion.description)
.unwrap_or_default()
.lines()
.skip(self.skipped_rows)
.take(self.working_details.description_rows)
.collect::<Vec<&str>>()
.join("\r\n");
if use_ansi_coloring && !description.is_empty() {
format!(
"{}{}{}",
self.color.description_style.prefix(),
description,
RESET,
)
} else {
description
}
}
/// Selectable list of examples from the actual value
fn create_example_string(&self, use_ansi_coloring: bool) -> String {
if !self.show_examples {
return "".into();
}
let examples: String = self
.examples
.iter()
.enumerate()
.map(|(index, example)| {
if let Some(example_index) = self.example_index {
if index == example_index {
format!(
" {}{}{}\r\n",
self.color.selected_text_style.prefix(),
example,
RESET
)
} else {
format!(" {}\r\n", example)
}
} else {
format!(" {}\r\n", example)
}
})
.collect();
if examples.is_empty() {
"".into()
} else if use_ansi_coloring {
format!(
"{}\r\n\r\nExamples:\r\n{}{}",
self.color.description_style.prefix(),
RESET,
examples,
)
} else {
format!("\r\n\r\nExamples:\r\n{}", examples,)
}
}
}
impl Menu for DescriptionMenu {
/// Menu name
fn name(&self) -> &str {
self.name.as_str()
}
/// Menu indicator
fn indicator(&self) -> &str {
self.marker.as_str()
}
/// Deactivates context menu
fn is_active(&self) -> bool {
self.active
}
/// The menu stays active even with one record
fn can_quick_complete(&self) -> bool {
false
}
/// The menu does not need to partially complete
fn can_partially_complete(
&mut self,
_values_updated: bool,
_editor: &mut Editor,
_completer: &mut dyn Completer,
) -> bool {
false
}
/// Selects what type of event happened with the menu
fn menu_event(&mut self, event: MenuEvent) {
match &event {
MenuEvent::Activate(_) => self.active = true,
MenuEvent::Deactivate => {
self.active = false;
self.input = None;
self.values = Vec::new();
}
_ => {}
};
self.event = Some(event);
}
/// Updates menu values
fn update_values(&mut self, editor: &mut Editor, completer: &mut dyn Completer) {
if self.only_buffer_difference {
if let Some(old_string) = &self.input {
let (start, input) = string_difference(editor.get_buffer(), old_string);
if !input.is_empty() {
self.reset_position();
self.values = completer.complete(input, start);
}
}
} else {
let trimmed_buffer = editor.get_buffer().replace('\n', " ");
self.values = completer.complete(
trimmed_buffer.as_str(),
editor.line_buffer().insertion_point(),
);
self.reset_position();
}
}
/// The working details for the menu changes based on the size of the lines
/// collected from the completer
fn update_working_details(
&mut self,
editor: &mut Editor,
completer: &mut dyn Completer,
painter: &Painter,
) {
if let Some(event) = self.event.take() {
// Updating all working parameters from the menu before executing any of the
// possible event
let max_width = self.get_values().iter().fold(0, |acc, suggestion| {
let str_len = suggestion.value.len() + self.default_details.col_padding;
if str_len > acc {
str_len
} else {
acc
}
});
// If no default width is found, then the total screen width is used to estimate
// the column width based on the default number of columns
let default_width = if let Some(col_width) = self.default_details.col_width {
col_width
} else {
let col_width = painter.screen_width() / self.default_details.columns;
col_width as usize
};
// Adjusting the working width of the column based the max line width found
// in the menu values
if max_width > default_width {
self.working_details.col_width = max_width;
} else {
self.working_details.col_width = default_width;
};
// The working columns is adjusted based on possible number of columns
// that could be fitted in the screen with the calculated column width
let possible_cols = painter.screen_width() / self.working_details.col_width as u16;
if possible_cols > self.default_details.columns {
self.working_details.columns = self.default_details.columns.max(1);
} else {
self.working_details.columns = possible_cols;
}
// Updating the working rows to display the description
if self.menu_required_lines(painter.screen_width()) <= painter.remaining_lines() {
self.working_details.description_rows = self.default_details.description_rows;
self.show_examples = true;
} else {
self.working_details.description_rows = painter
.remaining_lines()
.saturating_sub(self.default_details.selection_rows + 1)
as usize;
self.show_examples = false;
}
match event {
MenuEvent::Activate(_) => {
self.reset_position();
self.input = Some(editor.get_buffer().to_string());
self.update_values(editor, completer);
}
MenuEvent::Deactivate => self.active = false,
MenuEvent::Edit(_) => {
self.reset_position();
self.update_values(editor, completer);
self.update_examples()
}
MenuEvent::NextElement => {
self.skipped_rows = 0;
self.move_next();
self.update_examples();
}
MenuEvent::PreviousElement => {
self.skipped_rows = 0;
self.move_previous();
self.update_examples();
}
MenuEvent::MoveUp => {
if let Some(example_index) = self.example_index {
if let Some(index) = example_index.checked_sub(1) {
self.example_index = Some(index);
} else {
self.example_index = Some(self.examples.len().saturating_sub(1));
}
} else if !self.examples.is_empty() {
self.example_index = Some(0);
}
}
MenuEvent::MoveDown => {
if let Some(example_index) = self.example_index {
let index = example_index + 1;
if index < self.examples.len() {
self.example_index = Some(index);
} else {
self.example_index = Some(0);
}
} else if !self.examples.is_empty() {
self.example_index = Some(0);
}
}
MenuEvent::MoveLeft => self.skipped_rows = self.skipped_rows.saturating_sub(1),
MenuEvent::MoveRight => {
let skipped = self.skipped_rows + 1;
let description_rows = self
.get_value()
.and_then(|suggestion| suggestion.description)
.unwrap_or_default()
.lines()
.count();
let allowed_skips =
description_rows.saturating_sub(self.working_details.description_rows);
if skipped < allowed_skips {
self.skipped_rows = skipped;
} else {
self.skipped_rows = allowed_skips;
}
}
MenuEvent::PreviousPage | MenuEvent::NextPage => {}
}
}
}
/// The buffer gets replaced in the Span location
fn replace_in_buffer(&self, editor: &mut Editor) {
if let Some(Suggestion { value, span, .. }) = self.get_value() {
let start = span.start.min(editor.line_buffer().len());
let end = span.end.min(editor.line_buffer().len());
let replacement = if let Some(example_index) = self.example_index {
self.examples
.get(example_index)
.expect("the example index is always checked")
} else {
&value
};
editor.edit_buffer(
|lb| {
lb.replace_range(start..end, replacement);
let mut offset = lb.insertion_point();
offset += lb.len().saturating_sub(end.saturating_sub(start));
lb.set_insertion_point(offset);
},
UndoBehavior::CreateUndoPoint,
);
}
}
/// Minimum rows that should be displayed by the menu
fn min_rows(&self) -> u16 {
self.get_rows().min(self.min_rows)
}
/// Gets values from filler that will be displayed in the menu
fn get_values(&self) -> &[Suggestion] {
&self.values
}
fn menu_required_lines(&self, _terminal_columns: u16) -> u16 {
let example_lines = self
.examples
.iter()
.fold(0, |acc, example| example.lines().count() + acc);
self.default_details.selection_rows
+ self.default_details.description_rows as u16
+ example_lines as u16
+ 3
}
fn menu_string(&self, _available_lines: u16, use_ansi_coloring: bool) -> String {
if self.get_values().is_empty() {
self.no_records_msg(use_ansi_coloring)
} else {
// The skip values represent the number of lines that should be skipped
// while printing the menu
let available_lines = self.default_details.selection_rows;
let skip_values = if self.row_pos >= available_lines {
let skip_lines = self.row_pos.saturating_sub(available_lines) + 1;
(skip_lines * self.get_cols()) as usize
} else {
0
};
// It seems that crossterm prefers to have a complete string ready to be printed
// rather than looping through the values and printing multiple things
// This reduces the flickering when printing the menu
let available_values = (available_lines * self.get_cols()) as usize;
let selection_values: String = self
.get_values()
.iter()
.skip(skip_values)
.take(available_values)
.enumerate()
.map(|(index, suggestion)| {
// Correcting the enumerate index based on the number of skipped values
let index = index + skip_values;
let column = index as u16 % self.get_cols();
let empty_space = self.get_width().saturating_sub(suggestion.value.len());
self.create_entry_string(
suggestion,
index,
column,
empty_space,
use_ansi_coloring,
)
})
.collect();
format!(
"{}{}{}",
selection_values,
self.create_description_string(use_ansi_coloring),
self.create_example_string(use_ansi_coloring)
)
}
}
}

View File

@ -1,74 +1,63 @@
use nu_engine::documentation::{get_flags_section, HelpStyle}; use nu_engine::documentation::get_flags_section;
use nu_protocol::{engine::EngineState, levenshtein_distance, Config}; use nu_protocol::{engine::EngineState, levenshtein_distance};
use nu_utils::IgnoreCaseExt;
use reedline::{Completer, Suggestion}; use reedline::{Completer, Suggestion};
use std::{fmt::Write, sync::Arc}; use std::fmt::Write;
use std::sync::Arc;
pub struct NuHelpCompleter { pub struct NuHelpCompleter(Arc<EngineState>);
engine_state: Arc<EngineState>,
config: Arc<Config>,
}
impl NuHelpCompleter { impl NuHelpCompleter {
pub fn new(engine_state: Arc<EngineState>, config: Arc<Config>) -> Self { pub fn new(engine_state: Arc<EngineState>) -> Self {
Self { Self(engine_state)
engine_state,
config,
}
} }
fn completion_helper(&self, line: &str, pos: usize) -> Vec<Suggestion> { fn completion_helper(&self, line: &str, pos: usize) -> Vec<Suggestion> {
let folded_line = line.to_folded_case(); let full_commands = self.0.get_signatures_with_examples(false);
let mut help_style = HelpStyle::default(); //Vec<(Signature, Vec<Example>, bool, bool)> {
help_style.update_from_config(&self.engine_state, &self.config); let mut commands = full_commands
.iter()
let mut commands = self .filter(|(sig, _, _, _, _)| {
.engine_state sig.name.to_lowercase().contains(&line.to_lowercase())
.get_decls_sorted(false) || sig.usage.to_lowercase().contains(&line.to_lowercase())
.into_iter() || sig
.filter_map(|(_, decl_id)| { .search_terms
let decl = self.engine_state.get_decl(decl_id); .iter()
(decl.name().to_folded_case().contains(&folded_line) .any(|term| term.to_lowercase().contains(&line.to_lowercase()))
|| decl.description().to_folded_case().contains(&folded_line) || sig
|| decl .extra_usage
.search_terms() .to_lowercase()
.into_iter() .contains(&line.to_lowercase())
.any(|term| term.to_folded_case().contains(&folded_line))
|| decl
.extra_description()
.to_folded_case()
.contains(&folded_line))
.then_some(decl)
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
commands.sort_by_cached_key(|decl| levenshtein_distance(line, decl.name())); commands.sort_by(|(a, _, _, _, _), (b, _, _, _, _)| {
let a_distance = levenshtein_distance(line, &a.name);
let b_distance = levenshtein_distance(line, &b.name);
a_distance.cmp(&b_distance)
});
commands commands
.into_iter() .into_iter()
.map(|decl| { .map(|(sig, examples, _, _, _)| {
let mut long_desc = String::new(); let mut long_desc = String::new();
let description = decl.description(); let usage = &sig.usage;
if !description.is_empty() { if !usage.is_empty() {
long_desc.push_str(description); long_desc.push_str(usage);
long_desc.push_str("\r\n\r\n"); long_desc.push_str("\r\n\r\n");
} }
let extra_desc = decl.extra_description(); let extra_usage = &sig.extra_usage;
if !extra_desc.is_empty() { if !extra_usage.is_empty() {
long_desc.push_str(extra_desc); long_desc.push_str(extra_usage);
long_desc.push_str("\r\n\r\n"); long_desc.push_str("\r\n\r\n");
} }
let sig = decl.signature();
let _ = write!(long_desc, "Usage:\r\n > {}\r\n", sig.call_signature()); let _ = write!(long_desc, "Usage:\r\n > {}\r\n", sig.call_signature());
if !sig.named.is_empty() { if !sig.named.is_empty() {
long_desc.push_str(&get_flags_section(&sig, &help_style, |v| { long_desc.push_str(&get_flags_section(sig))
v.to_parsable_string(", ", &self.config)
}))
} }
if !sig.required_positional.is_empty() if !sig.required_positional.is_empty()
@ -80,18 +69,10 @@ impl NuHelpCompleter {
let _ = write!(long_desc, " {}: {}\r\n", positional.name, positional.desc); let _ = write!(long_desc, " {}: {}\r\n", positional.name, positional.desc);
} }
for positional in &sig.optional_positional { for positional in &sig.optional_positional {
let opt_suffix = if let Some(value) = &positional.default_value {
format!(
" (optional, default: {})",
&value.to_parsable_string(", ", &self.config),
)
} else {
(" (optional)").to_string()
};
let _ = write!( let _ = write!(
long_desc, long_desc,
" (optional) {}: {}{}\r\n", " (optional) {}: {}\r\n",
positional.name, positional.desc, opt_suffix positional.name, positional.desc
); );
} }
@ -104,21 +85,20 @@ impl NuHelpCompleter {
} }
} }
let extra: Vec<String> = decl let extra: Vec<String> = examples
.examples()
.iter() .iter()
.map(|example| example.example.replace('\n', "\r\n")) .map(|example| example.example.replace('\n', "\r\n"))
.collect(); .collect();
Suggestion { Suggestion {
value: decl.name().into(), value: sig.name.clone(),
description: Some(long_desc), description: Some(long_desc),
extra: Some(extra), extra: Some(extra),
span: reedline::Span { span: reedline::Span {
start: pos - line.len(), start: pos,
end: pos, end: pos + line.len(),
}, },
..Suggestion::default() append_whitespace: false,
} }
}) })
.collect() .collect()
@ -130,43 +110,3 @@ impl Completer for NuHelpCompleter {
self.completion_helper(line, pos) self.completion_helper(line, pos)
} }
} }
#[cfg(test)]
mod test {
use super::*;
use rstest::rstest;
#[rstest]
#[case("who", 5, 8, &["whoami"])]
#[case("hash", 1, 5, &["hash", "hash md5", "hash sha256"])]
#[case("into f", 0, 6, &["into float", "into filesize"])]
#[case("into nonexistent", 0, 16, &[])]
fn test_help_completer(
#[case] line: &str,
#[case] start: usize,
#[case] end: usize,
#[case] expected: &[&str],
) {
let engine_state =
nu_command::add_shell_command_context(nu_cmd_lang::create_default_context());
let config = engine_state.get_config().clone();
let mut completer = NuHelpCompleter::new(engine_state.into(), config);
let suggestions = completer.complete(line, end);
assert_eq!(
expected.len(),
suggestions.len(),
"expected {:?}, got {:?}",
expected,
suggestions
.iter()
.map(|s| s.value.clone())
.collect::<Vec<_>>()
);
for (exp, actual) in expected.iter().zip(suggestions) {
assert_eq!(exp, &actual.value);
assert_eq!(reedline::Span::new(start, end), actual.span);
}
}
}

View File

@ -1,8 +1,7 @@
use nu_engine::eval_block; use nu_engine::eval_block;
use nu_protocol::{ use nu_protocol::{
debugger::WithoutDebug,
engine::{EngineState, Stack}, engine::{EngineState, Stack},
BlockId, IntoPipelineData, Span, Value, IntoPipelineData, Span, Value,
}; };
use reedline::{menu_functions::parse_selection_char, Completer, Suggestion}; use reedline::{menu_functions::parse_selection_char, Completer, Suggestion};
use std::sync::Arc; use std::sync::Arc;
@ -10,7 +9,7 @@ use std::sync::Arc;
const SELECTION_CHAR: char = '!'; const SELECTION_CHAR: char = '!';
pub struct NuMenuCompleter { pub struct NuMenuCompleter {
block_id: BlockId, block_id: usize,
span: Span, span: Span,
stack: Stack, stack: Stack,
engine_state: Arc<EngineState>, engine_state: Arc<EngineState>,
@ -19,7 +18,7 @@ pub struct NuMenuCompleter {
impl NuMenuCompleter { impl NuMenuCompleter {
pub fn new( pub fn new(
block_id: BlockId, block_id: usize,
span: Span, span: Span,
stack: Stack, stack: Stack,
engine_state: Arc<EngineState>, engine_state: Arc<EngineState>,
@ -28,7 +27,7 @@ impl NuMenuCompleter {
Self { Self {
block_id, block_id,
span, span,
stack: stack.reset_out_dest().collect_value(), stack,
engine_state, engine_state,
only_buffer_difference, only_buffer_difference,
} }
@ -43,23 +42,36 @@ impl Completer for NuMenuCompleter {
if let Some(buffer) = block.signature.get_positional(0) { if let Some(buffer) = block.signature.get_positional(0) {
if let Some(buffer_id) = &buffer.var_id { if let Some(buffer_id) = &buffer.var_id {
let line_buffer = Value::string(parsed.remainder, self.span); let line_buffer = Value::String {
val: parsed.remainder.to_string(),
span: self.span,
};
self.stack.add_var(*buffer_id, line_buffer); self.stack.add_var(*buffer_id, line_buffer);
} }
} }
if let Some(position) = block.signature.get_positional(1) { if let Some(position) = block.signature.get_positional(1) {
if let Some(position_id) = &position.var_id { if let Some(position_id) = &position.var_id {
let line_buffer = Value::int(pos as i64, self.span); let line_buffer = Value::Int {
val: pos as i64,
span: self.span,
};
self.stack.add_var(*position_id, line_buffer); self.stack.add_var(*position_id, line_buffer);
} }
} }
let input = Value::nothing(self.span).into_pipeline_data(); let input = Value::nothing(self.span).into_pipeline_data();
let res = eval_block(
&self.engine_state,
&mut self.stack,
block,
input,
false,
false,
);
let res = eval_block::<WithoutDebug>(&self.engine_state, &mut self.stack, block, input); if let Ok(values) = res {
let values = values.into_value(self.span);
if let Ok(values) = res.and_then(|data| data.into_value(self.span)) {
convert_to_suggestions(values, line, pos, self.only_buffer_difference) convert_to_suggestions(values, line, pos, self.only_buffer_difference)
} else { } else {
Vec::new() Vec::new()
@ -74,20 +86,27 @@ fn convert_to_suggestions(
only_buffer_difference: bool, only_buffer_difference: bool,
) -> Vec<Suggestion> { ) -> Vec<Suggestion> {
match value { match value {
Value::Record { val, .. } => { Value::Record { .. } => {
let text = val let text = match value
.get("value") .get_data_by_key("value")
.and_then(|val| val.coerce_string().ok()) .and_then(|val| val.as_string().ok())
.unwrap_or_else(|| "No value key".to_string()); {
Some(val) => val,
None => "No value key".to_string(),
};
let description = val let description = value
.get("description") .get_data_by_key("description")
.and_then(|val| val.coerce_string().ok()); .and_then(|val| val.as_string().ok());
let span = match val.get("span") { let span = match value.get_data_by_key("span") {
Some(Value::Record { val: span, .. }) => { Some(span @ Value::Record { .. }) => {
let start = span.get("start").and_then(|val| val.as_int().ok()); let start = span
let end = span.get("end").and_then(|val| val.as_int().ok()); .get_data_by_key("start")
.and_then(|val| val.as_integer().ok());
let end = span
.get_data_by_key("end")
.and_then(|val| val.as_integer().ok());
match (start, end) { match (start, end) {
(Some(start), Some(end)) => { (Some(start), Some(end)) => {
let start = start.min(end); let start = start.min(end);
@ -97,13 +116,9 @@ fn convert_to_suggestions(
} }
} }
_ => reedline::Span { _ => reedline::Span {
start: if only_buffer_difference { start: if only_buffer_difference { pos } else { 0 },
pos - line.len()
} else {
0
},
end: if only_buffer_difference { end: if only_buffer_difference {
pos pos + line.len()
} else { } else {
line.len() line.len()
}, },
@ -111,25 +126,21 @@ fn convert_to_suggestions(
} }
} }
_ => reedline::Span { _ => reedline::Span {
start: if only_buffer_difference { start: if only_buffer_difference { pos } else { 0 },
pos - line.len()
} else {
0
},
end: if only_buffer_difference { end: if only_buffer_difference {
pos pos + line.len()
} else { } else {
line.len() line.len()
}, },
}, },
}; };
let extra = match val.get("extra") { let extra = match value.get_data_by_key("extra") {
Some(Value::List { vals, .. }) => { Some(Value::List { vals, .. }) => {
let extra: Vec<String> = vals let extra: Vec<String> = vals
.iter() .into_iter()
.filter_map(|extra| match extra { .filter_map(|extra| match extra {
Value::String { val, .. } => Some(val.clone()), Value::String { val, .. } => Some(val),
_ => None, _ => None,
}) })
.collect(); .collect();
@ -144,7 +155,7 @@ fn convert_to_suggestions(
description, description,
extra, extra,
span, span,
..Suggestion::default() append_whitespace: false,
}] }]
} }
Value::List { vals, .. } => vals Value::List { vals, .. } => vals
@ -152,20 +163,14 @@ fn convert_to_suggestions(
.flat_map(|val| convert_to_suggestions(val, line, pos, only_buffer_difference)) .flat_map(|val| convert_to_suggestions(val, line, pos, only_buffer_difference))
.collect(), .collect(),
_ => vec![Suggestion { _ => vec![Suggestion {
value: format!("Not a record: {value:?}"), value: format!("Not a record: {:?}", value),
description: None,
extra: None,
span: reedline::Span { span: reedline::Span {
start: if only_buffer_difference { start: 0,
pos - line.len() end: line.len(),
} else {
0
},
end: if only_buffer_difference {
pos
} else {
line.len()
},
}, },
..Suggestion::default() append_whitespace: false,
}], }],
} }
} }

View File

@ -1,5 +1,7 @@
mod description_menu;
mod help_completions; mod help_completions;
mod menu_completions; mod menu_completions;
pub use description_menu::DescriptionMenu;
pub use help_completions::NuHelpCompleter; pub use help_completions::NuHelpCompleter;
pub use menu_completions::NuMenuCompleter; pub use menu_completions::NuMenuCompleter;

View File

@ -1,7 +1,7 @@
use std::sync::Arc; use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_engine::command_prelude::*; use nu_protocol::{Category, Example, PipelineData, ShellError, Signature, Value};
use reedline::{Highlighter, StyledText}; use reedline::Highlighter;
#[derive(Clone)] #[derive(Clone)]
pub struct NuHighlight; pub struct NuHighlight;
@ -12,12 +12,10 @@ impl Command for NuHighlight {
} }
fn signature(&self) -> Signature { fn signature(&self) -> Signature {
Signature::build("nu-highlight") Signature::build("nu-highlight").category(Category::Strings)
.category(Category::Strings)
.input_output_types(vec![(Type::String, Type::String)])
} }
fn description(&self) -> &str { fn usage(&self) -> &str {
"Syntax highlight the input string." "Syntax highlight the input string."
} }
@ -28,28 +26,34 @@ impl Command for NuHighlight {
fn run( fn run(
&self, &self,
engine_state: &EngineState, engine_state: &EngineState,
stack: &mut Stack, _stack: &mut Stack,
call: &Call, call: &Call,
input: PipelineData, input: PipelineData,
) -> Result<PipelineData, ShellError> { ) -> Result<PipelineData, ShellError> {
let head = call.head; let head = call.head;
let signals = engine_state.signals(); let ctrlc = engine_state.ctrlc.clone();
let engine_state = engine_state.clone();
let config = engine_state.get_config().clone();
let highlighter = crate::NuHighlighter { let highlighter = crate::NuHighlighter {
engine_state: Arc::new(engine_state.clone()), engine_state,
stack: Arc::new(stack.clone()), config,
}; };
input.map( input.map(
move |x| match x.coerce_into_string() { move |x| match x.as_string() {
Ok(line) => { Ok(line) => {
let highlights = highlighter.highlight(&line, line.len()); let highlights = highlighter.highlight(&line, line.len());
Value::string(highlights.render_simple(), head)
Value::String {
val: highlights.render_simple(),
span: head,
}
} }
Err(err) => Value::error(err, head), Err(err) => Value::Error { error: err },
}, },
signals, ctrlc,
) )
} }
@ -61,16 +65,3 @@ impl Command for NuHighlight {
}] }]
} }
} }
/// A highlighter that does nothing
///
/// Used to remove highlighting from a reedline instance
/// (letting NuHighlighter structs be dropped)
#[derive(Default)]
pub struct NoOpHighlighter {}
impl Highlighter for NoOpHighlighter {
fn highlight(&self, _line: &str, _cursor: usize) -> reedline::StyledText {
StyledText::new()
}
}

View File

@ -1,5 +1,9 @@
use nu_engine::command_prelude::*; use nu_engine::CallExt;
use nu_protocol::ByteStreamSource; use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, SyntaxShape, Value,
};
#[derive(Clone)] #[derive(Clone)]
pub struct Print; pub struct Print;
@ -11,11 +15,6 @@ impl Command for Print {
fn signature(&self) -> Signature { fn signature(&self) -> Signature {
Signature::build("print") Signature::build("print")
.input_output_types(vec![
(Type::Nothing, Type::Nothing),
(Type::Any, Type::Nothing),
])
.allow_variants_without_examples(true)
.rest("rest", SyntaxShape::Any, "the values to print") .rest("rest", SyntaxShape::Any, "the values to print")
.switch( .switch(
"no-newline", "no-newline",
@ -23,19 +22,14 @@ impl Command for Print {
Some('n'), Some('n'),
) )
.switch("stderr", "print to stderr instead of stdout", Some('e')) .switch("stderr", "print to stderr instead of stdout", Some('e'))
.switch(
"raw",
"print without formatting (including binary data)",
Some('r'),
)
.category(Category::Strings) .category(Category::Strings)
} }
fn description(&self) -> &str { fn usage(&self) -> &str {
"Print the given values to stdout." "Print the given values to stdout"
} }
fn extra_description(&self) -> &str { fn extra_usage(&self) -> &str {
r#"Unlike `echo`, this command does not return any value (`print | describe` will return "nothing"). r#"Unlike `echo`, this command does not return any value (`print | describe` will return "nothing").
Since this command has no output, there is no point in piping it with other commands. Since this command has no output, there is no point in piping it with other commands.
@ -51,38 +45,19 @@ Since this command has no output, there is no point in piping it with other comm
engine_state: &EngineState, engine_state: &EngineState,
stack: &mut Stack, stack: &mut Stack,
call: &Call, call: &Call,
mut input: PipelineData, _input: PipelineData,
) -> Result<PipelineData, ShellError> { ) -> Result<PipelineData, ShellError> {
let args: Vec<Value> = call.rest(engine_state, stack, 0)?; let args: Vec<Value> = call.rest(engine_state, stack, 0)?;
let no_newline = call.has_flag(engine_state, stack, "no-newline")?; let no_newline = call.has_flag("no-newline");
let to_stderr = call.has_flag(engine_state, stack, "stderr")?; let to_stderr = call.has_flag("stderr");
let raw = call.has_flag(engine_state, stack, "raw")?; let head = call.head;
// This will allow for easy printing of pipelines as well for arg in args {
if !args.is_empty() { arg.into_pipeline_data()
for arg in args { .print(engine_state, stack, no_newline, to_stderr)?;
if raw {
arg.into_pipeline_data()
.print_raw(engine_state, no_newline, to_stderr)?;
} else {
arg.into_pipeline_data()
.print(engine_state, stack, no_newline, to_stderr)?;
}
}
} else if !input.is_nothing() {
if let PipelineData::ByteStream(stream, _) = &mut input {
if let ByteStreamSource::Child(child) = stream.source_mut() {
child.ignore_error(true);
}
}
if raw {
input.print_raw(engine_state, no_newline, to_stderr)?;
} else {
input.print(engine_state, stack, no_newline, to_stderr)?;
}
} }
Ok(PipelineData::empty()) Ok(PipelineData::new(head))
} }
fn examples(&self) -> Vec<Example> { fn examples(&self) -> Vec<Example> {
@ -97,11 +72,6 @@ Since this command has no output, there is no point in piping it with other comm
example: r#"print (2 + 3)"#, example: r#"print (2 + 3)"#,
result: None, result: None,
}, },
Example {
description: "Print 'ABC' from binary data",
example: r#"0x[41 42 43] | print --raw"#,
result: None,
},
] ]
} }
} }

View File

@ -1,20 +1,16 @@
use crate::prompt_update::{
POST_PROMPT_MARKER, PRE_PROMPT_MARKER, VSCODE_POST_PROMPT_MARKER, VSCODE_PRE_PROMPT_MARKER,
};
use nu_protocol::engine::{EngineState, Stack};
#[cfg(windows)] #[cfg(windows)]
use nu_utils::enable_vt_processing; use nu_utils::enable_vt_processing;
use reedline::{ use reedline::DefaultPrompt;
DefaultPrompt, Prompt, PromptEditMode, PromptHistorySearch, PromptHistorySearchStatus, use {
PromptViMode, reedline::{
Prompt, PromptEditMode, PromptHistorySearch, PromptHistorySearchStatus, PromptViMode,
},
std::borrow::Cow,
}; };
use std::borrow::Cow;
/// Nushell prompt definition /// Nushell prompt definition
#[derive(Clone)] #[derive(Clone)]
pub struct NushellPrompt { pub struct NushellPrompt {
shell_integration_osc133: bool,
shell_integration_osc633: bool,
left_prompt_string: Option<String>, left_prompt_string: Option<String>,
right_prompt_string: Option<String>, right_prompt_string: Option<String>,
default_prompt_indicator: Option<String>, default_prompt_indicator: Option<String>,
@ -22,20 +18,17 @@ pub struct NushellPrompt {
default_vi_normal_prompt_indicator: Option<String>, default_vi_normal_prompt_indicator: Option<String>,
default_multiline_indicator: Option<String>, default_multiline_indicator: Option<String>,
render_right_prompt_on_last_line: bool, render_right_prompt_on_last_line: bool,
engine_state: EngineState, }
stack: Stack,
impl Default for NushellPrompt {
fn default() -> Self {
NushellPrompt::new()
}
} }
impl NushellPrompt { impl NushellPrompt {
pub fn new( pub fn new() -> NushellPrompt {
shell_integration_osc133: bool,
shell_integration_osc633: bool,
engine_state: EngineState,
stack: Stack,
) -> NushellPrompt {
NushellPrompt { NushellPrompt {
shell_integration_osc133,
shell_integration_osc633,
left_prompt_string: None, left_prompt_string: None,
right_prompt_string: None, right_prompt_string: None,
default_prompt_indicator: None, default_prompt_indicator: None,
@ -43,8 +36,6 @@ impl NushellPrompt {
default_vi_normal_prompt_indicator: None, default_vi_normal_prompt_indicator: None,
default_multiline_indicator: None, default_multiline_indicator: None,
render_right_prompt_on_last_line: false, render_right_prompt_on_last_line: false,
engine_state,
stack,
} }
} }
@ -100,7 +91,7 @@ impl NushellPrompt {
} }
fn default_wrapped_custom_string(&self, str: String) -> String { fn default_wrapped_custom_string(&self, str: String) -> String {
format!("({str})") format!("({})", str)
} }
} }
@ -114,32 +105,12 @@ impl Prompt for NushellPrompt {
if let Some(prompt_string) = &self.left_prompt_string { if let Some(prompt_string) = &self.left_prompt_string {
prompt_string.replace('\n', "\r\n").into() prompt_string.replace('\n', "\r\n").into()
} else { } else {
let default = DefaultPrompt::default(); let default = DefaultPrompt::new();
let prompt = default default
.render_prompt_left() .render_prompt_left()
.to_string() .to_string()
.replace('\n', "\r\n"); .replace('\n', "\r\n")
.into()
if self.shell_integration_osc633 {
if self
.stack
.get_env_var(&self.engine_state, "TERM_PROGRAM")
.and_then(|v| v.as_str().ok())
== Some("vscode")
{
// We're in vscode and we have osc633 enabled
format!("{VSCODE_PRE_PROMPT_MARKER}{prompt}{VSCODE_POST_PROMPT_MARKER}").into()
} else if self.shell_integration_osc133 {
// If we're in VSCode but we don't find the env var, but we have osc133 set, then use it
format!("{PRE_PROMPT_MARKER}{prompt}{POST_PROMPT_MARKER}").into()
} else {
prompt.into()
}
} else if self.shell_integration_osc133 {
format!("{PRE_PROMPT_MARKER}{prompt}{POST_PROMPT_MARKER}").into()
} else {
prompt.into()
}
} }
} }
@ -147,7 +118,7 @@ impl Prompt for NushellPrompt {
if let Some(prompt_string) = &self.right_prompt_string { if let Some(prompt_string) = &self.right_prompt_string {
prompt_string.replace('\n', "\r\n").into() prompt_string.replace('\n', "\r\n").into()
} else { } else {
let default = DefaultPrompt::default(); let default = DefaultPrompt::new();
default default
.render_prompt_right() .render_prompt_right()
.to_string() .to_string()
@ -159,36 +130,32 @@ impl Prompt for NushellPrompt {
fn render_prompt_indicator(&self, edit_mode: PromptEditMode) -> Cow<str> { fn render_prompt_indicator(&self, edit_mode: PromptEditMode) -> Cow<str> {
match edit_mode { match edit_mode {
PromptEditMode::Default => match &self.default_prompt_indicator { PromptEditMode::Default => match &self.default_prompt_indicator {
Some(indicator) => indicator, Some(indicator) => indicator.as_str().into(),
None => "> ", None => "".into(),
} },
.into(),
PromptEditMode::Emacs => match &self.default_prompt_indicator { PromptEditMode::Emacs => match &self.default_prompt_indicator {
Some(indicator) => indicator, Some(indicator) => indicator.as_str().into(),
None => "> ", None => "".into(),
} },
.into(),
PromptEditMode::Vi(vi_mode) => match vi_mode { PromptEditMode::Vi(vi_mode) => match vi_mode {
PromptViMode::Normal => match &self.default_vi_normal_prompt_indicator { PromptViMode::Normal => match &self.default_vi_normal_prompt_indicator {
Some(indicator) => indicator, Some(indicator) => indicator.as_str().into(),
None => "> ", None => ": ".into(),
}, },
PromptViMode::Insert => match &self.default_vi_insert_prompt_indicator { PromptViMode::Insert => match &self.default_vi_insert_prompt_indicator {
Some(indicator) => indicator, Some(indicator) => indicator.as_str().into(),
None => ": ", None => "".into(),
}, },
} },
.into(),
PromptEditMode::Custom(str) => self.default_wrapped_custom_string(str).into(), PromptEditMode::Custom(str) => self.default_wrapped_custom_string(str).into(),
} }
} }
fn render_prompt_multiline_indicator(&self) -> Cow<str> { fn render_prompt_multiline_indicator(&self) -> Cow<str> {
match &self.default_multiline_indicator { match &self.default_multiline_indicator {
Some(indicator) => indicator, Some(indicator) => indicator.as_str().into(),
None => "::: ", None => "::: ".into(),
} }
.into()
} }
fn render_prompt_history_search_indicator( fn render_prompt_history_search_indicator(

View File

@ -1,9 +1,10 @@
use crate::util::report_error;
use crate::NushellPrompt; use crate::NushellPrompt;
use log::trace; use log::info;
use nu_engine::ClosureEvalOnce; use nu_engine::eval_subexpression;
use nu_protocol::{ use nu_protocol::{
engine::{EngineState, Stack}, engine::{EngineState, Stack, StateWorkingSet},
report_shell_error, Config, PipelineData, Value, Config, PipelineData, Span, Value,
}; };
use reedline::Prompt; use reedline::Prompt;
@ -14,49 +15,10 @@ pub(crate) const PROMPT_INDICATOR: &str = "PROMPT_INDICATOR";
pub(crate) const PROMPT_INDICATOR_VI_INSERT: &str = "PROMPT_INDICATOR_VI_INSERT"; pub(crate) const PROMPT_INDICATOR_VI_INSERT: &str = "PROMPT_INDICATOR_VI_INSERT";
pub(crate) const PROMPT_INDICATOR_VI_NORMAL: &str = "PROMPT_INDICATOR_VI_NORMAL"; pub(crate) const PROMPT_INDICATOR_VI_NORMAL: &str = "PROMPT_INDICATOR_VI_NORMAL";
pub(crate) const PROMPT_MULTILINE_INDICATOR: &str = "PROMPT_MULTILINE_INDICATOR"; pub(crate) const PROMPT_MULTILINE_INDICATOR: &str = "PROMPT_MULTILINE_INDICATOR";
pub(crate) const TRANSIENT_PROMPT_COMMAND: &str = "TRANSIENT_PROMPT_COMMAND";
pub(crate) const TRANSIENT_PROMPT_COMMAND_RIGHT: &str = "TRANSIENT_PROMPT_COMMAND_RIGHT";
pub(crate) const TRANSIENT_PROMPT_INDICATOR: &str = "TRANSIENT_PROMPT_INDICATOR";
pub(crate) const TRANSIENT_PROMPT_INDICATOR_VI_INSERT: &str =
"TRANSIENT_PROMPT_INDICATOR_VI_INSERT";
pub(crate) const TRANSIENT_PROMPT_INDICATOR_VI_NORMAL: &str =
"TRANSIENT_PROMPT_INDICATOR_VI_NORMAL";
pub(crate) const TRANSIENT_PROMPT_MULTILINE_INDICATOR: &str =
"TRANSIENT_PROMPT_MULTILINE_INDICATOR";
// Store all these Ansi Escape Markers here so they can be reused easily
// According to Daniel Imms @Tyriar, we need to do these this way: // According to Daniel Imms @Tyriar, we need to do these this way:
// <133 A><prompt><133 B><command><133 C><command output> // <133 A><prompt><133 B><command><133 C><command output>
pub(crate) const PRE_PROMPT_MARKER: &str = "\x1b]133;A\x1b\\"; const PRE_PROMPT_MARKER: &str = "\x1b]133;A\x1b\\";
pub(crate) const POST_PROMPT_MARKER: &str = "\x1b]133;B\x1b\\"; const POST_PROMPT_MARKER: &str = "\x1b]133;B\x1b\\";
pub(crate) const PRE_EXECUTION_MARKER: &str = "\x1b]133;C\x1b\\";
#[allow(dead_code)]
pub(crate) const POST_EXECUTION_MARKER_PREFIX: &str = "\x1b]133;D;";
#[allow(dead_code)]
pub(crate) const POST_EXECUTION_MARKER_SUFFIX: &str = "\x1b\\";
// OSC633 is the same as OSC133 but specifically for VSCode
pub(crate) const VSCODE_PRE_PROMPT_MARKER: &str = "\x1b]633;A\x1b\\";
pub(crate) const VSCODE_POST_PROMPT_MARKER: &str = "\x1b]633;B\x1b\\";
#[allow(dead_code)]
pub(crate) const VSCODE_PRE_EXECUTION_MARKER: &str = "\x1b]633;C\x1b\\";
#[allow(dead_code)]
//"\x1b]633;D;{}\x1b\\"
pub(crate) const VSCODE_POST_EXECUTION_MARKER_PREFIX: &str = "\x1b]633;D;";
#[allow(dead_code)]
pub(crate) const VSCODE_POST_EXECUTION_MARKER_SUFFIX: &str = "\x1b\\";
#[allow(dead_code)]
//"\x1b]633;E;{}\x1b\\"
pub(crate) const VSCODE_COMMANDLINE_MARKER_PREFIX: &str = "\x1b]633;E;";
#[allow(dead_code)]
pub(crate) const VSCODE_COMMANDLINE_MARKER_SUFFIX: &str = "\x1b\\";
#[allow(dead_code)]
// "\x1b]633;P;Cwd={}\x1b\\"
pub(crate) const VSCODE_CWD_PROPERTY_MARKER_PREFIX: &str = "\x1b]633;P;Cwd=";
#[allow(dead_code)]
pub(crate) const VSCODE_CWD_PROPERTY_MARKER_SUFFIX: &str = "\x1b\\";
pub(crate) const RESET_APPLICATION_MODE: &str = "\x1b[?1l";
fn get_prompt_string( fn get_prompt_string(
prompt: &str, prompt: &str,
@ -67,22 +29,60 @@ fn get_prompt_string(
stack stack
.get_env_var(engine_state, prompt) .get_env_var(engine_state, prompt)
.and_then(|v| match v { .and_then(|v| match v {
Value::Closure { val, .. } => { Value::Closure {
let result = ClosureEvalOnce::new(engine_state, stack, val.as_ref().clone()) val: block_id,
.run_with_input(PipelineData::Empty); captures,
..
trace!( } => {
let block = engine_state.get_block(block_id);
let mut stack = stack.captures_to_stack(&captures);
// Use eval_subexpression to force a redirection of output, so we can use everything in prompt
let ret_val = eval_subexpression(
engine_state,
&mut stack,
block,
PipelineData::new(Span::new(0, 0)), // Don't try this at home, 0 span is ignored
);
info!(
"get_prompt_string (block) {}:{}:{}", "get_prompt_string (block) {}:{}:{}",
file!(), file!(),
line!(), line!(),
column!() column!()
); );
result match ret_val {
.map_err(|err| { Ok(ret_val) => Some(ret_val),
report_shell_error(engine_state, &err); Err(err) => {
}) let working_set = StateWorkingSet::new(engine_state);
.ok() report_error(&working_set, &err);
None
}
}
}
Value::Block { val: block_id, .. } => {
let block = engine_state.get_block(block_id);
// Use eval_subexpression to force a redirection of output, so we can use everything in prompt
let ret_val = eval_subexpression(
engine_state,
stack,
block,
PipelineData::new(Span::new(0, 0)), // Don't try this at home, 0 span is ignored
);
info!(
"get_prompt_string (block) {}:{}:{}",
file!(),
line!(),
column!()
);
match ret_val {
Ok(ret_val) => Some(ret_val),
Err(err) => {
let working_set = StateWorkingSet::new(engine_state);
report_error(&working_set, &err);
None
}
}
} }
Value::String { .. } => Some(PipelineData::Value(v.clone(), None)), Value::String { .. } => Some(PipelineData::Value(v.clone(), None)),
_ => None, _ => None,
@ -90,72 +90,61 @@ fn get_prompt_string(
.and_then(|pipeline_data| { .and_then(|pipeline_data| {
let output = pipeline_data.collect_string("", config).ok(); let output = pipeline_data.collect_string("", config).ok();
output.map(|mut x| { match output {
// Just remove the very last newline. Some(mut x) => {
if x.ends_with('\n') { // Just remove the very last newline.
x.pop(); if x.ends_with('\n') {
} x.pop();
}
if x.ends_with('\r') { if x.ends_with('\r') {
x.pop(); x.pop();
}
Some(x)
} }
x None => None,
}) }
}) })
} }
pub(crate) fn update_prompt( pub(crate) fn update_prompt<'prompt>(
config: &Config, config: &Config,
engine_state: &EngineState, engine_state: &EngineState,
stack: &mut Stack, stack: &Stack,
nu_prompt: &mut NushellPrompt, nu_prompt: &'prompt mut NushellPrompt,
) { ) -> &'prompt dyn Prompt {
let configured_left_prompt_string = let mut stack = stack.clone();
match get_prompt_string(PROMPT_COMMAND, config, engine_state, stack) {
Some(s) => s, let left_prompt_string = get_prompt_string(PROMPT_COMMAND, config, engine_state, &mut stack);
None => "".to_string(),
};
// Now that we have the prompt string lets ansify it. // Now that we have the prompt string lets ansify it.
// <133 A><prompt><133 B><command><133 C><command output> // <133 A><prompt><133 B><command><133 C><command output>
let left_prompt_string = if config.shell_integration.osc633 { let left_prompt_string = if config.shell_integration {
if stack match left_prompt_string {
.get_env_var(engine_state, "TERM_PROGRAM") Some(prompt_string) => Some(format!(
.and_then(|v| v.as_str().ok()) "{}{}{}",
== Some("vscode") PRE_PROMPT_MARKER, prompt_string, POST_PROMPT_MARKER
{ )),
// We're in vscode and we have osc633 enabled None => left_prompt_string,
Some(format!(
"{VSCODE_PRE_PROMPT_MARKER}{configured_left_prompt_string}{VSCODE_POST_PROMPT_MARKER}"
))
} else if config.shell_integration.osc133 {
// If we're in VSCode but we don't find the env var, but we have osc133 set, then use it
Some(format!(
"{PRE_PROMPT_MARKER}{configured_left_prompt_string}{POST_PROMPT_MARKER}"
))
} else {
configured_left_prompt_string.into()
} }
} else if config.shell_integration.osc133 {
Some(format!(
"{PRE_PROMPT_MARKER}{configured_left_prompt_string}{POST_PROMPT_MARKER}"
))
} else { } else {
configured_left_prompt_string.into() left_prompt_string
}; };
let right_prompt_string = get_prompt_string(PROMPT_COMMAND_RIGHT, config, engine_state, stack); let right_prompt_string =
get_prompt_string(PROMPT_COMMAND_RIGHT, config, engine_state, &mut stack);
let prompt_indicator_string = get_prompt_string(PROMPT_INDICATOR, config, engine_state, stack); let prompt_indicator_string =
get_prompt_string(PROMPT_INDICATOR, config, engine_state, &mut stack);
let prompt_multiline_string = let prompt_multiline_string =
get_prompt_string(PROMPT_MULTILINE_INDICATOR, config, engine_state, stack); get_prompt_string(PROMPT_MULTILINE_INDICATOR, config, engine_state, &mut stack);
let prompt_vi_insert_string = let prompt_vi_insert_string =
get_prompt_string(PROMPT_INDICATOR_VI_INSERT, config, engine_state, stack); get_prompt_string(PROMPT_INDICATOR_VI_INSERT, config, engine_state, &mut stack);
let prompt_vi_normal_string = let prompt_vi_normal_string =
get_prompt_string(PROMPT_INDICATOR_VI_NORMAL, config, engine_state, stack); get_prompt_string(PROMPT_INDICATOR_VI_NORMAL, config, engine_state, &mut stack);
// apply the other indicators // apply the other indicators
nu_prompt.update_all_prompt_strings( nu_prompt.update_all_prompt_strings(
@ -166,55 +155,9 @@ pub(crate) fn update_prompt(
(prompt_vi_insert_string, prompt_vi_normal_string), (prompt_vi_insert_string, prompt_vi_normal_string),
config.render_right_prompt_on_last_line, config.render_right_prompt_on_last_line,
); );
trace!("update_prompt {}:{}:{}", file!(), line!(), column!());
} let ret_val = nu_prompt as &dyn Prompt;
info!("update_prompt {}:{}:{}", file!(), line!(), column!());
/// Construct the transient prompt based on the normal nu_prompt
pub(crate) fn make_transient_prompt( ret_val
config: &Config,
engine_state: &EngineState,
stack: &mut Stack,
nu_prompt: &NushellPrompt,
) -> Box<dyn Prompt> {
let mut nu_prompt = nu_prompt.clone();
if let Some(s) = get_prompt_string(TRANSIENT_PROMPT_COMMAND, config, engine_state, stack) {
nu_prompt.update_prompt_left(Some(s))
}
if let Some(s) = get_prompt_string(TRANSIENT_PROMPT_COMMAND_RIGHT, config, engine_state, stack)
{
nu_prompt.update_prompt_right(Some(s), config.render_right_prompt_on_last_line)
}
if let Some(s) = get_prompt_string(TRANSIENT_PROMPT_INDICATOR, config, engine_state, stack) {
nu_prompt.update_prompt_indicator(Some(s))
}
if let Some(s) = get_prompt_string(
TRANSIENT_PROMPT_INDICATOR_VI_INSERT,
config,
engine_state,
stack,
) {
nu_prompt.update_prompt_vi_insert(Some(s))
}
if let Some(s) = get_prompt_string(
TRANSIENT_PROMPT_INDICATOR_VI_NORMAL,
config,
engine_state,
stack,
) {
nu_prompt.update_prompt_vi_normal(Some(s))
}
if let Some(s) = get_prompt_string(
TRANSIENT_PROMPT_MULTILINE_INDICATOR,
config,
engine_state,
stack,
) {
nu_prompt.update_prompt_multiline(Some(s))
}
Box::new(nu_prompt)
} }

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,57 +1,28 @@
use log::trace; use log::trace;
use nu_ansi_term::Style; use nu_ansi_term::Style;
use nu_color_config::{get_matching_brackets_style, get_shape_color}; use nu_color_config::{get_matching_brackets_style, get_shape_color};
use nu_engine::env;
use nu_parser::{flatten_block, parse, FlatShape}; use nu_parser::{flatten_block, parse, FlatShape};
use nu_protocol::{ use nu_protocol::ast::{Argument, Block, Expr, Expression, PipelineElement};
ast::{Block, Expr, Expression, PipelineRedirection, RecordItem}, use nu_protocol::engine::{EngineState, StateWorkingSet};
engine::{EngineState, Stack, StateWorkingSet}, use nu_protocol::{Config, Span};
Span,
};
use reedline::{Highlighter, StyledText}; use reedline::{Highlighter, StyledText};
use std::sync::Arc;
pub struct NuHighlighter { pub struct NuHighlighter {
pub engine_state: Arc<EngineState>, pub engine_state: EngineState,
pub stack: Arc<Stack>, pub config: Config,
} }
impl Highlighter for NuHighlighter { impl Highlighter for NuHighlighter {
fn highlight(&self, line: &str, _cursor: usize) -> StyledText { fn highlight(&self, line: &str, _cursor: usize) -> StyledText {
trace!("highlighting: {}", line); trace!("highlighting: {}", line);
let config = self.stack.get_config(&self.engine_state);
let highlight_resolved_externals = config.highlight_resolved_externals;
let mut working_set = StateWorkingSet::new(&self.engine_state); let mut working_set = StateWorkingSet::new(&self.engine_state);
let block = parse(&mut working_set, None, line.as_bytes(), false); let block = {
let (block, _) = parse(&mut working_set, None, line.as_bytes(), false, &[]);
block
};
let (shapes, global_span_offset) = { let (shapes, global_span_offset) = {
let mut shapes = flatten_block(&working_set, &block); let shapes = flatten_block(&working_set, &block);
// Highlighting externals has a config point because of concerns that using which to resolve
// externals may slow down things too much.
if highlight_resolved_externals {
for (span, shape) in shapes.iter_mut() {
if *shape == FlatShape::External {
let str_contents =
working_set.get_span_contents(Span::new(span.start, span.end));
let str_word = String::from_utf8_lossy(str_contents).to_string();
let paths = env::path_str(&self.engine_state, &self.stack, *span).ok();
#[allow(deprecated)]
let res = if let Ok(cwd) =
env::current_dir_str(&self.engine_state, &self.stack)
{
which::which_in(str_word, paths.as_ref(), cwd).ok()
} else {
which::which_in_global(str_word, paths.as_ref())
.ok()
.and_then(|mut i| i.next())
};
if res.is_some() {
*shape = FlatShape::ExternalResolved;
}
}
}
}
(shapes, self.engine_state.next_span_start()) (shapes, self.engine_state.next_span_start())
}; };
@ -86,69 +57,74 @@ impl Highlighter for NuHighlighter {
[(shape.0.start - global_span_offset)..(shape.0.end - global_span_offset)] [(shape.0.start - global_span_offset)..(shape.0.end - global_span_offset)]
.to_string(); .to_string();
let mut add_colored_token = |shape: &FlatShape, text: String| { macro_rules! add_colored_token_with_bracket_highlight {
output.push((get_shape_color(shape.as_str(), &config), text)); ($shape:expr, $span:expr, $text:expr) => {{
};
match shape.1 {
FlatShape::Garbage => add_colored_token(&shape.1, next_token),
FlatShape::Nothing => add_colored_token(&shape.1, next_token),
FlatShape::Binary => add_colored_token(&shape.1, next_token),
FlatShape::Bool => add_colored_token(&shape.1, next_token),
FlatShape::Int => add_colored_token(&shape.1, next_token),
FlatShape::Float => add_colored_token(&shape.1, next_token),
FlatShape::Range => add_colored_token(&shape.1, next_token),
FlatShape::InternalCall(_) => add_colored_token(&shape.1, next_token),
FlatShape::External => add_colored_token(&shape.1, next_token),
FlatShape::ExternalArg => add_colored_token(&shape.1, next_token),
FlatShape::ExternalResolved => add_colored_token(&shape.1, next_token),
FlatShape::Keyword => add_colored_token(&shape.1, next_token),
FlatShape::Literal => add_colored_token(&shape.1, next_token),
FlatShape::Operator => add_colored_token(&shape.1, next_token),
FlatShape::Signature => add_colored_token(&shape.1, next_token),
FlatShape::String => add_colored_token(&shape.1, next_token),
FlatShape::RawString => add_colored_token(&shape.1, next_token),
FlatShape::StringInterpolation => add_colored_token(&shape.1, next_token),
FlatShape::DateTime => add_colored_token(&shape.1, next_token),
FlatShape::List
| FlatShape::Table
| FlatShape::Record
| FlatShape::Block
| FlatShape::Closure => {
let span = shape.0;
let shape = &shape.1;
let spans = split_span_by_highlight_positions( let spans = split_span_by_highlight_positions(
line, line,
span, &$span,
&matching_brackets_pos, &matching_brackets_pos,
global_span_offset, global_span_offset,
); );
for (part, highlight) in spans { spans.iter().for_each(|(part, highlight)| {
let start = part.start - span.start; let start = part.start - $span.start;
let end = part.end - span.start; let end = part.end - $span.start;
let text = next_token[start..end].to_string(); let text = (&next_token[start..end]).to_string();
let mut style = get_shape_color(shape.as_str(), &config); let mut style = get_shape_color($shape.to_string(), &self.config);
if highlight { if *highlight {
style = get_matching_brackets_style(style, &config); style = get_matching_brackets_style(style, &self.config);
} }
output.push((style, text)); output.push((style, text));
} });
}};
}
macro_rules! add_colored_token {
($shape:expr, $text:expr) => {
output.push((get_shape_color($shape.to_string(), &self.config), $text))
};
}
match shape.1 {
FlatShape::Garbage => add_colored_token!(shape.1, next_token),
FlatShape::Nothing => add_colored_token!(shape.1, next_token),
FlatShape::Binary => add_colored_token!(shape.1, next_token),
FlatShape::Bool => add_colored_token!(shape.1, next_token),
FlatShape::Int => add_colored_token!(shape.1, next_token),
FlatShape::Float => add_colored_token!(shape.1, next_token),
FlatShape::Range => add_colored_token!(shape.1, next_token),
FlatShape::InternalCall => add_colored_token!(shape.1, next_token),
FlatShape::External => add_colored_token!(shape.1, next_token),
FlatShape::ExternalArg => add_colored_token!(shape.1, next_token),
FlatShape::Literal => add_colored_token!(shape.1, next_token),
FlatShape::Operator => add_colored_token!(shape.1, next_token),
FlatShape::Signature => add_colored_token!(shape.1, next_token),
FlatShape::String => add_colored_token!(shape.1, next_token),
FlatShape::StringInterpolation => add_colored_token!(shape.1, next_token),
FlatShape::DateTime => add_colored_token!(shape.1, next_token),
FlatShape::List => {
add_colored_token_with_bracket_highlight!(shape.1, shape.0, next_token)
}
FlatShape::Table => {
add_colored_token_with_bracket_highlight!(shape.1, shape.0, next_token)
}
FlatShape::Record => {
add_colored_token_with_bracket_highlight!(shape.1, shape.0, next_token)
} }
FlatShape::Filepath => add_colored_token(&shape.1, next_token), FlatShape::Block => {
FlatShape::Directory => add_colored_token(&shape.1, next_token), add_colored_token_with_bracket_highlight!(shape.1, shape.0, next_token)
FlatShape::GlobInterpolation => add_colored_token(&shape.1, next_token),
FlatShape::GlobPattern => add_colored_token(&shape.1, next_token),
FlatShape::Variable(_) | FlatShape::VarDecl(_) => {
add_colored_token(&shape.1, next_token)
} }
FlatShape::Flag => add_colored_token(&shape.1, next_token),
FlatShape::Pipe => add_colored_token(&shape.1, next_token), FlatShape::Filepath => add_colored_token!(shape.1, next_token),
FlatShape::And => add_colored_token(&shape.1, next_token), FlatShape::Directory => add_colored_token!(shape.1, next_token),
FlatShape::Or => add_colored_token(&shape.1, next_token), FlatShape::GlobPattern => add_colored_token!(shape.1, next_token),
FlatShape::Redirection => add_colored_token(&shape.1, next_token), FlatShape::Variable => add_colored_token!(shape.1, next_token),
FlatShape::Custom(..) => add_colored_token(&shape.1, next_token), FlatShape::Flag => add_colored_token!(shape.1, next_token),
FlatShape::MatchPattern => add_colored_token(&shape.1, next_token), FlatShape::Pipe => add_colored_token!(shape.1, next_token),
FlatShape::And => add_colored_token!(shape.1, next_token),
FlatShape::Or => add_colored_token!(shape.1, next_token),
FlatShape::Redirection => add_colored_token!(shape.1, next_token),
FlatShape::Custom(..) => add_colored_token!(shape.1, next_token),
} }
last_seen_span = shape.0.end; last_seen_span = shape.0.end;
} }
@ -164,8 +140,8 @@ impl Highlighter for NuHighlighter {
fn split_span_by_highlight_positions( fn split_span_by_highlight_positions(
line: &str, line: &str,
span: Span, span: &Span,
highlight_positions: &[usize], highlight_positions: &Vec<usize>,
global_span_offset: usize, global_span_offset: usize,
) -> Vec<(Span, bool)> { ) -> Vec<(Span, bool)> {
let mut start = span.start; let mut start = span.start;
@ -173,7 +149,7 @@ fn split_span_by_highlight_positions(
for pos in highlight_positions { for pos in highlight_positions {
if start <= *pos && pos < &span.end { if start <= *pos && pos < &span.end {
if start < *pos { if start < *pos {
result.push((Span::new(start, *pos), false)); result.push((Span { start, end: *pos }, false));
} }
let span_str = &line[pos - global_span_offset..span.end - global_span_offset]; let span_str = &line[pos - global_span_offset..span.end - global_span_offset];
let end = span_str let end = span_str
@ -181,12 +157,18 @@ fn split_span_by_highlight_positions(
.next() .next()
.map(|c| pos + get_char_length(c)) .map(|c| pos + get_char_length(c))
.unwrap_or(pos + 1); .unwrap_or(pos + 1);
result.push((Span::new(*pos, end), true)); result.push((Span { start: *pos, end }, true));
start = end; start = end;
} }
} }
if start < span.end { if start < span.end {
result.push((Span::new(start, span.end), false)); result.push((
Span {
start,
end: span.end,
},
false,
));
} }
result result
} }
@ -253,38 +235,22 @@ fn find_matching_block_end_in_block(
) -> Option<usize> { ) -> Option<usize> {
for p in &block.pipelines { for p in &block.pipelines {
for e in &p.elements { for e in &p.elements {
if e.expr.span.contains(global_cursor_offset) { match e {
if let Some(pos) = find_matching_block_end_in_expr( PipelineElement::Expression(_, e)
line, | PipelineElement::Redirection(_, _, e)
working_set, | PipelineElement::And(_, e)
&e.expr, | PipelineElement::Or(_, e) => {
global_span_offset, if e.span.contains(global_cursor_offset) {
global_cursor_offset, if let Some(pos) = find_matching_block_end_in_expr(
) { line,
return Some(pos); working_set,
} e,
} global_span_offset,
global_cursor_offset,
if let Some(redirection) = e.redirection.as_ref() { ) {
match redirection {
PipelineRedirection::Single { target, .. }
| PipelineRedirection::Separate { out: target, .. }
| PipelineRedirection::Separate { err: target, .. }
if target.span().contains(global_cursor_offset) =>
{
if let Some(pos) = target.expr().and_then(|expr| {
find_matching_block_end_in_expr(
line,
working_set,
expr,
global_span_offset,
global_cursor_offset,
)
}) {
return Some(pos); return Some(pos);
} }
} }
_ => {}
} }
} }
} }
@ -299,6 +265,20 @@ fn find_matching_block_end_in_expr(
global_span_offset: usize, global_span_offset: usize,
global_cursor_offset: usize, global_cursor_offset: usize,
) -> Option<usize> { ) -> Option<usize> {
macro_rules! find_in_expr_or_continue {
($inner_expr:ident) => {
if let Some(pos) = find_matching_block_end_in_expr(
line,
working_set,
$inner_expr,
global_span_offset,
global_cursor_offset,
) {
return Some(pos);
}
};
}
if expression.span.contains(global_cursor_offset) && expression.span.start >= global_span_offset if expression.span.contains(global_cursor_offset) && expression.span.start >= global_span_offset
{ {
let expr_first = expression.span.start; let expr_first = expression.span.start;
@ -324,20 +304,18 @@ fn find_matching_block_end_in_expr(
Expr::Keyword(..) => None, Expr::Keyword(..) => None,
Expr::ValueWithUnit(..) => None, Expr::ValueWithUnit(..) => None,
Expr::DateTime(_) => None, Expr::DateTime(_) => None,
Expr::Filepath(_, _) => None, Expr::Filepath(_) => None,
Expr::Directory(_, _) => None, Expr::Directory(_) => None,
Expr::GlobPattern(_, _) => None, Expr::GlobPattern(_) => None,
Expr::String(_) => None, Expr::String(_) => None,
Expr::RawString(_) => None,
Expr::CellPath(_) => None, Expr::CellPath(_) => None,
Expr::ImportPattern(_) => None, Expr::ImportPattern(_) => None,
Expr::Overlay(_) => None, Expr::Overlay(_) => None,
Expr::Signature(_) => None, Expr::Signature(_) => None,
Expr::MatchBlock(_) => None,
Expr::Nothing => None, Expr::Nothing => None,
Expr::Garbage => None, Expr::Garbage => None,
Expr::Table(table) => { Expr::Table(hdr, rows) => {
if expr_last == global_cursor_offset { if expr_last == global_cursor_offset {
// cursor is at table end // cursor is at table end
Some(expr_first) Some(expr_first)
@ -346,19 +324,15 @@ fn find_matching_block_end_in_expr(
Some(expr_last) Some(expr_last)
} else { } else {
// cursor is inside table // cursor is inside table
table for inner_expr in hdr {
.columns find_in_expr_or_continue!(inner_expr);
.iter() }
.chain(table.rows.iter().flat_map(AsRef::as_ref)) for row in rows {
.find_map(|expr| { for inner_expr in row {
find_matching_block_end_in_expr( find_in_expr_or_continue!(inner_expr);
line, }
working_set, }
expr, None
global_span_offset,
global_cursor_offset,
)
})
} }
} }
@ -371,45 +345,27 @@ fn find_matching_block_end_in_expr(
Some(expr_last) Some(expr_last)
} else { } else {
// cursor is inside record // cursor is inside record
exprs.iter().find_map(|expr| match expr { for (k, v) in exprs {
RecordItem::Pair(k, v) => find_matching_block_end_in_expr( find_in_expr_or_continue!(k);
line, find_in_expr_or_continue!(v);
working_set, }
k, None
global_span_offset,
global_cursor_offset,
)
.or_else(|| {
find_matching_block_end_in_expr(
line,
working_set,
v,
global_span_offset,
global_cursor_offset,
)
}),
RecordItem::Spread(_, record) => find_matching_block_end_in_expr(
line,
working_set,
record,
global_span_offset,
global_cursor_offset,
),
})
} }
} }
Expr::Call(call) => call.arguments.iter().find_map(|arg| { Expr::Call(call) => {
arg.expr().and_then(|expr| { for arg in &call.arguments {
find_matching_block_end_in_expr( let opt_expr = match arg {
line, Argument::Named((_, _, opt_expr)) => opt_expr.as_ref(),
working_set, Argument::Positional(inner_expr) => Some(inner_expr),
expr, };
global_span_offset,
global_cursor_offset, if let Some(inner_expr) = opt_expr {
) find_in_expr_or_continue!(inner_expr);
}) }
}), }
None
}
Expr::FullCellPath(b) => find_matching_block_end_in_expr( Expr::FullCellPath(b) => find_matching_block_end_in_expr(
line, line,
@ -419,23 +375,12 @@ fn find_matching_block_end_in_expr(
global_cursor_offset, global_cursor_offset,
), ),
Expr::BinaryOp(lhs, op, rhs) => [lhs, op, rhs].into_iter().find_map(|expr| { Expr::BinaryOp(lhs, op, rhs) => {
find_matching_block_end_in_expr( find_in_expr_or_continue!(lhs);
line, find_in_expr_or_continue!(op);
working_set, find_in_expr_or_continue!(rhs);
expr, None
global_span_offset, }
global_cursor_offset,
)
}),
Expr::Collect(_, expr) => find_matching_block_end_in_expr(
line,
working_set,
expr,
global_span_offset,
global_cursor_offset,
),
Expr::Block(block_id) Expr::Block(block_id)
| Expr::Closure(block_id) | Expr::Closure(block_id)
@ -460,19 +405,14 @@ fn find_matching_block_end_in_expr(
} }
} }
Expr::StringInterpolation(exprs) | Expr::GlobInterpolation(exprs, _) => { Expr::StringInterpolation(inner_expr) => {
exprs.iter().find_map(|expr| { for inner_expr in inner_expr {
find_matching_block_end_in_expr( find_in_expr_or_continue!(inner_expr);
line, }
working_set, None
expr,
global_span_offset,
global_cursor_offset,
)
})
} }
Expr::List(list) => { Expr::List(inner_expr) => {
if expr_last == global_cursor_offset { if expr_last == global_cursor_offset {
// cursor is at list end // cursor is at list end
Some(expr_first) Some(expr_first)
@ -480,15 +420,11 @@ fn find_matching_block_end_in_expr(
// cursor is at list start // cursor is at list start
Some(expr_last) Some(expr_last)
} else { } else {
list.iter().find_map(|item| { // cursor is inside list
find_matching_block_end_in_expr( for inner_expr in inner_expr {
line, find_in_expr_or_continue!(inner_expr);
working_set, }
item.expr(), None
global_span_offset,
global_cursor_offset,
)
})
} }
} }
}; };

View File

@ -1,17 +1,15 @@
use nu_cmd_base::hook::eval_hook; use crate::repl::eval_hook;
use nu_engine::{eval_block, eval_block_with_early_return}; use nu_engine::eval_block;
use nu_parser::{escape_quote_string, lex, parse, unescape_unquote_string, Token, TokenContents}; use nu_parser::{escape_quote_string, lex, parse, unescape_unquote_string, Token, TokenContents};
use nu_protocol::engine::StateWorkingSet;
use nu_protocol::CliError;
use nu_protocol::{ use nu_protocol::{
cli_error::report_compile_error, engine::{EngineState, Stack},
debugger::WithoutDebug, print_if_stream, PipelineData, ShellError, Span, Value,
engine::{EngineState, Stack, StateWorkingSet},
report_parse_error, report_parse_warning, report_shell_error, PipelineData, ShellError, Span,
Value,
}; };
#[cfg(windows)] #[cfg(windows)]
use nu_utils::enable_vt_processing; use nu_utils::enable_vt_processing;
use nu_utils::perf; use std::path::{Path, PathBuf};
use std::path::Path;
// This will collect environment variables from std::env and adds them to a stack. // This will collect environment variables from std::env and adds them to a stack.
// //
@ -41,15 +39,16 @@ fn gather_env_vars(
init_cwd: &Path, init_cwd: &Path,
) { ) {
fn report_capture_error(engine_state: &EngineState, env_str: &str, msg: &str) { fn report_capture_error(engine_state: &EngineState, env_str: &str, msg: &str) {
report_shell_error( let working_set = StateWorkingSet::new(engine_state);
engine_state, report_error(
&ShellError::GenericError { &working_set,
error: format!("Environment variable was not captured: {env_str}"), &ShellError::GenericError(
msg: "".into(), format!("Environment variable was not captured: {}", env_str),
span: None, "".to_string(),
help: Some(msg.into()), None,
inner: vec![], Some(msg.into()),
}, Vec::new(),
),
); );
} }
@ -72,17 +71,19 @@ fn gather_env_vars(
} }
None => { None => {
// Could not capture current working directory // Could not capture current working directory
report_shell_error( let working_set = StateWorkingSet::new(engine_state);
engine_state, report_error(
&ShellError::GenericError { &working_set,
error: "Current directory is not a valid utf-8 path".into(), &ShellError::GenericError(
msg: "".into(), "Current directory is not a valid utf-8 path".to_string(),
span: None, "".to_string(),
help: Some(format!( None,
"Retrieving current directory failed: {init_cwd:?} not a valid utf-8 path" Some(format!(
"Retrieving current directory failed: {:?} not a valid utf-8 path",
init_cwd
)), )),
inner: vec![], Vec::new(),
}, ),
); );
} }
} }
@ -92,8 +93,8 @@ fn gather_env_vars(
let span_offset = engine_state.next_span_start(); let span_offset = engine_state.next_span_start();
engine_state.add_file( engine_state.add_file(
"Host Environment Variables".into(), "Host Environment Variables".to_string(),
fake_env_file.as_bytes().into(), fake_env_file.as_bytes().to_vec(),
); );
let (tokens, _) = lex(fake_env_file.as_bytes(), span_offset, &[], &[], true); let (tokens, _) = lex(fake_env_file.as_bytes(), span_offset, &[], &[], true);
@ -104,16 +105,15 @@ fn gather_env_vars(
span: full_span, span: full_span,
} = token } = token
{ {
let contents = engine_state.get_span_contents(full_span); let contents = engine_state.get_span_contents(&full_span);
let (parts, _) = lex(contents, full_span.start, &[], &[b'='], true); let (parts, _) = lex(contents, full_span.start, &[], &[b'='], true);
let name = if let Some(Token { let name = if let Some(Token {
contents: TokenContents::Item, contents: TokenContents::Item,
span, span,
}) = parts.first() }) = parts.get(0)
{ {
let mut working_set = StateWorkingSet::new(engine_state); let bytes = engine_state.get_span_contents(span);
let bytes = working_set.get_span_contents(*span);
if bytes.len() < 2 { if bytes.len() < 2 {
report_capture_error( report_capture_error(
@ -125,12 +125,9 @@ fn gather_env_vars(
continue; continue;
} }
let (bytes, err) = unescape_unquote_string(bytes, *span); let (bytes, parse_error) = unescape_unquote_string(bytes, *span);
if let Some(err) = err {
working_set.error(err);
}
if working_set.parse_errors.first().is_some() { if parse_error.is_some() {
report_capture_error( report_capture_error(
engine_state, engine_state,
&String::from_utf8_lossy(contents), &String::from_utf8_lossy(contents),
@ -156,8 +153,7 @@ fn gather_env_vars(
span, span,
}) = parts.get(2) }) = parts.get(2)
{ {
let mut working_set = StateWorkingSet::new(engine_state); let bytes = engine_state.get_span_contents(span);
let bytes = working_set.get_span_contents(*span);
if bytes.len() < 2 { if bytes.len() < 2 {
report_capture_error( report_capture_error(
@ -169,12 +165,9 @@ fn gather_env_vars(
continue; continue;
} }
let (bytes, err) = unescape_unquote_string(bytes, *span); let (bytes, parse_error) = unescape_unquote_string(bytes, *span);
if let Some(err) = err {
working_set.error(err);
}
if working_set.parse_errors.first().is_some() { if parse_error.is_some() {
report_capture_error( report_capture_error(
engine_state, engine_state,
&String::from_utf8_lossy(contents), &String::from_utf8_lossy(contents),
@ -184,7 +177,10 @@ fn gather_env_vars(
continue; continue;
} }
Value::string(bytes, *span) Value::String {
val: bytes,
span: *span,
}
} else { } else {
report_capture_error( report_capture_error(
engine_state, engine_state,
@ -207,97 +203,142 @@ pub fn eval_source(
source: &[u8], source: &[u8],
fname: &str, fname: &str,
input: PipelineData, input: PipelineData,
allow_return: bool, ) -> bool {
) -> i32 {
let start_time = std::time::Instant::now();
let exit_code = match evaluate_source(engine_state, stack, source, fname, input, allow_return) {
Ok(failed) => {
let code = failed.into();
stack.set_last_exit_code(code, Span::unknown());
code
}
Err(err) => {
report_shell_error(engine_state, &err);
let code = err.exit_code();
stack.set_last_error(&err);
code.unwrap_or(0)
}
};
// reset vt processing, aka ansi because illbehaved externals can break it
#[cfg(windows)]
{
let _ = enable_vt_processing();
}
perf!(
&format!("eval_source {}", &fname),
start_time,
engine_state.get_config().use_ansi_coloring
);
exit_code
}
fn evaluate_source(
engine_state: &mut EngineState,
stack: &mut Stack,
source: &[u8],
fname: &str,
input: PipelineData,
allow_return: bool,
) -> Result<bool, ShellError> {
let (block, delta) = { let (block, delta) = {
let mut working_set = StateWorkingSet::new(engine_state); let mut working_set = StateWorkingSet::new(engine_state);
let output = parse( let (output, err) = parse(
&mut working_set, &mut working_set,
Some(fname), // format!("entry #{}", entry_num) Some(fname), // format!("entry #{}", entry_num)
source, source,
false, false,
&[],
); );
if let Some(warning) = working_set.parse_warnings.first() { if let Some(err) = err {
report_parse_warning(&working_set, warning); set_last_exit_code(stack, 1);
} report_error(&working_set, &err);
return false;
if let Some(err) = working_set.parse_errors.first() {
report_parse_error(&working_set, err);
return Ok(true);
}
if let Some(err) = working_set.compile_errors.first() {
report_compile_error(&working_set, err);
// Not a fatal error, for now
} }
(output, working_set.render()) (output, working_set.render())
}; };
engine_state.merge_delta(delta)?; if let Err(err) = engine_state.merge_delta(delta) {
set_last_exit_code(stack, 1);
report_error_new(engine_state, &err);
return false;
}
let pipeline = if allow_return { match eval_block(engine_state, stack, &block, input, false, false) {
eval_block_with_early_return::<WithoutDebug>(engine_state, stack, &block, input) Ok(pipeline_data) => {
} else { let config = engine_state.get_config();
eval_block::<WithoutDebug>(engine_state, stack, &block, input) let result;
}?; if let PipelineData::ExternalStream {
stdout: stream,
stderr: stderr_stream,
exit_code,
..
} = pipeline_data
{
result = print_if_stream(stream, stderr_stream, false, exit_code);
} else if let Some(hook) = config.hooks.display_output.clone() {
match eval_hook(engine_state, stack, Some(pipeline_data), vec![], &hook) {
Err(err) => {
result = Err(err);
}
Ok(val) => {
result = val.print(engine_state, stack, false, false);
}
}
} else {
result = pipeline_data.print(engine_state, stack, false, false);
}
if let PipelineData::ByteStream(..) = pipeline { match result {
pipeline.print(engine_state, stack, false, false) Err(err) => {
} else if let Some(hook) = engine_state.get_config().hooks.display_output.clone() { let working_set = StateWorkingSet::new(engine_state);
let pipeline = eval_hook(
engine_state,
stack,
Some(pipeline),
vec![],
&hook,
"display_output",
)?;
pipeline.print(engine_state, stack, false, false)
} else {
pipeline.print(engine_state, stack, true, false)
}?;
Ok(false) report_error(&working_set, &err);
return false;
}
Ok(exit_code) => {
set_last_exit_code(stack, exit_code);
}
}
// reset vt processing, aka ansi because illbehaved externals can break it
#[cfg(windows)]
{
let _ = enable_vt_processing();
}
}
Err(err) => {
set_last_exit_code(stack, 1);
let working_set = StateWorkingSet::new(engine_state);
report_error(&working_set, &err);
return false;
}
}
true
}
fn set_last_exit_code(stack: &mut Stack, exit_code: i64) {
stack.add_env_var(
"LAST_EXIT_CODE".to_string(),
Value::Int {
val: exit_code,
span: Span { start: 0, end: 0 },
},
);
}
pub fn report_error(
working_set: &StateWorkingSet,
error: &(dyn miette::Diagnostic + Send + Sync + 'static),
) {
eprintln!("Error: {:?}", CliError(error, working_set));
// reset vt processing, aka ansi because illbehaved externals can break it
#[cfg(windows)]
{
let _ = nu_utils::enable_vt_processing();
}
}
pub fn report_error_new(
engine_state: &EngineState,
error: &(dyn miette::Diagnostic + Send + Sync + 'static),
) {
let working_set = StateWorkingSet::new(engine_state);
report_error(&working_set, error);
}
pub fn get_init_cwd() -> PathBuf {
match std::env::current_dir() {
Ok(cwd) => cwd,
Err(_) => match std::env::var("PWD") {
Ok(cwd) => PathBuf::from(cwd),
Err(_) => match nu_path::home_dir() {
Some(cwd) => cwd,
None => PathBuf::new(),
},
},
}
}
pub fn get_guaranteed_cwd(engine_state: &EngineState, stack: &Stack) -> PathBuf {
match nu_engine::env::current_dir(engine_state, stack) {
Ok(p) => p,
Err(e) => {
let working_set = StateWorkingSet::new(engine_state);
report_error(&working_set, &e);
get_init_cwd()
}
}
} }
#[cfg(test)] #[cfg(test)]
@ -322,10 +363,16 @@ mod test {
let env = engine_state.render_env_vars(); let env = engine_state.render_env_vars();
assert!(matches!(env.get("FOO"), Some(&Value::String { val, .. }) if val == "foo")); assert!(
assert!(matches!(env.get("SYMBOLS"), Some(&Value::String { val, .. }) if val == symbols)); matches!(env.get(&"FOO".to_string()), Some(&Value::String { val, .. }) if val == "foo")
assert!(matches!(env.get(symbols), Some(&Value::String { val, .. }) if val == "symbols")); );
assert!(env.contains_key("PWD")); assert!(
matches!(env.get(&"SYMBOLS".to_string()), Some(&Value::String { val, .. }) if val == symbols)
);
assert!(
matches!(env.get(&symbols.to_string()), Some(&Value::String { val, .. }) if val == "symbols")
);
assert!(env.get(&"PWD".to_string()).is_some());
assert_eq!(env.len(), 4); assert_eq!(env.len(), 4);
} }
} }

View File

@ -1,24 +1,17 @@
use nu_parser::parse; use nu_parser::{parse, ParseError};
use nu_protocol::{ use nu_protocol::engine::{EngineState, StateWorkingSet};
engine::{EngineState, StateWorkingSet},
ParseError,
};
use reedline::{ValidationResult, Validator}; use reedline::{ValidationResult, Validator};
use std::sync::Arc;
pub struct NuValidator { pub struct NuValidator {
pub engine_state: Arc<EngineState>, pub engine_state: EngineState,
} }
impl Validator for NuValidator { impl Validator for NuValidator {
fn validate(&self, line: &str) -> ValidationResult { fn validate(&self, line: &str) -> ValidationResult {
let mut working_set = StateWorkingSet::new(&self.engine_state); let mut working_set = StateWorkingSet::new(&self.engine_state);
parse(&mut working_set, None, line.as_bytes(), false); let (_, err) = parse(&mut working_set, None, line.as_bytes(), false, &[]);
if matches!( if matches!(err, Some(ParseError::UnexpectedEof(..))) {
working_set.parse_errors.first(),
Some(ParseError::UnexpectedEof(..))
) {
ValidationResult::Incomplete ValidationResult::Incomplete
} else { } else {
ValidationResult::Complete ValidationResult::Complete

View File

@ -1,7 +0,0 @@
use nu_test_support::nu;
#[test]
fn not_empty() {
let result = nu!("keybindings list | is-not-empty");
assert_eq!(result.out, "true");
}

View File

@ -1,2 +0,0 @@
mod keybindings_list;
mod nu_highlight;

View File

@ -1,7 +0,0 @@
use nu_test_support::nu;
#[test]
fn nu_highlight_not_expr() {
let actual = nu!("'not false' | nu-highlight | ansi strip");
assert_eq!(actual.out, "not false");
}

View File

@ -0,0 +1,734 @@
pub mod support;
use nu_cli::NuCompleter;
use nu_parser::parse;
use nu_protocol::engine::StateWorkingSet;
use reedline::{Completer, Suggestion};
use rstest::{fixture, rstest};
use support::{file, folder, match_suggestions, new_engine};
#[fixture]
fn completer() -> NuCompleter {
// Create a new engine
let (dir, _, mut engine, mut stack) = new_engine();
// Add record value as example
let record = "def tst [--mod -s] {}";
assert!(support::merge_input(record.as_bytes(), &mut engine, &mut stack, dir).is_ok());
// Instantiate a new completer
NuCompleter::new(std::sync::Arc::new(engine), stack)
}
#[fixture]
fn completer_strings() -> NuCompleter {
// Create a new engine
let (dir, _, mut engine, mut stack) = new_engine();
// Add record value as example
let record = r#"def animals [] { ["cat", "dog", "eel" ] }
def my-command [animal: string@animals] { print $animal }"#;
assert!(support::merge_input(record.as_bytes(), &mut engine, &mut stack, dir).is_ok());
// Instantiate a new completer
NuCompleter::new(std::sync::Arc::new(engine), stack)
}
#[test]
fn variables_dollar_sign_with_varialblecompletion() {
let (_, _, engine, stack) = new_engine();
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
let target_dir = "$ ";
let suggestions = completer.complete(target_dir, target_dir.len());
assert_eq!(7, suggestions.len());
}
#[rstest]
fn variables_double_dash_argument_with_flagcompletion(mut completer: NuCompleter) {
let suggestions = completer.complete("tst --", 6);
let expected: Vec<String> = vec!["--help".into(), "--mod".into()];
// dbg!(&expected, &suggestions);
match_suggestions(expected, suggestions);
}
#[rstest]
fn variables_single_dash_argument_with_flagcompletion(mut completer: NuCompleter) {
let suggestions = completer.complete("tst -", 5);
let expected: Vec<String> = vec!["--help".into(), "--mod".into(), "-h".into(), "-s".into()];
match_suggestions(expected, suggestions);
}
#[rstest]
fn variables_command_with_commandcompletion(mut completer_strings: NuCompleter) {
let suggestions = completer_strings.complete("my-c ", 4);
let expected: Vec<String> = vec!["my-command".into()];
match_suggestions(expected, suggestions);
}
#[rstest]
fn variables_subcommands_with_customcompletion(mut completer_strings: NuCompleter) {
let suggestions = completer_strings.complete("my-command ", 11);
let expected: Vec<String> = vec!["cat".into(), "dog".into(), "eel".into()];
match_suggestions(expected, suggestions);
}
#[rstest]
fn variables_customcompletion_subcommands_with_customcompletion_2(
mut completer_strings: NuCompleter,
) {
let suggestions = completer_strings.complete("my-command ", 11);
let expected: Vec<String> = vec!["cat".into(), "dog".into(), "eel".into()];
match_suggestions(expected, suggestions);
}
#[test]
fn dotnu_completions() {
// Create a new engine
let (_, _, engine, stack) = new_engine();
// Instatiate a new completer
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
// Test source completion
let completion_str = "source-env ".to_string();
let suggestions = completer.complete(&completion_str, completion_str.len());
assert_eq!(1, suggestions.len());
assert_eq!("custom_completion.nu", suggestions.get(0).unwrap().value);
// Test use completion
let completion_str = "use ".to_string();
let suggestions = completer.complete(&completion_str, completion_str.len());
assert_eq!(1, suggestions.len());
assert_eq!("custom_completion.nu", suggestions.get(0).unwrap().value);
}
#[test]
#[ignore]
fn external_completer_trailing_space() {
// https://github.com/nushell/nushell/issues/6378
let block = "let external_completer = {|spans| $spans}";
let input = "gh alias ".to_string();
let suggestions = run_external_completion(block, &input);
assert_eq!(3, suggestions.len());
assert_eq!("gh", suggestions.get(0).unwrap().value);
assert_eq!("alias", suggestions.get(1).unwrap().value);
assert_eq!("", suggestions.get(2).unwrap().value);
}
#[test]
fn external_completer_no_trailing_space() {
let block = "let external_completer = {|spans| $spans}";
let input = "gh alias".to_string();
let suggestions = run_external_completion(block, &input);
assert_eq!(2, suggestions.len());
assert_eq!("gh", suggestions.get(0).unwrap().value);
assert_eq!("alias", suggestions.get(1).unwrap().value);
}
#[test]
fn external_completer_pass_flags() {
let block = "let external_completer = {|spans| $spans}";
let input = "gh api --".to_string();
let suggestions = run_external_completion(block, &input);
assert_eq!(3, suggestions.len());
assert_eq!("gh", suggestions.get(0).unwrap().value);
assert_eq!("api", suggestions.get(1).unwrap().value);
assert_eq!("--", suggestions.get(2).unwrap().value);
}
#[test]
fn file_completions() {
// Create a new engine
let (dir, dir_str, engine, stack) = new_engine();
// Instatiate a new completer
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
// Test completions for the current folder
let target_dir = format!("cp {}", dir_str);
let suggestions = completer.complete(&target_dir, target_dir.len());
// Create the expected values
let expected_paths: Vec<String> = vec![
file(dir.join("nushell")),
folder(dir.join("test_a")),
folder(dir.join("test_b")),
folder(dir.join("another")),
file(dir.join("custom_completion.nu")),
file(dir.join(".hidden_file")),
folder(dir.join(".hidden_folder")),
];
// Match the results
match_suggestions(expected_paths, suggestions);
// Test completions for a file
let target_dir = format!("cp {}", folder(dir.join("another")));
let suggestions = completer.complete(&target_dir, target_dir.len());
// Create the expected values
let expected_paths: Vec<String> = vec![file(dir.join("another").join("newfile"))];
// Match the results
match_suggestions(expected_paths, suggestions);
}
#[test]
fn command_ls_with_filecompletion() {
let (_, _, engine, stack) = new_engine();
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
let target_dir = "ls ";
let suggestions = completer.complete(target_dir, target_dir.len());
#[cfg(windows)]
let expected_paths: Vec<String> = vec![
"nushell".to_string(),
"test_a\\".to_string(),
"test_b\\".to_string(),
"another\\".to_string(),
"custom_completion.nu".to_string(),
".hidden_file".to_string(),
".hidden_folder\\".to_string(),
];
#[cfg(not(windows))]
let expected_paths: Vec<String> = vec![
"nushell".to_string(),
"test_a/".to_string(),
"test_b/".to_string(),
"another/".to_string(),
"custom_completion.nu".to_string(),
".hidden_file".to_string(),
".hidden_folder/".to_string(),
];
match_suggestions(expected_paths, suggestions)
}
#[test]
fn command_open_with_filecompletion() {
let (_, _, engine, stack) = new_engine();
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
let target_dir = "open ";
let suggestions = completer.complete(target_dir, target_dir.len());
#[cfg(windows)]
let expected_paths: Vec<String> = vec![
"nushell".to_string(),
"test_a\\".to_string(),
"test_b\\".to_string(),
"another\\".to_string(),
"custom_completion.nu".to_string(),
".hidden_file".to_string(),
".hidden_folder\\".to_string(),
];
#[cfg(not(windows))]
let expected_paths: Vec<String> = vec![
"nushell".to_string(),
"test_a/".to_string(),
"test_b/".to_string(),
"another/".to_string(),
"custom_completion.nu".to_string(),
".hidden_file".to_string(),
".hidden_folder/".to_string(),
];
match_suggestions(expected_paths, suggestions)
}
#[test]
fn command_rm_with_globcompletion() {
let (_, _, engine, stack) = new_engine();
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
let target_dir = "rm ";
let suggestions = completer.complete(target_dir, target_dir.len());
#[cfg(windows)]
let expected_paths: Vec<String> = vec![
"nushell".to_string(),
"test_a\\".to_string(),
"test_b\\".to_string(),
"another\\".to_string(),
"custom_completion.nu".to_string(),
".hidden_file".to_string(),
".hidden_folder\\".to_string(),
];
#[cfg(not(windows))]
let expected_paths: Vec<String> = vec![
"nushell".to_string(),
"test_a/".to_string(),
"test_b/".to_string(),
"another/".to_string(),
"custom_completion.nu".to_string(),
".hidden_file".to_string(),
".hidden_folder/".to_string(),
];
match_suggestions(expected_paths, suggestions)
}
#[test]
fn command_cp_with_globcompletion() {
let (_, _, engine, stack) = new_engine();
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
let target_dir = "cp ";
let suggestions = completer.complete(target_dir, target_dir.len());
#[cfg(windows)]
let expected_paths: Vec<String> = vec![
"nushell".to_string(),
"test_a\\".to_string(),
"test_b\\".to_string(),
"another\\".to_string(),
"custom_completion.nu".to_string(),
".hidden_file".to_string(),
".hidden_folder\\".to_string(),
];
#[cfg(not(windows))]
let expected_paths: Vec<String> = vec![
"nushell".to_string(),
"test_a/".to_string(),
"test_b/".to_string(),
"another/".to_string(),
"custom_completion.nu".to_string(),
".hidden_file".to_string(),
".hidden_folder/".to_string(),
];
match_suggestions(expected_paths, suggestions)
}
#[test]
fn command_save_with_filecompletion() {
let (_, _, engine, stack) = new_engine();
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
let target_dir = "save ";
let suggestions = completer.complete(target_dir, target_dir.len());
#[cfg(windows)]
let expected_paths: Vec<String> = vec![
"nushell".to_string(),
"test_a\\".to_string(),
"test_b\\".to_string(),
"another\\".to_string(),
"custom_completion.nu".to_string(),
".hidden_file".to_string(),
".hidden_folder\\".to_string(),
];
#[cfg(not(windows))]
let expected_paths: Vec<String> = vec![
"nushell".to_string(),
"test_a/".to_string(),
"test_b/".to_string(),
"another/".to_string(),
"custom_completion.nu".to_string(),
".hidden_file".to_string(),
".hidden_folder/".to_string(),
];
match_suggestions(expected_paths, suggestions)
}
#[test]
fn command_touch_with_filecompletion() {
let (_, _, engine, stack) = new_engine();
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
let target_dir = "touch ";
let suggestions = completer.complete(target_dir, target_dir.len());
#[cfg(windows)]
let expected_paths: Vec<String> = vec![
"nushell".to_string(),
"test_a\\".to_string(),
"test_b\\".to_string(),
"another\\".to_string(),
"custom_completion.nu".to_string(),
".hidden_file".to_string(),
".hidden_folder\\".to_string(),
];
#[cfg(not(windows))]
let expected_paths: Vec<String> = vec![
"nushell".to_string(),
"test_a/".to_string(),
"test_b/".to_string(),
"another/".to_string(),
"custom_completion.nu".to_string(),
".hidden_file".to_string(),
".hidden_folder/".to_string(),
];
match_suggestions(expected_paths, suggestions)
}
#[test]
fn command_watch_with_filecompletion() {
let (_, _, engine, stack) = new_engine();
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
let target_dir = "watch ";
let suggestions = completer.complete(target_dir, target_dir.len());
#[cfg(windows)]
let expected_paths: Vec<String> = vec![
"nushell".to_string(),
"test_a\\".to_string(),
"test_b\\".to_string(),
"another\\".to_string(),
"custom_completion.nu".to_string(),
".hidden_file".to_string(),
".hidden_folder\\".to_string(),
];
#[cfg(not(windows))]
let expected_paths: Vec<String> = vec![
"nushell".to_string(),
"test_a/".to_string(),
"test_b/".to_string(),
"another/".to_string(),
"custom_completion.nu".to_string(),
".hidden_file".to_string(),
".hidden_folder/".to_string(),
];
match_suggestions(expected_paths, suggestions)
}
#[test]
fn flag_completions() {
// Create a new engine
let (_, _, engine, stack) = new_engine();
// Instatiate a new completer
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
// Test completions for the 'ls' flags
let suggestions = completer.complete("ls -", 4);
assert_eq!(14, suggestions.len());
let expected: Vec<String> = vec![
"--all".into(),
"--directory".into(),
"--du".into(),
"--full-paths".into(),
"--help".into(),
"--long".into(),
"--short-names".into(),
"-D".into(),
"-a".into(),
"-d".into(),
"-f".into(),
"-h".into(),
"-l".into(),
"-s".into(),
];
// Match results
match_suggestions(expected, suggestions);
}
#[test]
fn folder_with_directorycompletions() {
// Create a new engine
let (dir, dir_str, engine, stack) = new_engine();
// Instatiate a new completer
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
// Test completions for the current folder
let target_dir = format!("cd {}", dir_str);
let suggestions = completer.complete(&target_dir, target_dir.len());
// Create the expected values
let expected_paths: Vec<String> = vec![
folder(dir.join("test_a")),
folder(dir.join("test_b")),
folder(dir.join("another")),
folder(dir.join(".hidden_folder")),
];
// Match the results
match_suggestions(expected_paths, suggestions);
}
#[test]
fn variables_completions() {
// Create a new engine
let (dir, _, mut engine, mut stack) = new_engine();
// Add record value as example
let record = "let actor = { name: 'Tom Hardy', age: 44 }";
assert!(support::merge_input(record.as_bytes(), &mut engine, &mut stack, dir).is_ok());
// Instatiate a new completer
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
// Test completions for $nu
let suggestions = completer.complete("$nu.", 4);
assert_eq!(9, suggestions.len());
let expected: Vec<String> = vec![
"config-path".into(),
"env-path".into(),
"history-path".into(),
"home-path".into(),
"loginshell-path".into(),
"os-info".into(),
"pid".into(),
"scope".into(),
"temp-path".into(),
];
// Match results
match_suggestions(expected, suggestions);
// Test completions for $nu.h (filter)
let suggestions = completer.complete("$nu.h", 5);
assert_eq!(2, suggestions.len());
let expected: Vec<String> = vec!["history-path".into(), "home-path".into()];
// Match results
match_suggestions(expected, suggestions);
// Test completions for custom var
let suggestions = completer.complete("$actor.", 7);
assert_eq!(2, suggestions.len());
let expected: Vec<String> = vec!["age".into(), "name".into()];
// Match results
match_suggestions(expected, suggestions);
// Test completions for custom var (filtering)
let suggestions = completer.complete("$actor.n", 8);
assert_eq!(1, suggestions.len());
let expected: Vec<String> = vec!["name".into()];
// Match results
match_suggestions(expected, suggestions);
// Test completions for $env
let suggestions = completer.complete("$env.", 5);
assert_eq!(2, suggestions.len());
let expected: Vec<String> = vec!["PWD".into(), "TEST".into()];
// Match results
match_suggestions(expected, suggestions);
// Test completions for $env
let suggestions = completer.complete("$env.T", 6);
assert_eq!(1, suggestions.len());
let expected: Vec<String> = vec!["TEST".into()];
// Match results
match_suggestions(expected, suggestions);
}
#[test]
fn alias_of_command_and_flags() {
let (dir, _, mut engine, mut stack) = new_engine();
// Create an alias
let alias = r#"alias ll = ls -l"#;
assert!(support::merge_input(alias.as_bytes(), &mut engine, &mut stack, dir).is_ok());
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
let suggestions = completer.complete("ll t", 4);
#[cfg(windows)]
let expected_paths: Vec<String> = vec!["test_a\\".to_string(), "test_b\\".to_string()];
#[cfg(not(windows))]
let expected_paths: Vec<String> = vec!["test_a/".to_string(), "test_b/".to_string()];
match_suggestions(expected_paths, suggestions)
}
#[test]
fn alias_of_basic_command() {
let (dir, _, mut engine, mut stack) = new_engine();
// Create an alias
let alias = r#"alias ll = ls "#;
assert!(support::merge_input(alias.as_bytes(), &mut engine, &mut stack, dir).is_ok());
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
let suggestions = completer.complete("ll t", 4);
#[cfg(windows)]
let expected_paths: Vec<String> = vec!["test_a\\".to_string(), "test_b\\".to_string()];
#[cfg(not(windows))]
let expected_paths: Vec<String> = vec!["test_a/".to_string(), "test_b/".to_string()];
match_suggestions(expected_paths, suggestions)
}
#[test]
fn alias_of_another_alias() {
let (dir, _, mut engine, mut stack) = new_engine();
// Create an alias
let alias = r#"alias ll = ls -la"#;
assert!(support::merge_input(alias.as_bytes(), &mut engine, &mut stack, dir.clone()).is_ok());
// Create the second alias
let alias = r#"alias lf = ll -f"#;
assert!(support::merge_input(alias.as_bytes(), &mut engine, &mut stack, dir).is_ok());
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
let suggestions = completer.complete("lf t", 4);
#[cfg(windows)]
let expected_paths: Vec<String> = vec!["test_a\\".to_string(), "test_b\\".to_string()];
#[cfg(not(windows))]
let expected_paths: Vec<String> = vec!["test_a/".to_string(), "test_b/".to_string()];
match_suggestions(expected_paths, suggestions)
}
fn run_external_completion(block: &str, input: &str) -> Vec<Suggestion> {
// Create a new engine
let (dir, _, mut engine_state, mut stack) = new_engine();
let (_, delta) = {
let mut working_set = StateWorkingSet::new(&engine_state);
let (block, err) = parse(&mut working_set, None, block.as_bytes(), false, &[]);
assert!(err.is_none());
(block, working_set.render())
};
assert!(engine_state.merge_delta(delta).is_ok());
// Merge environment into the permanent state
assert!(engine_state.merge_env(&mut stack, &dir).is_ok());
let latest_block_id = engine_state.num_blocks() - 1;
// Change config adding the external completer
let mut config = engine_state.get_config().clone();
config.external_completer = Some(latest_block_id);
engine_state.set_config(&config);
// Instatiate a new completer
let mut completer = NuCompleter::new(std::sync::Arc::new(engine_state), stack);
completer.complete(input, input.len())
}
#[test]
fn unknown_command_completion() {
let (_, _, engine, stack) = new_engine();
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
let target_dir = "thiscommanddoesnotexist ";
let suggestions = completer.complete(target_dir, target_dir.len());
#[cfg(windows)]
let expected_paths: Vec<String> = vec![
"nushell".to_string(),
"test_a\\".to_string(),
"test_b\\".to_string(),
"another\\".to_string(),
"custom_completion.nu".to_string(),
".hidden_file".to_string(),
".hidden_folder\\".to_string(),
];
#[cfg(not(windows))]
let expected_paths: Vec<String> = vec![
"nushell".to_string(),
"test_a/".to_string(),
"test_b/".to_string(),
"another/".to_string(),
"custom_completion.nu".to_string(),
".hidden_file".to_string(),
".hidden_folder/".to_string(),
];
match_suggestions(expected_paths, suggestions)
}
#[rstest]
fn flagcompletion_triggers_after_cursor(mut completer: NuCompleter) {
let suggestions = completer.complete("tst -h", 5);
let expected: Vec<String> = vec!["--help".into(), "--mod".into(), "-h".into(), "-s".into()];
match_suggestions(expected, suggestions);
}
#[rstest]
fn customcompletion_triggers_after_cursor(mut completer_strings: NuCompleter) {
let suggestions = completer_strings.complete("my-command c", 11);
let expected: Vec<String> = vec!["cat".into(), "dog".into(), "eel".into()];
match_suggestions(expected, suggestions);
}
#[rstest]
fn customcompletion_triggers_after_cursor_piped(mut completer_strings: NuCompleter) {
let suggestions = completer_strings.complete("my-command c | ls", 11);
let expected: Vec<String> = vec!["cat".into(), "dog".into(), "eel".into()];
match_suggestions(expected, suggestions);
}
#[rstest]
fn flagcompletion_triggers_after_cursor_piped(mut completer: NuCompleter) {
let suggestions = completer.complete("tst -h | ls", 5);
let expected: Vec<String> = vec!["--help".into(), "--mod".into(), "-h".into(), "-s".into()];
match_suggestions(expected, suggestions);
}
#[test]
fn filecompletions_triggers_after_cursor() {
let (_, _, engine, stack) = new_engine();
let mut completer = NuCompleter::new(std::sync::Arc::new(engine), stack);
let suggestions = completer.complete("cp test_c", 3);
#[cfg(windows)]
let expected_paths: Vec<String> = vec![
"nushell".to_string(),
"test_a\\".to_string(),
"test_b\\".to_string(),
"another\\".to_string(),
"custom_completion.nu".to_string(),
".hidden_file".to_string(),
".hidden_folder\\".to_string(),
];
#[cfg(not(windows))]
let expected_paths: Vec<String> = vec![
"nushell".to_string(),
"test_a/".to_string(),
"test_b/".to_string(),
"another/".to_string(),
"custom_completion.nu".to_string(),
".hidden_file".to_string(),
".hidden_folder/".to_string(),
];
match_suggestions(expected_paths, suggestions);
}

File diff suppressed because it is too large Load Diff

View File

@ -1,249 +0,0 @@
use nu_engine::eval_block;
use nu_parser::parse;
use nu_path::{AbsolutePathBuf, PathBuf};
use nu_protocol::{
debugger::WithoutDebug,
engine::{EngineState, Stack, StateWorkingSet},
PipelineData, ShellError, Span, Value,
};
use nu_test_support::fs;
use reedline::Suggestion;
use std::path::MAIN_SEPARATOR;
fn create_default_context() -> EngineState {
nu_command::add_shell_command_context(nu_cmd_lang::create_default_context())
}
// creates a new engine with the current path into the completions fixtures folder
pub fn new_engine() -> (AbsolutePathBuf, String, EngineState, Stack) {
// Target folder inside assets
let dir = fs::fixtures().join("completions");
let dir_str = dir
.clone()
.into_os_string()
.into_string()
.unwrap_or_default();
// Create a new engine with default context
let mut engine_state = create_default_context();
// Add $nu
engine_state.generate_nu_constant();
// New stack
let mut stack = Stack::new();
// Add pwd as env var
stack.add_env_var(
"PWD".to_string(),
Value::string(dir_str.clone(), nu_protocol::Span::new(0, dir_str.len())),
);
stack.add_env_var(
"TEST".to_string(),
Value::string(
"NUSHELL".to_string(),
nu_protocol::Span::new(0, dir_str.len()),
),
);
#[cfg(windows)]
stack.add_env_var(
"Path".to_string(),
Value::string(
"c:\\some\\path;c:\\some\\other\\path".to_string(),
nu_protocol::Span::new(0, dir_str.len()),
),
);
#[cfg(not(windows))]
stack.add_env_var(
"PATH".to_string(),
Value::string(
"/some/path:/some/other/path".to_string(),
nu_protocol::Span::new(0, dir_str.len()),
),
);
// Merge environment into the permanent state
let merge_result = engine_state.merge_env(&mut stack);
assert!(merge_result.is_ok());
(dir, dir_str, engine_state, stack)
}
// creates a new engine with the current path into the completions fixtures folder
pub fn new_dotnu_engine() -> (AbsolutePathBuf, String, EngineState, Stack) {
// Target folder inside assets
let dir = fs::fixtures().join("dotnu_completions");
let dir_str = dir
.clone()
.into_os_string()
.into_string()
.unwrap_or_default();
let dir_span = nu_protocol::Span::new(0, dir_str.len());
// Create a new engine with default context
let mut engine_state = create_default_context();
// Add $nu
engine_state.generate_nu_constant();
// New stack
let mut stack = Stack::new();
// Add pwd as env var
stack.add_env_var("PWD".to_string(), Value::string(dir_str.clone(), dir_span));
stack.add_env_var(
"TEST".to_string(),
Value::string("NUSHELL".to_string(), dir_span),
);
stack.add_env_var(
"NU_LIB_DIRS".to_string(),
Value::List {
vals: vec![
Value::string(file(dir.join("lib-dir1")), dir_span),
Value::string(file(dir.join("lib-dir2")), dir_span),
Value::string(file(dir.join("lib-dir3")), dir_span),
],
internal_span: dir_span,
},
);
// Merge environment into the permanent state
let merge_result = engine_state.merge_env(&mut stack);
assert!(merge_result.is_ok());
(dir, dir_str, engine_state, stack)
}
pub fn new_quote_engine() -> (AbsolutePathBuf, String, EngineState, Stack) {
// Target folder inside assets
let dir = fs::fixtures().join("quoted_completions");
let dir_str = dir
.clone()
.into_os_string()
.into_string()
.unwrap_or_default();
// Create a new engine with default context
let mut engine_state = create_default_context();
// New stack
let mut stack = Stack::new();
// Add pwd as env var
stack.add_env_var(
"PWD".to_string(),
Value::string(dir_str.clone(), nu_protocol::Span::new(0, dir_str.len())),
);
stack.add_env_var(
"TEST".to_string(),
Value::string(
"NUSHELL".to_string(),
nu_protocol::Span::new(0, dir_str.len()),
),
);
// Merge environment into the permanent state
let merge_result = engine_state.merge_env(&mut stack);
assert!(merge_result.is_ok());
(dir, dir_str, engine_state, stack)
}
pub fn new_partial_engine() -> (AbsolutePathBuf, String, EngineState, Stack) {
// Target folder inside assets
let dir = fs::fixtures().join("partial_completions");
let dir_str = dir
.clone()
.into_os_string()
.into_string()
.unwrap_or_default();
// Create a new engine with default context
let mut engine_state = create_default_context();
// New stack
let mut stack = Stack::new();
// Add pwd as env var
stack.add_env_var(
"PWD".to_string(),
Value::string(dir_str.clone(), nu_protocol::Span::new(0, dir_str.len())),
);
stack.add_env_var(
"TEST".to_string(),
Value::string(
"NUSHELL".to_string(),
nu_protocol::Span::new(0, dir_str.len()),
),
);
// Merge environment into the permanent state
let merge_result = engine_state.merge_env(&mut stack);
assert!(merge_result.is_ok());
(dir, dir_str, engine_state, stack)
}
// match a list of suggestions with the expected values
pub fn match_suggestions(expected: &Vec<String>, suggestions: &Vec<Suggestion>) {
let expected_len = expected.len();
let suggestions_len = suggestions.len();
if expected_len != suggestions_len {
panic!(
"\nexpected {expected_len} suggestions but got {suggestions_len}: \n\
Suggestions: {suggestions:#?} \n\
Expected: {expected:#?}\n"
)
}
let suggestoins_str = suggestions
.iter()
.map(|it| it.value.clone())
.collect::<Vec<_>>();
assert_eq!(expected, &suggestoins_str);
}
// append the separator to the converted path
pub fn folder(path: impl Into<PathBuf>) -> String {
let mut converted_path = file(path);
converted_path.push(MAIN_SEPARATOR);
converted_path
}
// convert a given path to string
pub fn file(path: impl Into<PathBuf>) -> String {
path.into().into_os_string().into_string().unwrap()
}
// merge_input executes the given input into the engine
// and merges the state
pub fn merge_input(
input: &[u8],
engine_state: &mut EngineState,
stack: &mut Stack,
) -> Result<(), ShellError> {
let (block, delta) = {
let mut working_set = StateWorkingSet::new(engine_state);
let block = parse(&mut working_set, None, input, false);
assert!(working_set.parse_errors.is_empty());
(block, working_set.render())
};
engine_state.merge_delta(delta)?;
assert!(eval_block::<WithoutDebug>(
engine_state,
stack,
&block,
PipelineData::Value(Value::nothing(Span::unknown()), None),
)
.is_ok());
// Merge environment into the permanent state
engine_state.merge_env(stack)
}

View File

@ -1,2 +0,0 @@
mod commands;
mod completions;

View File

@ -0,0 +1,126 @@
use std::path::PathBuf;
use nu_command::create_default_context;
use nu_engine::eval_block;
use nu_parser::parse;
use nu_protocol::{
engine::{EngineState, Stack, StateWorkingSet},
PipelineData, ShellError, Span, Value,
};
use nu_test_support::fs;
use reedline::Suggestion;
const SEP: char = std::path::MAIN_SEPARATOR;
// creates a new engine with the current path into the completions fixtures folder
pub fn new_engine() -> (PathBuf, String, EngineState, Stack) {
// Target folder inside assets
let dir = fs::fixtures().join("completions");
let mut dir_str = dir
.clone()
.into_os_string()
.into_string()
.unwrap_or_default();
dir_str.push(SEP);
// Create a new engine with default context
let mut engine_state = create_default_context();
// New stack
let mut stack = Stack::new();
// Add pwd as env var
stack.add_env_var(
"PWD".to_string(),
Value::String {
val: dir_str.clone(),
span: nu_protocol::Span {
start: 0,
end: dir_str.len(),
},
},
);
stack.add_env_var(
"TEST".to_string(),
Value::String {
val: "NUSHELL".to_string(),
span: nu_protocol::Span {
start: 0,
end: dir_str.len(),
},
},
);
// Merge environment into the permanent state
let merge_result = engine_state.merge_env(&mut stack, &dir);
assert!(merge_result.is_ok());
(dir, dir_str, engine_state, stack)
}
// match a list of suggestions with the expected values
pub fn match_suggestions(expected: Vec<String>, suggestions: Vec<Suggestion>) {
let expected_len = expected.len();
let suggestions_len = suggestions.len();
if expected_len != suggestions_len {
panic!(
"\nexpected {expected_len} suggestions but got {suggestions_len}: \n\
Suggestions: {suggestions:#?} \n\
Expected: {expected:#?}\n"
)
}
expected.iter().zip(suggestions).for_each(|it| {
assert_eq!(it.0, &it.1.value);
});
}
// append the separator to the converted path
pub fn folder(path: PathBuf) -> String {
let mut converted_path = file(path);
converted_path.push(SEP);
converted_path
}
// convert a given path to string
pub fn file(path: PathBuf) -> String {
path.into_os_string().into_string().unwrap_or_default()
}
// merge_input executes the given input into the engine
// and merges the state
pub fn merge_input(
input: &[u8],
engine_state: &mut EngineState,
stack: &mut Stack,
dir: PathBuf,
) -> Result<(), ShellError> {
let (block, delta) = {
let mut working_set = StateWorkingSet::new(engine_state);
let (block, err) = parse(&mut working_set, None, input, false, &[]);
assert!(err.is_none());
(block, working_set.render())
};
engine_state.merge_delta(delta)?;
assert!(eval_block(
engine_state,
stack,
&block,
PipelineData::Value(
Value::Nothing {
span: Span { start: 0, end: 0 },
},
None
),
false,
false
)
.is_ok());
// Merge environment into the permanent state
engine_state.merge_env(stack, &dir)
}

View File

@ -1,24 +0,0 @@
[package]
authors = ["The Nushell Project Developers"]
description = "The foundation tools to build Nushell commands."
edition = "2021"
license = "MIT"
name = "nu-cmd-base"
repository = "https://github.com/nushell/nushell/tree/main/crates/nu-cmd-base"
version = "0.99.1"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lints]
workspace = true
[dependencies]
nu-engine = { path = "../nu-engine", version = "0.99.1" }
nu-parser = { path = "../nu-parser", version = "0.99.1" }
nu-path = { path = "../nu-path", version = "0.99.1" }
nu-protocol = { path = "../nu-protocol", version = "0.99.1" }
indexmap = { workspace = true }
miette = { workspace = true }
[dev-dependencies]

View File

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2019 - 2023 The Nushell Project Developers
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,5 +0,0 @@
Utilities used by the different `nu-command`/`nu-cmd-*` crates, should not contain any full `Command` implementations.
## Internal Nushell crate
This crate implements components of Nushell and is not designed to support plugin authors or other users directly.

View File

@ -1 +0,0 @@
pub mod to;

View File

@ -1,20 +0,0 @@
use indexmap::{indexset, IndexSet};
use nu_protocol::Value;
pub fn merge_descriptors(values: &[Value]) -> Vec<String> {
let mut ret: Vec<String> = vec![];
let mut seen: IndexSet<String> = indexset! {};
for value in values {
let data_descriptors = match value {
Value::Record { val, .. } => val.columns().cloned().collect(),
_ => vec!["".to_string()],
};
for desc in data_descriptors {
if !desc.is_empty() && !seen.contains(&desc) {
seen.insert(desc.to_string());
ret.push(desc.to_string());
}
}
}
ret
}

View File

@ -1 +0,0 @@
pub mod delimited;

View File

@ -1,346 +0,0 @@
use miette::Result;
use nu_engine::{eval_block, eval_block_with_early_return};
use nu_parser::parse;
use nu_protocol::{
cli_error::{report_parse_error, report_shell_error},
debugger::WithoutDebug,
engine::{Closure, EngineState, Stack, StateWorkingSet},
PipelineData, PositionalArg, ShellError, Span, Type, Value, VarId,
};
use std::sync::Arc;
pub fn eval_env_change_hook(
env_change_hook: Option<Value>,
engine_state: &mut EngineState,
stack: &mut Stack,
) -> Result<(), ShellError> {
if let Some(hook) = env_change_hook {
match hook {
Value::Record { val, .. } => {
for (env_name, hook_value) in &*val {
let before = engine_state.previous_env_vars.get(env_name);
let after = stack.get_env_var(engine_state, env_name);
if before != after {
let before = before.cloned().unwrap_or_default();
let after = after.cloned().unwrap_or_default();
eval_hook(
engine_state,
stack,
None,
vec![("$before".into(), before), ("$after".into(), after.clone())],
hook_value,
"env_change",
)?;
Arc::make_mut(&mut engine_state.previous_env_vars)
.insert(env_name.clone(), after);
}
}
}
x => {
return Err(ShellError::TypeMismatch {
err_message: "record for the 'env_change' hook".to_string(),
span: x.span(),
});
}
}
}
Ok(())
}
pub fn eval_hook(
engine_state: &mut EngineState,
stack: &mut Stack,
input: Option<PipelineData>,
arguments: Vec<(String, Value)>,
value: &Value,
hook_name: &str,
) -> Result<PipelineData, ShellError> {
let mut output = PipelineData::empty();
let span = value.span();
match value {
Value::String { val, .. } => {
let (block, delta, vars) = {
let mut working_set = StateWorkingSet::new(engine_state);
let mut vars: Vec<(VarId, Value)> = vec![];
for (name, val) in arguments {
let var_id = working_set.add_variable(
name.as_bytes().to_vec(),
val.span(),
Type::Any,
false,
);
vars.push((var_id, val));
}
let output = parse(
&mut working_set,
Some(&format!("{hook_name} hook")),
val.as_bytes(),
false,
);
if let Some(err) = working_set.parse_errors.first() {
report_parse_error(&working_set, err);
return Err(ShellError::GenericError {
error: format!("Failed to run {hook_name} hook"),
msg: "source code has errors".into(),
span: Some(span),
help: None,
inner: Vec::new(),
});
}
(output, working_set.render(), vars)
};
engine_state.merge_delta(delta)?;
let input = if let Some(input) = input {
input
} else {
PipelineData::empty()
};
let var_ids: Vec<VarId> = vars
.into_iter()
.map(|(var_id, val)| {
stack.add_var(var_id, val);
var_id
})
.collect();
match eval_block::<WithoutDebug>(engine_state, stack, &block, input) {
Ok(pipeline_data) => {
output = pipeline_data;
}
Err(err) => {
report_shell_error(engine_state, &err);
}
}
for var_id in var_ids.iter() {
stack.remove_var(*var_id);
}
}
Value::List { vals, .. } => {
for val in vals {
eval_hook(
engine_state,
stack,
None,
arguments.clone(),
val,
&format!("{hook_name} list, recursive"),
)?;
}
}
Value::Record { val, .. } => {
// Hooks can optionally be a record in this form:
// {
// condition: {|before, after| ... } # block that evaluates to true/false
// code: # block or a string
// }
// The condition block will be run to check whether the main hook (in `code`) should be run.
// If it returns true (the default if a condition block is not specified), the hook should be run.
let do_run_hook = if let Some(condition) = val.get("condition") {
let other_span = condition.span();
if let Ok(closure) = condition.as_closure() {
match run_hook(
engine_state,
stack,
closure,
None,
arguments.clone(),
other_span,
) {
Ok(pipeline_data) => {
if let PipelineData::Value(Value::Bool { val, .. }, ..) = pipeline_data
{
val
} else {
return Err(ShellError::RuntimeTypeMismatch {
expected: Type::Bool,
actual: pipeline_data.get_type(),
span: pipeline_data.span().unwrap_or(other_span),
});
}
}
Err(err) => {
return Err(err);
}
}
} else {
return Err(ShellError::RuntimeTypeMismatch {
expected: Type::Closure,
actual: condition.get_type(),
span: other_span,
});
}
} else {
// always run the hook
true
};
if do_run_hook {
let Some(follow) = val.get("code") else {
return Err(ShellError::CantFindColumn {
col_name: "code".into(),
span: Some(span),
src_span: span,
});
};
let source_span = follow.span();
match follow {
Value::String { val, .. } => {
let (block, delta, vars) = {
let mut working_set = StateWorkingSet::new(engine_state);
let mut vars: Vec<(VarId, Value)> = vec![];
for (name, val) in arguments {
let var_id = working_set.add_variable(
name.as_bytes().to_vec(),
val.span(),
Type::Any,
false,
);
vars.push((var_id, val));
}
let output = parse(
&mut working_set,
Some(&format!("{hook_name} hook")),
val.as_bytes(),
false,
);
if let Some(err) = working_set.parse_errors.first() {
report_parse_error(&working_set, err);
return Err(ShellError::GenericError {
error: format!("Failed to run {hook_name} hook"),
msg: "source code has errors".into(),
span: Some(span),
help: None,
inner: Vec::new(),
});
}
(output, working_set.render(), vars)
};
engine_state.merge_delta(delta)?;
let input = PipelineData::empty();
let var_ids: Vec<VarId> = vars
.into_iter()
.map(|(var_id, val)| {
stack.add_var(var_id, val);
var_id
})
.collect();
match eval_block::<WithoutDebug>(engine_state, stack, &block, input) {
Ok(pipeline_data) => {
output = pipeline_data;
}
Err(err) => {
report_shell_error(engine_state, &err);
}
}
for var_id in var_ids.iter() {
stack.remove_var(*var_id);
}
}
Value::Closure { val, .. } => {
run_hook(engine_state, stack, val, input, arguments, source_span)?;
}
other => {
return Err(ShellError::RuntimeTypeMismatch {
expected: Type::custom("string or closure"),
actual: other.get_type(),
span: source_span,
});
}
}
}
}
Value::Closure { val, .. } => {
output = run_hook(engine_state, stack, val, input, arguments, span)?;
}
other => {
return Err(ShellError::RuntimeTypeMismatch {
expected: Type::custom("string, closure, record, or list"),
actual: other.get_type(),
span: other.span(),
});
}
}
engine_state.merge_env(stack)?;
Ok(output)
}
fn run_hook(
engine_state: &EngineState,
stack: &mut Stack,
closure: &Closure,
optional_input: Option<PipelineData>,
arguments: Vec<(String, Value)>,
span: Span,
) -> Result<PipelineData, ShellError> {
let block = engine_state.get_block(closure.block_id);
let input = optional_input.unwrap_or_else(PipelineData::empty);
let mut callee_stack = stack
.captures_to_stack_preserve_out_dest(closure.captures.clone())
.reset_pipes();
for (idx, PositionalArg { var_id, .. }) in
block.signature.required_positional.iter().enumerate()
{
if let Some(var_id) = var_id {
if let Some(arg) = arguments.get(idx) {
callee_stack.add_var(*var_id, arg.1.clone())
} else {
return Err(ShellError::IncompatibleParametersSingle {
msg: "This hook block has too many parameters".into(),
span,
});
}
}
}
let pipeline_data = eval_block_with_early_return::<WithoutDebug>(
engine_state,
&mut callee_stack,
block,
input,
)?;
if let PipelineData::Value(Value::Error { error, .. }, _) = pipeline_data {
return Err(*error);
}
// If all went fine, preserve the environment of the called block
let caller_env_vars = stack.get_env_var_names(engine_state);
// remove env vars that are present in the caller but not in the callee
// (the callee hid them)
for var in caller_env_vars.iter() {
if !callee_stack.has_env_var(engine_state, var) {
stack.remove_env_var(engine_state, var);
}
}
// add new env vars from callee to caller
for (var, value) in callee_stack.get_stack_env_vars() {
stack.add_env_var(var, value);
}
Ok(pipeline_data)
}

View File

@ -1,5 +0,0 @@
#![doc = include_str!("../README.md")]
pub mod formats;
pub mod hook;
pub mod input_handler;
pub mod util;

View File

@ -1,96 +0,0 @@
use nu_protocol::{
engine::{EngineState, Stack},
Range, ShellError, Span, Value,
};
use std::ops::Bound;
type MakeRangeError = fn(&str, Span) -> ShellError;
/// Returns a inclusive pair of boundary in given `range`.
pub fn process_range(range: &Range) -> Result<(isize, isize), MakeRangeError> {
match range {
Range::IntRange(range) => {
let start = range.start().try_into().unwrap_or(0);
let end = match range.end() {
Bound::Included(v) => v as isize,
Bound::Excluded(v) => (v - 1) as isize,
Bound::Unbounded => isize::MAX,
};
Ok((start, end))
}
Range::FloatRange(_) => Err(|msg, span| ShellError::TypeMismatch {
err_message: msg.to_string(),
span,
}),
}
}
const HELP_MSG: &str = "Nushell's config file can be found with the command: $nu.config-path. \
For more help: (https://nushell.sh/book/configuration.html#configurations-with-built-in-commands)";
fn get_editor_commandline(
value: &Value,
var_name: &str,
) -> Result<(String, Vec<String>), ShellError> {
match value {
Value::String { val, .. } if !val.is_empty() => Ok((val.to_string(), Vec::new())),
Value::List { vals, .. } if !vals.is_empty() => {
let mut editor_cmd = vals.iter().map(|l| l.coerce_string());
match editor_cmd.next().transpose()? {
Some(editor) if !editor.is_empty() => {
let params = editor_cmd.collect::<Result<_, ShellError>>()?;
Ok((editor, params))
}
_ => Err(ShellError::GenericError {
error: "Editor executable is missing".into(),
msg: "Set the first element to an executable".into(),
span: Some(value.span()),
help: Some(HELP_MSG.into()),
inner: vec![],
}),
}
}
Value::String { .. } | Value::List { .. } => Err(ShellError::GenericError {
error: format!("{var_name} should be a non-empty string or list<String>"),
msg: "Specify an executable here".into(),
span: Some(value.span()),
help: Some(HELP_MSG.into()),
inner: vec![],
}),
x => Err(ShellError::CantConvert {
to_type: "string or list<string>".into(),
from_type: x.get_type().to_string(),
span: value.span(),
help: None,
}),
}
}
pub fn get_editor(
engine_state: &EngineState,
stack: &Stack,
span: Span,
) -> Result<(String, Vec<String>), ShellError> {
let config = engine_state.get_config();
let env_vars = stack.get_env_vars(engine_state);
if let Ok(buff_editor) =
get_editor_commandline(&config.buffer_editor, "$env.config.buffer_editor")
{
Ok(buff_editor)
} else if let Some(value) = env_vars.get("EDITOR") {
get_editor_commandline(value, "$env.EDITOR")
} else if let Some(value) = env_vars.get("VISUAL") {
get_editor_commandline(value, "$env.VISUAL")
} else {
Err(ShellError::GenericError {
error: "No editor configured".into(),
msg:
"Please specify one via `$env.config.buffer_editor` or `$env.EDITOR`/`$env.VISUAL`"
.into(),
span: Some(span),
help: Some(HELP_MSG.into()),
inner: vec![],
})
}
}

Some files were not shown because too many files have changed in this diff Show More